Merge pull request #5850 from TimeIncOSS/f-aws-config

provider/aws: Add support for AWSConfig service
This commit is contained in:
Radek Simko 2017-02-13 15:07:15 +00:00 committed by GitHub
commit c6b21d853a
17 changed files with 2647 additions and 0 deletions

View File

@ -27,6 +27,7 @@ import (
"github.com/aws/aws-sdk-go/service/codebuild"
"github.com/aws/aws-sdk-go/service/codecommit"
"github.com/aws/aws-sdk-go/service/codedeploy"
"github.com/aws/aws-sdk-go/service/configservice"
"github.com/aws/aws-sdk-go/service/databasemigrationservice"
"github.com/aws/aws-sdk-go/service/directoryservice"
"github.com/aws/aws-sdk-go/service/dynamodb"
@ -108,6 +109,7 @@ type AWSClient struct {
cloudwatchconn *cloudwatch.CloudWatch
cloudwatchlogsconn *cloudwatchlogs.CloudWatchLogs
cloudwatcheventsconn *cloudwatchevents.CloudWatchEvents
configconn *configservice.ConfigService
dmsconn *databasemigrationservice.DatabaseMigrationService
dsconn *directoryservice.DirectoryService
dynamodbconn *dynamodb.DynamoDB
@ -281,6 +283,7 @@ func (c *Config) Client() (interface{}, error) {
client.codecommitconn = codecommit.New(sess)
client.codebuildconn = codebuild.New(sess)
client.codedeployconn = codedeploy.New(sess)
client.configconn = configservice.New(sess)
client.dmsconn = databasemigrationservice.New(sess)
client.dsconn = directoryservice.New(sess)
client.dynamodbconn = dynamodb.New(dynamoSess)

View File

@ -235,6 +235,10 @@ func Provider() terraform.ResourceProvider {
"aws_cloudwatch_log_metric_filter": resourceAwsCloudWatchLogMetricFilter(),
"aws_cloudwatch_log_stream": resourceAwsCloudWatchLogStream(),
"aws_cloudwatch_log_subscription_filter": resourceAwsCloudwatchLogSubscriptionFilter(),
"aws_config_config_rule": resourceAwsConfigConfigRule(),
"aws_config_configuration_recorder": resourceAwsConfigConfigurationRecorder(),
"aws_config_configuration_recorder_status": resourceAwsConfigConfigurationRecorderStatus(),
"aws_config_delivery_channel": resourceAwsConfigDeliveryChannel(),
"aws_autoscaling_lifecycle_hook": resourceAwsAutoscalingLifecycleHook(),
"aws_cloudwatch_metric_alarm": resourceAwsCloudWatchMetricAlarm(),
"aws_codedeploy_app": resourceAwsCodeDeployApp(),

View File

@ -0,0 +1,301 @@
package aws
import (
"bytes"
"fmt"
"log"
"time"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/configservice"
)
func resourceAwsConfigConfigRule() *schema.Resource {
return &schema.Resource{
Create: resourceAwsConfigConfigRulePut,
Read: resourceAwsConfigConfigRuleRead,
Update: resourceAwsConfigConfigRulePut,
Delete: resourceAwsConfigConfigRuleDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateMaxLength(64),
},
"rule_id": {
Type: schema.TypeString,
Computed: true,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateMaxLength(256),
},
"input_parameters": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateJsonString,
},
"maximum_execution_frequency": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateConfigExecutionFrequency,
},
"scope": {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"compliance_resource_id": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateMaxLength(256),
},
"compliance_resource_types": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 100,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validateMaxLength(256),
},
Set: schema.HashString,
},
"tag_key": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateMaxLength(128),
},
"tag_value": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateMaxLength(256),
},
},
},
},
"source": {
Type: schema.TypeList,
MaxItems: 1,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"owner": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateConfigRuleSourceOwner,
},
"source_detail": {
Type: schema.TypeSet,
Set: configRuleSourceDetailsHash,
Optional: true,
MaxItems: 25,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"event_source": {
Type: schema.TypeString,
Optional: true,
},
"maximum_execution_frequency": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateConfigExecutionFrequency,
},
"message_type": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"source_identifier": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateMaxLength(256),
},
},
},
},
},
}
}
func resourceAwsConfigConfigRulePut(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
name := d.Get("name").(string)
ruleInput := configservice.ConfigRule{
ConfigRuleName: aws.String(name),
Source: expandConfigRuleSource(d.Get("source").([]interface{})),
}
scopes := d.Get("scope").([]interface{})
if len(scopes) > 0 {
ruleInput.Scope = expandConfigRuleScope(scopes[0].(map[string]interface{}))
}
if v, ok := d.GetOk("description"); ok {
ruleInput.Description = aws.String(v.(string))
}
if v, ok := d.GetOk("input_parameters"); ok {
ruleInput.InputParameters = aws.String(v.(string))
}
if v, ok := d.GetOk("maximum_execution_frequency"); ok {
ruleInput.MaximumExecutionFrequency = aws.String(v.(string))
}
input := configservice.PutConfigRuleInput{
ConfigRule: &ruleInput,
}
log.Printf("[DEBUG] Creating AWSConfig config rule: %s", input)
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
_, err := conn.PutConfigRule(&input)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == "InsufficientPermissionsException" {
// IAM is eventually consistent
return resource.RetryableError(err)
}
}
return resource.NonRetryableError(fmt.Errorf("Failed to create AWSConfig rule: %s", err))
}
return nil
})
if err != nil {
return err
}
d.SetId(name)
log.Printf("[DEBUG] AWSConfig config rule %q created", name)
return resourceAwsConfigConfigRuleRead(d, meta)
}
func resourceAwsConfigConfigRuleRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
out, err := conn.DescribeConfigRules(&configservice.DescribeConfigRulesInput{
ConfigRuleNames: []*string{aws.String(d.Id())},
})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchConfigRuleException" {
log.Printf("[WARN] Config Rule %q is gone (NoSuchConfigRuleException)", d.Id())
d.SetId("")
return nil
}
return err
}
numberOfRules := len(out.ConfigRules)
if numberOfRules < 1 {
log.Printf("[WARN] Config Rule %q is gone (no rules found)", d.Id())
d.SetId("")
return nil
}
if numberOfRules > 1 {
return fmt.Errorf("Expected exactly 1 Config Rule, received %d: %#v",
numberOfRules, out.ConfigRules)
}
log.Printf("[DEBUG] AWS Config config rule received: %s", out)
rule := out.ConfigRules[0]
d.Set("arn", rule.ConfigRuleArn)
d.Set("rule_id", rule.ConfigRuleId)
d.Set("name", rule.ConfigRuleName)
d.Set("description", rule.Description)
d.Set("input_parameters", rule.InputParameters)
d.Set("maximum_execution_frequency", rule.MaximumExecutionFrequency)
if rule.Scope != nil {
d.Set("scope", flattenConfigRuleScope(rule.Scope))
}
d.Set("source", flattenConfigRuleSource(rule.Source))
return nil
}
func resourceAwsConfigConfigRuleDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
name := d.Get("name").(string)
log.Printf("[DEBUG] Deleting AWS Config config rule %q", name)
_, err := conn.DeleteConfigRule(&configservice.DeleteConfigRuleInput{
ConfigRuleName: aws.String(name),
})
if err != nil {
return fmt.Errorf("Deleting Config Rule failed: %s", err)
}
conf := resource.StateChangeConf{
Pending: []string{
configservice.ConfigRuleStateActive,
configservice.ConfigRuleStateDeleting,
configservice.ConfigRuleStateDeletingResults,
configservice.ConfigRuleStateEvaluating,
},
Target: []string{""},
Timeout: 5 * time.Minute,
Refresh: func() (interface{}, string, error) {
out, err := conn.DescribeConfigRules(&configservice.DescribeConfigRulesInput{
ConfigRuleNames: []*string{aws.String(d.Id())},
})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchConfigRuleException" {
return 42, "", nil
}
return 42, "", fmt.Errorf("Failed to describe config rule %q: %s", d.Id(), err)
}
if len(out.ConfigRules) < 1 {
return 42, "", nil
}
rule := out.ConfigRules[0]
return out, *rule.ConfigRuleState, nil
},
}
_, err = conf.WaitForState()
if err != nil {
return err
}
log.Printf("[DEBUG] AWS Config config rule %q deleted", name)
d.SetId("")
return nil
}
func configRuleSourceDetailsHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if v, ok := m["message_type"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
if v, ok := m["event_source"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
if v, ok := m["maximum_execution_frequency"]; ok {
buf.WriteString(fmt.Sprintf("%s-", v.(string)))
}
return hashcode.String(buf.String())
}

View File

@ -0,0 +1,473 @@
package aws
import (
"fmt"
"regexp"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/configservice"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAWSConfigConfigRule_basic(t *testing.T) {
var cr configservice.ConfigRule
rInt := acctest.RandInt()
expectedName := fmt.Sprintf("tf-acc-test-%d", rInt)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigConfigRuleDestroy,
Steps: []resource.TestStep{
{
Config: testAccConfigConfigRuleConfig_basic(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckConfigConfigRuleExists("aws_config_config_rule.foo", &cr),
testAccCheckConfigConfigRuleName("aws_config_config_rule.foo", expectedName, &cr),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "name", expectedName),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.#", "1"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.0.owner", "AWS"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.0.source_identifier", "S3_BUCKET_VERSIONING_ENABLED"),
),
},
},
})
}
func TestAccAWSConfigConfigRule_ownerAws(t *testing.T) {
var cr configservice.ConfigRule
rInt := acctest.RandInt()
expectedName := fmt.Sprintf("tf-acc-test-%d", rInt)
expectedArn := regexp.MustCompile("arn:aws:config:[a-z0-9-]+:[0-9]{12}:config-rule/config-rule-([a-z0-9]+)")
expectedRuleId := regexp.MustCompile("config-rule-[a-z0-9]+")
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigConfigRuleDestroy,
Steps: []resource.TestStep{
{
Config: testAccConfigConfigRuleConfig_ownerAws(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckConfigConfigRuleExists("aws_config_config_rule.foo", &cr),
testAccCheckConfigConfigRuleName("aws_config_config_rule.foo", expectedName, &cr),
resource.TestMatchResourceAttr("aws_config_config_rule.foo", "arn", expectedArn),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "name", expectedName),
resource.TestMatchResourceAttr("aws_config_config_rule.foo", "rule_id", expectedRuleId),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "description", "Terraform Acceptance tests"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.#", "1"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.0.owner", "AWS"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.0.source_identifier", "REQUIRED_TAGS"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.0.source_detail.#", "0"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "scope.#", "1"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "scope.0.compliance_resource_id", "blablah"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "scope.0.compliance_resource_types.#", "1"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "scope.0.compliance_resource_types.3865728585", "AWS::EC2::Instance"),
),
},
},
})
}
func TestAccAWSConfigConfigRule_customlambda(t *testing.T) {
var cr configservice.ConfigRule
rInt := acctest.RandInt()
expectedName := fmt.Sprintf("tf-acc-test-%d", rInt)
path := "test-fixtures/lambdatest.zip"
expectedArn := regexp.MustCompile("arn:aws:config:[a-z0-9-]+:[0-9]{12}:config-rule/config-rule-([a-z0-9]+)")
expectedFunctionArn := regexp.MustCompile(fmt.Sprintf("arn:aws:lambda:[a-z0-9-]+:[0-9]{12}:function:tf_acc_lambda_awsconfig_%d", rInt))
expectedRuleId := regexp.MustCompile("config-rule-[a-z0-9]+")
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigConfigRuleDestroy,
Steps: []resource.TestStep{
{
Config: testAccConfigConfigRuleConfig_customLambda(rInt, path),
Check: resource.ComposeTestCheckFunc(
testAccCheckConfigConfigRuleExists("aws_config_config_rule.foo", &cr),
testAccCheckConfigConfigRuleName("aws_config_config_rule.foo", expectedName, &cr),
resource.TestMatchResourceAttr("aws_config_config_rule.foo", "arn", expectedArn),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "name", expectedName),
resource.TestMatchResourceAttr("aws_config_config_rule.foo", "rule_id", expectedRuleId),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "description", "Terraform Acceptance tests"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "maximum_execution_frequency", "Six_Hours"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.#", "1"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.0.owner", "CUSTOM_LAMBDA"),
resource.TestMatchResourceAttr("aws_config_config_rule.foo", "source.0.source_identifier", expectedFunctionArn),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.0.source_detail.#", "1"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.0.source_detail.3026922761.event_source", "aws.config"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.0.source_detail.3026922761.message_type", "ConfigurationSnapshotDeliveryCompleted"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "source.0.source_detail.3026922761.maximum_execution_frequency", ""),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "scope.#", "1"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "scope.0.tag_key", "IsTemporary"),
resource.TestCheckResourceAttr("aws_config_config_rule.foo", "scope.0.tag_value", "yes"),
),
},
},
})
}
func TestAccAWSConfigConfigRule_importAws(t *testing.T) {
resourceName := "aws_config_config_rule.foo"
rInt := acctest.RandInt()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigConfigRuleDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccConfigConfigRuleConfig_ownerAws(rInt),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func TestAccAWSConfigConfigRule_importLambda(t *testing.T) {
resourceName := "aws_config_config_rule.foo"
rInt := acctest.RandInt()
path := "test-fixtures/lambdatest.zip"
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigConfigRuleDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccConfigConfigRuleConfig_customLambda(rInt, path),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func testAccCheckConfigConfigRuleName(n, desired string, obj *configservice.ConfigRule) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.Attributes["name"] != *obj.ConfigRuleName {
return fmt.Errorf("Expected name: %q, given: %q", desired, *obj.ConfigRuleName)
}
return nil
}
}
func testAccCheckConfigConfigRuleExists(n string, obj *configservice.ConfigRule) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not Found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No config rule ID is set")
}
conn := testAccProvider.Meta().(*AWSClient).configconn
out, err := conn.DescribeConfigRules(&configservice.DescribeConfigRulesInput{
ConfigRuleNames: []*string{aws.String(rs.Primary.Attributes["name"])},
})
if err != nil {
return fmt.Errorf("Failed to describe config rule: %s", err)
}
if len(out.ConfigRules) < 1 {
return fmt.Errorf("No config rule found when describing %q", rs.Primary.Attributes["name"])
}
cr := out.ConfigRules[0]
*obj = *cr
return nil
}
}
func testAccCheckConfigConfigRuleDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).configconn
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_config_config_rule" {
continue
}
resp, err := conn.DescribeConfigRules(&configservice.DescribeConfigRulesInput{
ConfigRuleNames: []*string{aws.String(rs.Primary.Attributes["name"])},
})
if err == nil {
if len(resp.ConfigRules) != 0 &&
*resp.ConfigRules[0].ConfigRuleName == rs.Primary.Attributes["name"] {
return fmt.Errorf("config rule still exists: %s", rs.Primary.Attributes["name"])
}
}
}
return nil
}
func testAccConfigConfigRuleConfig_basic(randInt int) string {
return fmt.Sprintf(`
resource "aws_config_config_rule" "foo" {
name = "tf-acc-test-%d"
source {
owner = "AWS"
source_identifier = "S3_BUCKET_VERSIONING_ENABLED"
}
depends_on = ["aws_config_configuration_recorder.foo"]
}
resource "aws_config_configuration_recorder" "foo" {
name = "tf-acc-test-%d"
role_arn = "${aws_iam_role.r.arn}"
}
resource "aws_iam_role" "r" {
name = "tf-acc-test-awsconfig-%d"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_iam_role_policy" "p" {
name = "tf-acc-test-awsconfig-%d"
role = "${aws_iam_role.r.id}"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "config:Put*",
"Effect": "Allow",
"Resource": "*"
}
]
}
EOF
}`, randInt, randInt, randInt, randInt)
}
func testAccConfigConfigRuleConfig_ownerAws(randInt int) string {
return fmt.Sprintf(`
resource "aws_config_config_rule" "foo" {
name = "tf-acc-test-%d"
description = "Terraform Acceptance tests"
source {
owner = "AWS"
source_identifier = "REQUIRED_TAGS"
}
scope {
compliance_resource_id = "blablah"
compliance_resource_types = ["AWS::EC2::Instance"]
}
input_parameters = <<PARAMS
{"tag1Key":"CostCenter", "tag2Key":"Owner"}
PARAMS
depends_on = ["aws_config_configuration_recorder.foo"]
}
resource "aws_config_configuration_recorder" "foo" {
name = "tf-acc-test-%d"
role_arn = "${aws_iam_role.r.arn}"
}
resource "aws_iam_role" "r" {
name = "tf-acc-test-awsconfig-%d"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_iam_role_policy" "p" {
name = "tf-acc-test-awsconfig-%d"
role = "${aws_iam_role.r.id}"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "config:Put*",
"Effect": "Allow",
"Resource": "*"
}
]
}
EOF
}`, randInt, randInt, randInt, randInt)
}
func testAccConfigConfigRuleConfig_customLambda(randInt int, path string) string {
return fmt.Sprintf(`
resource "aws_config_config_rule" "foo" {
name = "tf-acc-test-%d"
description = "Terraform Acceptance tests"
maximum_execution_frequency = "Six_Hours"
source {
owner = "CUSTOM_LAMBDA"
source_identifier = "${aws_lambda_function.f.arn}"
source_detail {
event_source = "aws.config"
message_type = "ConfigurationSnapshotDeliveryCompleted"
}
}
scope {
tag_key = "IsTemporary"
tag_value = "yes"
}
depends_on = [
"aws_config_configuration_recorder.foo",
"aws_config_delivery_channel.foo",
]
}
resource "aws_lambda_function" "f" {
filename = "%s"
function_name = "tf_acc_lambda_awsconfig_%d"
role = "${aws_iam_role.iam_for_lambda.arn}"
handler = "exports.example"
runtime = "nodejs4.3"
}
resource "aws_lambda_permission" "p" {
statement_id = "AllowExecutionFromConfig"
action = "lambda:InvokeFunction"
function_name = "${aws_lambda_function.f.arn}"
principal = "config.amazonaws.com"
}
resource "aws_iam_role" "iam_for_lambda" {
name = "tf_acc_lambda_aws_config_%d"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
POLICY
}
resource "aws_iam_role_policy_attachment" "a" {
role = "${aws_iam_role.iam_for_lambda.name}"
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSConfigRulesExecutionRole"
}
resource "aws_config_delivery_channel" "foo" {
name = "tf-acc-test-%d"
s3_bucket_name = "${aws_s3_bucket.b.bucket}"
snapshot_delivery_properties {
delivery_frequency = "Six_Hours"
}
depends_on = ["aws_config_configuration_recorder.foo"]
}
resource "aws_s3_bucket" "b" {
bucket = "tf-acc-awsconfig-%d"
force_destroy = true
}
resource "aws_config_configuration_recorder" "foo" {
name = "tf-acc-test-%d"
role_arn = "${aws_iam_role.r.arn}"
}
resource "aws_iam_role" "r" {
name = "tf-acc-test-awsconfig-%d"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
POLICY
}
resource "aws_iam_role_policy" "p" {
name = "tf-acc-test-awsconfig-%d"
role = "${aws_iam_role.r.id}"
policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "config:Put*",
"Effect": "Allow",
"Resource": "*"
},
{
"Action": "s3:*",
"Effect": "Allow",
"Resource": [
"${aws_s3_bucket.b.arn}",
"${aws_s3_bucket.b.arn}/*"
]
},
{
"Action": "lambda:*",
"Effect": "Allow",
"Resource": "${aws_lambda_function.f.arn}"
}
]
}
POLICY
}`, randInt, path, randInt, randInt, randInt, randInt, randInt, randInt, randInt)
}

View File

@ -0,0 +1,148 @@
package aws
import (
"fmt"
"log"
"github.com/hashicorp/terraform/helper/schema"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/configservice"
)
func resourceAwsConfigConfigurationRecorder() *schema.Resource {
return &schema.Resource{
Create: resourceAwsConfigConfigurationRecorderPut,
Read: resourceAwsConfigConfigurationRecorderRead,
Update: resourceAwsConfigConfigurationRecorderPut,
Delete: resourceAwsConfigConfigurationRecorderDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Default: "default",
ValidateFunc: validateMaxLength(256),
},
"role_arn": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateArn,
},
"recording_group": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"all_supported": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
"include_global_resource_types": {
Type: schema.TypeBool,
Optional: true,
},
"resource_types": {
Type: schema.TypeSet,
Set: schema.HashString,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
}
}
func resourceAwsConfigConfigurationRecorderPut(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
name := d.Get("name").(string)
recorder := configservice.ConfigurationRecorder{
Name: aws.String(name),
RoleARN: aws.String(d.Get("role_arn").(string)),
}
if g, ok := d.GetOk("recording_group"); ok {
recorder.RecordingGroup = expandConfigRecordingGroup(g.([]interface{}))
}
input := configservice.PutConfigurationRecorderInput{
ConfigurationRecorder: &recorder,
}
_, err := conn.PutConfigurationRecorder(&input)
if err != nil {
return fmt.Errorf("Creating Configuration Recorder failed: %s", err)
}
d.SetId(name)
return resourceAwsConfigConfigurationRecorderRead(d, meta)
}
func resourceAwsConfigConfigurationRecorderRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
input := configservice.DescribeConfigurationRecordersInput{
ConfigurationRecorderNames: []*string{aws.String(d.Id())},
}
out, err := conn.DescribeConfigurationRecorders(&input)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoSuchConfigurationRecorderException" {
log.Printf("[WARN] Configuration Recorder %q is gone (NoSuchConfigurationRecorderException)", d.Id())
d.SetId("")
return nil
}
return fmt.Errorf("Getting Configuration Recorder failed: %s", err)
}
numberOfRecorders := len(out.ConfigurationRecorders)
if numberOfRecorders < 1 {
log.Printf("[WARN] Configuration Recorder %q is gone (no recorders found)", d.Id())
d.SetId("")
return nil
}
if numberOfRecorders > 1 {
return fmt.Errorf("Expected exactly 1 Configuration Recorder, received %d: %#v",
numberOfRecorders, out.ConfigurationRecorders)
}
recorder := out.ConfigurationRecorders[0]
d.Set("name", recorder.Name)
d.Set("role_arn", recorder.RoleARN)
if recorder.RecordingGroup != nil {
flattened := flattenConfigRecordingGroup(recorder.RecordingGroup)
err = d.Set("recording_group", flattened)
if err != nil {
return fmt.Errorf("Failed to set recording_group: %s", err)
}
}
return nil
}
func resourceAwsConfigConfigurationRecorderDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
input := configservice.DeleteConfigurationRecorderInput{
ConfigurationRecorderName: aws.String(d.Id()),
}
_, err := conn.DeleteConfigurationRecorder(&input)
if err != nil {
return fmt.Errorf("Deleting Configuration Recorder failed: %s", err)
}
d.SetId("")
return nil
}

View File

@ -0,0 +1,122 @@
package aws
import (
"fmt"
"log"
"github.com/hashicorp/terraform/helper/schema"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/configservice"
)
func resourceAwsConfigConfigurationRecorderStatus() *schema.Resource {
return &schema.Resource{
Create: resourceAwsConfigConfigurationRecorderStatusPut,
Read: resourceAwsConfigConfigurationRecorderStatusRead,
Update: resourceAwsConfigConfigurationRecorderStatusPut,
Delete: resourceAwsConfigConfigurationRecorderStatusDelete,
Importer: &schema.ResourceImporter{
State: func(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
d.Set("name", d.Id())
return []*schema.ResourceData{d}, nil
},
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"is_enabled": {
Type: schema.TypeBool,
Required: true,
},
},
}
}
func resourceAwsConfigConfigurationRecorderStatusPut(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
name := d.Get("name").(string)
d.SetId(name)
if d.HasChange("is_enabled") {
isEnabled := d.Get("is_enabled").(bool)
if isEnabled {
log.Printf("[DEBUG] Starting AWSConfig Configuration recorder %q", name)
startInput := configservice.StartConfigurationRecorderInput{
ConfigurationRecorderName: aws.String(name),
}
_, err := conn.StartConfigurationRecorder(&startInput)
if err != nil {
return fmt.Errorf("Failed to start Configuration Recorder: %s", err)
}
} else {
log.Printf("[DEBUG] Stopping AWSConfig Configuration recorder %q", name)
stopInput := configservice.StopConfigurationRecorderInput{
ConfigurationRecorderName: aws.String(name),
}
_, err := conn.StopConfigurationRecorder(&stopInput)
if err != nil {
return fmt.Errorf("Failed to stop Configuration Recorder: %s", err)
}
}
}
return resourceAwsConfigConfigurationRecorderStatusRead(d, meta)
}
func resourceAwsConfigConfigurationRecorderStatusRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
name := d.Id()
statusInput := configservice.DescribeConfigurationRecorderStatusInput{
ConfigurationRecorderNames: []*string{aws.String(name)},
}
statusOut, err := conn.DescribeConfigurationRecorderStatus(&statusInput)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == "NoSuchConfigurationRecorderException" {
log.Printf("[WARN] Configuration Recorder (status) %q is gone (NoSuchConfigurationRecorderException)", name)
d.SetId("")
return nil
}
}
return fmt.Errorf("Failed describing Configuration Recorder %q status: %s",
name, err)
}
numberOfStatuses := len(statusOut.ConfigurationRecordersStatus)
if numberOfStatuses < 1 {
log.Printf("[WARN] Configuration Recorder (status) %q is gone (no recorders found)", name)
d.SetId("")
return nil
}
if numberOfStatuses > 1 {
return fmt.Errorf("Expected exactly 1 Configuration Recorder (status), received %d: %#v",
numberOfStatuses, statusOut.ConfigurationRecordersStatus)
}
d.Set("is_enabled", statusOut.ConfigurationRecordersStatus[0].Recording)
return nil
}
func resourceAwsConfigConfigurationRecorderStatusDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
input := configservice.StopConfigurationRecorderInput{
ConfigurationRecorderName: aws.String(d.Get("name").(string)),
}
_, err := conn.StopConfigurationRecorder(&input)
if err != nil {
return fmt.Errorf("Stopping Configuration Recorder failed: %s", err)
}
d.SetId("")
return nil
}

View File

@ -0,0 +1,235 @@
package aws
import (
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/configservice"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAWSConfigConfigurationRecorderStatus_basic(t *testing.T) {
var cr configservice.ConfigurationRecorder
var crs configservice.ConfigurationRecorderStatus
rInt := acctest.RandInt()
expectedName := fmt.Sprintf("tf-acc-test-%d", rInt)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigConfigurationRecorderStatusDestroy,
Steps: []resource.TestStep{
{
Config: testAccConfigConfigurationRecorderStatusConfig(rInt, false),
Check: resource.ComposeTestCheckFunc(
testAccCheckConfigConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr),
testAccCheckConfigConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs),
testAccCheckConfigConfigurationRecorderStatus("aws_config_configuration_recorder_status.foo", false, &crs),
resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "is_enabled", "false"),
resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "name", expectedName),
),
},
},
})
}
func TestAccAWSConfigConfigurationRecorderStatus_startEnabled(t *testing.T) {
var cr configservice.ConfigurationRecorder
var crs configservice.ConfigurationRecorderStatus
rInt := acctest.RandInt()
expectedName := fmt.Sprintf("tf-acc-test-%d", rInt)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigConfigurationRecorderStatusDestroy,
Steps: []resource.TestStep{
{
Config: testAccConfigConfigurationRecorderStatusConfig(rInt, true),
Check: resource.ComposeTestCheckFunc(
testAccCheckConfigConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr),
testAccCheckConfigConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs),
testAccCheckConfigConfigurationRecorderStatus("aws_config_configuration_recorder_status.foo", true, &crs),
resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "is_enabled", "true"),
resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "name", expectedName),
),
},
{
Config: testAccConfigConfigurationRecorderStatusConfig(rInt, false),
Check: resource.ComposeTestCheckFunc(
testAccCheckConfigConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr),
testAccCheckConfigConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs),
testAccCheckConfigConfigurationRecorderStatus("aws_config_configuration_recorder_status.foo", false, &crs),
resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "is_enabled", "false"),
resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "name", expectedName),
),
},
{
Config: testAccConfigConfigurationRecorderStatusConfig(rInt, true),
Check: resource.ComposeTestCheckFunc(
testAccCheckConfigConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr),
testAccCheckConfigConfigurationRecorderStatusExists("aws_config_configuration_recorder_status.foo", &crs),
testAccCheckConfigConfigurationRecorderStatus("aws_config_configuration_recorder_status.foo", true, &crs),
resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "is_enabled", "true"),
resource.TestCheckResourceAttr("aws_config_configuration_recorder_status.foo", "name", expectedName),
),
},
},
})
}
func TestAccAWSConfigConfigurationRecorderStatus_importBasic(t *testing.T) {
resourceName := "aws_config_configuration_recorder_status.foo"
rInt := acctest.RandInt()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigConfigurationRecorderStatusDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccConfigConfigurationRecorderStatusConfig(rInt, true),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func testAccCheckConfigConfigurationRecorderStatusExists(n string, obj *configservice.ConfigurationRecorderStatus) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
conn := testAccProvider.Meta().(*AWSClient).configconn
out, err := conn.DescribeConfigurationRecorderStatus(&configservice.DescribeConfigurationRecorderStatusInput{
ConfigurationRecorderNames: []*string{aws.String(rs.Primary.Attributes["name"])},
})
if err != nil {
return fmt.Errorf("Failed to describe status of configuration recorder: %s", err)
}
if len(out.ConfigurationRecordersStatus) < 1 {
return fmt.Errorf("Configuration Recorder %q not found", rs.Primary.Attributes["name"])
}
status := out.ConfigurationRecordersStatus[0]
*obj = *status
return nil
}
}
func testAccCheckConfigConfigurationRecorderStatus(n string, desired bool, obj *configservice.ConfigurationRecorderStatus) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if *obj.Recording != desired {
return fmt.Errorf("Expected configuration recorder %q recording to be %t, given: %t",
n, desired, *obj.Recording)
}
return nil
}
}
func testAccCheckConfigConfigurationRecorderStatusDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).configconn
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_config_configuration_recorder_status" {
continue
}
resp, err := conn.DescribeConfigurationRecorderStatus(&configservice.DescribeConfigurationRecorderStatusInput{
ConfigurationRecorderNames: []*string{aws.String(rs.Primary.Attributes["name"])},
})
if err == nil {
if len(resp.ConfigurationRecordersStatus) != 0 &&
*resp.ConfigurationRecordersStatus[0].Name == rs.Primary.Attributes["name"] &&
*resp.ConfigurationRecordersStatus[0].Recording {
return fmt.Errorf("Configuration recorder is still recording: %s", rs.Primary.Attributes["name"])
}
}
}
return nil
}
func testAccConfigConfigurationRecorderStatusConfig(randInt int, enabled bool) string {
return fmt.Sprintf(`
resource "aws_config_configuration_recorder" "foo" {
name = "tf-acc-test-%d"
role_arn = "${aws_iam_role.r.arn}"
}
resource "aws_iam_role" "r" {
name = "tf-acc-test-awsconfig-%d"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
POLICY
}
resource "aws_iam_role_policy" "p" {
name = "tf-acc-test-awsconfig-%d"
role = "${aws_iam_role.r.id}"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:*"
],
"Effect": "Allow",
"Resource": [
"${aws_s3_bucket.b.arn}",
"${aws_s3_bucket.b.arn}/*"
]
}
]
}
EOF
}
resource "aws_s3_bucket" "b" {
bucket = "tf-acc-test-awsconfig-%d"
force_destroy = true
}
resource "aws_config_delivery_channel" "foo" {
name = "tf-acc-test-awsconfig-%d"
s3_bucket_name = "${aws_s3_bucket.b.bucket}"
}
resource "aws_config_configuration_recorder_status" "foo" {
name = "${aws_config_configuration_recorder.foo.name}"
is_enabled = %t
depends_on = ["aws_config_delivery_channel.foo"]
}
`, randInt, randInt, randInt, randInt, randInt, enabled)
}

View File

@ -0,0 +1,304 @@
package aws
import (
"fmt"
"regexp"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/configservice"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAWSConfigConfigurationRecorder_basic(t *testing.T) {
var cr configservice.ConfigurationRecorder
rInt := acctest.RandInt()
expectedName := fmt.Sprintf("tf-acc-test-%d", rInt)
expectedRoleName := fmt.Sprintf("tf-acc-test-awsconfig-%d", rInt)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigConfigurationRecorderDestroy,
Steps: []resource.TestStep{
{
Config: testAccConfigConfigurationRecorderConfig_basic(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckConfigConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr),
testAccCheckConfigConfigurationRecorderName("aws_config_configuration_recorder.foo", expectedName, &cr),
testAccCheckConfigConfigurationRecorderRoleArn("aws_config_configuration_recorder.foo",
regexp.MustCompile(`arn:aws:iam::[0-9]{12}:role/`+expectedRoleName), &cr),
resource.TestCheckResourceAttr("aws_config_configuration_recorder.foo", "name", expectedName),
resource.TestMatchResourceAttr("aws_config_configuration_recorder.foo", "role_arn",
regexp.MustCompile(`arn:aws:iam::[0-9]{12}:role/`+expectedRoleName)),
),
},
},
})
}
func TestAccAWSConfigConfigurationRecorder_allParams(t *testing.T) {
var cr configservice.ConfigurationRecorder
rInt := acctest.RandInt()
expectedName := fmt.Sprintf("tf-acc-test-%d", rInt)
expectedRoleName := fmt.Sprintf("tf-acc-test-awsconfig-%d", rInt)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigConfigurationRecorderDestroy,
Steps: []resource.TestStep{
{
Config: testAccConfigConfigurationRecorderConfig_allParams(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckConfigConfigurationRecorderExists("aws_config_configuration_recorder.foo", &cr),
testAccCheckConfigConfigurationRecorderName("aws_config_configuration_recorder.foo", expectedName, &cr),
testAccCheckConfigConfigurationRecorderRoleArn("aws_config_configuration_recorder.foo",
regexp.MustCompile(`arn:aws:iam::[0-9]{12}:role/`+expectedRoleName), &cr),
resource.TestCheckResourceAttr("aws_config_configuration_recorder.foo", "name", expectedName),
resource.TestMatchResourceAttr("aws_config_configuration_recorder.foo", "role_arn",
regexp.MustCompile(`arn:aws:iam::[0-9]{12}:role/`+expectedRoleName)),
resource.TestCheckResourceAttr("aws_config_configuration_recorder.foo", "recording_group.#", "1"),
resource.TestCheckResourceAttr("aws_config_configuration_recorder.foo", "recording_group.0.all_supported", "false"),
resource.TestCheckResourceAttr("aws_config_configuration_recorder.foo", "recording_group.0.include_global_resource_types", "false"),
resource.TestCheckResourceAttr("aws_config_configuration_recorder.foo", "recording_group.0.resource_types.#", "2"),
),
},
},
})
}
func TestAccAWSConfigConfigurationRecorder_importBasic(t *testing.T) {
resourceName := "aws_config_configuration_recorder.foo"
rInt := acctest.RandInt()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigConfigurationRecorderDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccConfigConfigurationRecorderConfig_basic(rInt),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func testAccCheckConfigConfigurationRecorderName(n string, desired string, obj *configservice.ConfigurationRecorder) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if *obj.Name != desired {
return fmt.Errorf("Expected configuration recorder %q name to be %q, given: %q",
n, desired, *obj.Name)
}
return nil
}
}
func testAccCheckConfigConfigurationRecorderRoleArn(n string, desired *regexp.Regexp, obj *configservice.ConfigurationRecorder) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if !desired.MatchString(*obj.RoleARN) {
return fmt.Errorf("Expected configuration recorder %q role ARN to match %q, given: %q",
n, desired.String(), *obj.RoleARN)
}
return nil
}
}
func testAccCheckConfigConfigurationRecorderExists(n string, obj *configservice.ConfigurationRecorder) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not Found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No configuration recorder ID is set")
}
conn := testAccProvider.Meta().(*AWSClient).configconn
out, err := conn.DescribeConfigurationRecorders(&configservice.DescribeConfigurationRecordersInput{
ConfigurationRecorderNames: []*string{aws.String(rs.Primary.Attributes["name"])},
})
if err != nil {
return fmt.Errorf("Failed to describe configuration recorder: %s", err)
}
if len(out.ConfigurationRecorders) < 1 {
return fmt.Errorf("No configuration recorder found when describing %q", rs.Primary.Attributes["name"])
}
cr := out.ConfigurationRecorders[0]
*obj = *cr
return nil
}
}
func testAccCheckConfigConfigurationRecorderDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).configconn
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_config_configuration_recorder_status" {
continue
}
resp, err := conn.DescribeConfigurationRecorders(&configservice.DescribeConfigurationRecordersInput{
ConfigurationRecorderNames: []*string{aws.String(rs.Primary.Attributes["name"])},
})
if err == nil {
if len(resp.ConfigurationRecorders) != 0 &&
*resp.ConfigurationRecorders[0].Name == rs.Primary.Attributes["name"] {
return fmt.Errorf("Configuration recorder still exists: %s", rs.Primary.Attributes["name"])
}
}
}
return nil
}
func testAccConfigConfigurationRecorderConfig_basic(randInt int) string {
return fmt.Sprintf(`
resource "aws_config_configuration_recorder" "foo" {
name = "tf-acc-test-%d"
role_arn = "${aws_iam_role.r.arn}"
}
resource "aws_iam_role" "r" {
name = "tf-acc-test-awsconfig-%d"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
POLICY
}
resource "aws_iam_role_policy" "p" {
name = "tf-acc-test-awsconfig-%d"
role = "${aws_iam_role.r.id}"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:*"
],
"Effect": "Allow",
"Resource": [
"${aws_s3_bucket.b.arn}",
"${aws_s3_bucket.b.arn}/*"
]
}
]
}
EOF
}
resource "aws_s3_bucket" "b" {
bucket = "tf-acc-test-awsconfig-%d"
force_destroy = true
}
resource "aws_config_delivery_channel" "foo" {
name = "tf-acc-test-awsconfig-%d"
s3_bucket_name = "${aws_s3_bucket.b.bucket}"
depends_on = ["aws_config_configuration_recorder.foo"]
}
`, randInt, randInt, randInt, randInt, randInt)
}
func testAccConfigConfigurationRecorderConfig_allParams(randInt int) string {
return fmt.Sprintf(`
resource "aws_config_configuration_recorder" "foo" {
name = "tf-acc-test-%d"
role_arn = "${aws_iam_role.r.arn}"
recording_group {
all_supported = false
include_global_resource_types = false
resource_types = ["AWS::EC2::Instance", "AWS::CloudTrail::Trail"]
}
}
resource "aws_iam_role" "r" {
name = "tf-acc-test-awsconfig-%d"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
POLICY
}
resource "aws_iam_role_policy" "p" {
name = "tf-acc-test-awsconfig-%d"
role = "${aws_iam_role.r.id}"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:*"
],
"Effect": "Allow",
"Resource": [
"${aws_s3_bucket.b.arn}",
"${aws_s3_bucket.b.arn}/*"
]
}
]
}
EOF
}
resource "aws_s3_bucket" "b" {
bucket = "tf-acc-test-awsconfig-%d"
force_destroy = true
}
resource "aws_config_delivery_channel" "foo" {
name = "tf-acc-test-awsconfig-%d"
s3_bucket_name = "${aws_s3_bucket.b.bucket}"
depends_on = ["aws_config_configuration_recorder.foo"]
}
`, randInt, randInt, randInt, randInt, randInt)
}

View File

@ -0,0 +1,171 @@
package aws
import (
"fmt"
"log"
"time"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/configservice"
)
func resourceAwsConfigDeliveryChannel() *schema.Resource {
return &schema.Resource{
Create: resourceAwsConfigDeliveryChannelPut,
Read: resourceAwsConfigDeliveryChannelRead,
Update: resourceAwsConfigDeliveryChannelPut,
Delete: resourceAwsConfigDeliveryChannelDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Default: "default",
ValidateFunc: validateMaxLength(256),
},
"s3_bucket_name": {
Type: schema.TypeString,
Required: true,
},
"s3_key_prefix": {
Type: schema.TypeString,
Optional: true,
},
"sns_topic_arn": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateArn,
},
"snapshot_delivery_properties": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"delivery_frequency": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateConfigExecutionFrequency,
},
},
},
},
},
}
}
func resourceAwsConfigDeliveryChannelPut(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
name := d.Get("name").(string)
channel := configservice.DeliveryChannel{
Name: aws.String(name),
S3BucketName: aws.String(d.Get("s3_bucket_name").(string)),
}
if v, ok := d.GetOk("s3_key_prefix"); ok {
channel.S3KeyPrefix = aws.String(v.(string))
}
if v, ok := d.GetOk("sns_topic_arn"); ok {
channel.SnsTopicARN = aws.String(v.(string))
}
if p, ok := d.GetOk("snapshot_delivery_properties"); ok {
propertiesBlocks := p.([]interface{})
block := propertiesBlocks[0].(map[string]interface{})
if v, ok := block["delivery_frequency"]; ok {
channel.ConfigSnapshotDeliveryProperties = &configservice.ConfigSnapshotDeliveryProperties{
DeliveryFrequency: aws.String(v.(string)),
}
}
}
input := configservice.PutDeliveryChannelInput{DeliveryChannel: &channel}
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
_, err := conn.PutDeliveryChannel(&input)
if err == nil {
return nil
}
awsErr, ok := err.(awserr.Error)
if ok && awsErr.Code() == "InsufficientDeliveryPolicyException" {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
})
if err != nil {
return fmt.Errorf("Creating Delivery Channel failed: %s", err)
}
d.SetId(name)
return resourceAwsConfigDeliveryChannelRead(d, meta)
}
func resourceAwsConfigDeliveryChannelRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
input := configservice.DescribeDeliveryChannelsInput{
DeliveryChannelNames: []*string{aws.String(d.Id())},
}
out, err := conn.DescribeDeliveryChannels(&input)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == "NoSuchDeliveryChannelException" {
log.Printf("[WARN] Delivery Channel %q is gone (NoSuchDeliveryChannelException)", d.Id())
d.SetId("")
return nil
}
}
return fmt.Errorf("Getting Delivery Channel failed: %s", err)
}
if len(out.DeliveryChannels) < 1 {
log.Printf("[WARN] Delivery Channel %q is gone (no channels found)", d.Id())
d.SetId("")
return nil
}
if len(out.DeliveryChannels) > 1 {
return fmt.Errorf("Received %d delivery channels under %s (expected exactly 1): %s",
len(out.DeliveryChannels), d.Id(), out.DeliveryChannels)
}
channel := out.DeliveryChannels[0]
d.Set("name", channel.Name)
d.Set("s3_bucket_name", channel.S3BucketName)
d.Set("s3_key_prefix", channel.S3KeyPrefix)
d.Set("sns_topic_arn", channel.SnsTopicARN)
if channel.ConfigSnapshotDeliveryProperties != nil {
d.Set("snapshot_delivery_properties", flattenConfigSnapshotDeliveryProperties(channel.ConfigSnapshotDeliveryProperties))
}
return nil
}
func resourceAwsConfigDeliveryChannelDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).configconn
input := configservice.DeleteDeliveryChannelInput{
DeliveryChannelName: aws.String(d.Id()),
}
_, err := conn.DeleteDeliveryChannel(&input)
if err != nil {
return fmt.Errorf("Unable to delete delivery channel: %s", err)
}
d.SetId("")
return nil
}

View File

@ -0,0 +1,279 @@
package aws
import (
"fmt"
"regexp"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/configservice"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAWSConfigDeliveryChannel_basic(t *testing.T) {
var dc configservice.DeliveryChannel
rInt := acctest.RandInt()
expectedName := fmt.Sprintf("tf-acc-test-awsconfig-%d", rInt)
expectedBucketName := fmt.Sprintf("tf-acc-test-awsconfig-%d", rInt)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigDeliveryChannelDestroy,
Steps: []resource.TestStep{
{
Config: testAccConfigDeliveryChannelConfig_basic(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckConfigDeliveryChannelExists("aws_config_delivery_channel.foo", &dc),
testAccCheckConfigDeliveryChannelName("aws_config_delivery_channel.foo", expectedName, &dc),
resource.TestCheckResourceAttr("aws_config_delivery_channel.foo", "name", expectedName),
resource.TestCheckResourceAttr("aws_config_delivery_channel.foo", "s3_bucket_name", expectedBucketName),
),
},
},
})
}
func TestAccAWSConfigDeliveryChannel_allParams(t *testing.T) {
var dc configservice.DeliveryChannel
rInt := acctest.RandInt()
expectedName := fmt.Sprintf("tf-acc-test-awsconfig-%d", rInt)
expectedBucketName := fmt.Sprintf("tf-acc-test-awsconfig-%d", rInt)
expectedSnsTopicArn := regexp.MustCompile(fmt.Sprintf("arn:aws:sns:[a-z0-9-]+:[0-9]{12}:tf-acc-test-%d", rInt))
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigDeliveryChannelDestroy,
Steps: []resource.TestStep{
{
Config: testAccConfigDeliveryChannelConfig_allParams(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckConfigDeliveryChannelExists("aws_config_delivery_channel.foo", &dc),
testAccCheckConfigDeliveryChannelName("aws_config_delivery_channel.foo", expectedName, &dc),
resource.TestCheckResourceAttr("aws_config_delivery_channel.foo", "name", expectedName),
resource.TestCheckResourceAttr("aws_config_delivery_channel.foo", "s3_bucket_name", expectedBucketName),
resource.TestCheckResourceAttr("aws_config_delivery_channel.foo", "s3_key_prefix", "one/two/three"),
resource.TestMatchResourceAttr("aws_config_delivery_channel.foo", "sns_topic_arn", expectedSnsTopicArn),
resource.TestCheckResourceAttr("aws_config_delivery_channel.foo", "snapshot_delivery_properties.0.delivery_frequency", "Six_Hours"),
),
},
},
})
}
func TestAccAWSConfigDeliveryChannel_importBasic(t *testing.T) {
resourceName := "aws_config_delivery_channel.foo"
rInt := acctest.RandInt()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckConfigDeliveryChannelDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccConfigDeliveryChannelConfig_basic(rInt),
},
resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
func testAccCheckConfigDeliveryChannelName(n, desired string, obj *configservice.DeliveryChannel) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if *obj.Name != desired {
return fmt.Errorf("Expected name: %q, given: %q", desired, *obj.Name)
}
return nil
}
}
func testAccCheckConfigDeliveryChannelExists(n string, obj *configservice.DeliveryChannel) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not Found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No delivery channel ID is set")
}
conn := testAccProvider.Meta().(*AWSClient).configconn
out, err := conn.DescribeDeliveryChannels(&configservice.DescribeDeliveryChannelsInput{
DeliveryChannelNames: []*string{aws.String(rs.Primary.Attributes["name"])},
})
if err != nil {
return fmt.Errorf("Failed to describe delivery channel: %s", err)
}
if len(out.DeliveryChannels) < 1 {
return fmt.Errorf("No delivery channel found when describing %q", rs.Primary.Attributes["name"])
}
dc := out.DeliveryChannels[0]
*obj = *dc
return nil
}
}
func testAccCheckConfigDeliveryChannelDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).configconn
for _, rs := range s.RootModule().Resources {
if rs.Type != "aws_config_delivery_channel" {
continue
}
resp, err := conn.DescribeDeliveryChannels(&configservice.DescribeDeliveryChannelsInput{
DeliveryChannelNames: []*string{aws.String(rs.Primary.Attributes["name"])},
})
if err == nil {
if len(resp.DeliveryChannels) != 0 &&
*resp.DeliveryChannels[0].Name == rs.Primary.Attributes["name"] {
return fmt.Errorf("Delivery Channel still exists: %s", rs.Primary.Attributes["name"])
}
}
}
return nil
}
func testAccConfigDeliveryChannelConfig_basic(randInt int) string {
return fmt.Sprintf(`
resource "aws_config_configuration_recorder" "foo" {
name = "tf-acc-test-%d"
role_arn = "${aws_iam_role.r.arn}"
}
resource "aws_iam_role" "r" {
name = "tf-acc-test-awsconfig-%d"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
POLICY
}
resource "aws_iam_role_policy" "p" {
name = "tf-acc-test-awsconfig-%d"
role = "${aws_iam_role.r.id}"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:*"
],
"Effect": "Allow",
"Resource": [
"${aws_s3_bucket.b.arn}",
"${aws_s3_bucket.b.arn}/*"
]
}
]
}
EOF
}
resource "aws_s3_bucket" "b" {
bucket = "tf-acc-test-awsconfig-%d"
force_destroy = true
}
resource "aws_config_delivery_channel" "foo" {
name = "tf-acc-test-awsconfig-%d"
s3_bucket_name = "${aws_s3_bucket.b.bucket}"
}`, randInt, randInt, randInt, randInt, randInt)
}
func testAccConfigDeliveryChannelConfig_allParams(randInt int) string {
return fmt.Sprintf(`
resource "aws_config_configuration_recorder" "foo" {
name = "tf-acc-test-%d"
role_arn = "${aws_iam_role.r.arn}"
}
resource "aws_iam_role" "r" {
name = "tf-acc-test-awsconfig-%d"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
POLICY
}
resource "aws_iam_role_policy" "p" {
name = "tf-acc-test-awsconfig-%d"
role = "${aws_iam_role.r.id}"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:*"
],
"Effect": "Allow",
"Resource": [
"${aws_s3_bucket.b.arn}",
"${aws_s3_bucket.b.arn}/*"
]
}
]
}
EOF
}
resource "aws_s3_bucket" "b" {
bucket = "tf-acc-test-awsconfig-%d"
force_destroy = true
}
resource "aws_sns_topic" "t" {
name = "tf-acc-test-%d"
}
resource "aws_config_delivery_channel" "foo" {
name = "tf-acc-test-awsconfig-%d"
s3_bucket_name = "${aws_s3_bucket.b.bucket}"
s3_key_prefix = "one/two/three"
sns_topic_arn = "${aws_sns_topic.t.arn}"
snapshot_delivery_properties {
delivery_frequency = "Six_Hours"
}
}`, randInt, randInt, randInt, randInt, randInt, randInt)
}

View File

@ -14,6 +14,7 @@ import (
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/aws/aws-sdk-go/service/configservice"
"github.com/aws/aws-sdk-go/service/directoryservice"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ecs"
@ -926,6 +927,52 @@ func expandESEBSOptions(m map[string]interface{}) *elasticsearch.EBSOptions {
return &options
}
func expandConfigRecordingGroup(configured []interface{}) *configservice.RecordingGroup {
recordingGroup := configservice.RecordingGroup{}
group := configured[0].(map[string]interface{})
if v, ok := group["all_supported"]; ok {
recordingGroup.AllSupported = aws.Bool(v.(bool))
}
if v, ok := group["include_global_resource_types"]; ok {
recordingGroup.IncludeGlobalResourceTypes = aws.Bool(v.(bool))
}
if v, ok := group["resource_types"]; ok {
recordingGroup.ResourceTypes = expandStringList(v.(*schema.Set).List())
}
return &recordingGroup
}
func flattenConfigRecordingGroup(g *configservice.RecordingGroup) []map[string]interface{} {
m := make(map[string]interface{}, 1)
if g.AllSupported != nil {
m["all_supported"] = *g.AllSupported
}
if g.IncludeGlobalResourceTypes != nil {
m["include_global_resource_types"] = *g.IncludeGlobalResourceTypes
}
if g.ResourceTypes != nil && len(g.ResourceTypes) > 0 {
m["resource_types"] = schema.NewSet(schema.HashString, flattenStringList(g.ResourceTypes))
}
return []map[string]interface{}{m}
}
func flattenConfigSnapshotDeliveryProperties(p *configservice.ConfigSnapshotDeliveryProperties) []map[string]interface{} {
m := make(map[string]interface{}, 0)
if p.DeliveryFrequency != nil {
m["delivery_frequency"] = *p.DeliveryFrequency
}
return []map[string]interface{}{m}
}
func pointersMapToStringList(pointers map[string]*string) map[string]interface{} {
list := make(map[string]interface{}, len(pointers))
for i, v := range pointers {
@ -1630,6 +1677,116 @@ func flattenPolicyAttributes(list []*elb.PolicyAttributeDescription) []interface
return attributes
}
func flattenConfigRuleSource(source *configservice.Source) []interface{} {
var result []interface{}
m := make(map[string]interface{})
m["owner"] = *source.Owner
m["source_identifier"] = *source.SourceIdentifier
if len(source.SourceDetails) > 0 {
m["source_detail"] = schema.NewSet(configRuleSourceDetailsHash, flattenConfigRuleSourceDetails(source.SourceDetails))
}
result = append(result, m)
return result
}
func flattenConfigRuleSourceDetails(details []*configservice.SourceDetail) []interface{} {
var items []interface{}
for _, d := range details {
m := make(map[string]interface{})
if d.MessageType != nil {
m["message_type"] = *d.MessageType
}
if d.EventSource != nil {
m["event_source"] = *d.EventSource
}
if d.MaximumExecutionFrequency != nil {
m["maximum_execution_frequency"] = *d.MaximumExecutionFrequency
}
items = append(items, m)
}
return items
}
func expandConfigRuleSource(configured []interface{}) *configservice.Source {
cfg := configured[0].(map[string]interface{})
source := configservice.Source{
Owner: aws.String(cfg["owner"].(string)),
SourceIdentifier: aws.String(cfg["source_identifier"].(string)),
}
if details, ok := cfg["source_detail"]; ok {
source.SourceDetails = expandConfigRuleSourceDetails(details.(*schema.Set))
}
return &source
}
func expandConfigRuleSourceDetails(configured *schema.Set) []*configservice.SourceDetail {
var results []*configservice.SourceDetail
for _, item := range configured.List() {
detail := item.(map[string]interface{})
src := configservice.SourceDetail{}
if msgType, ok := detail["message_type"].(string); ok && msgType != "" {
src.MessageType = aws.String(msgType)
}
if eventSource, ok := detail["event_source"].(string); ok && eventSource != "" {
src.EventSource = aws.String(eventSource)
}
if maxExecFreq, ok := detail["maximum_execution_frequency"].(string); ok && maxExecFreq != "" {
src.MaximumExecutionFrequency = aws.String(maxExecFreq)
}
results = append(results, &src)
}
return results
}
func flattenConfigRuleScope(scope *configservice.Scope) []interface{} {
var items []interface{}
m := make(map[string]interface{})
if scope.ComplianceResourceId != nil {
m["compliance_resource_id"] = *scope.ComplianceResourceId
}
if scope.ComplianceResourceTypes != nil {
m["compliance_resource_types"] = schema.NewSet(schema.HashString, flattenStringList(scope.ComplianceResourceTypes))
}
if scope.TagKey != nil {
m["tag_key"] = *scope.TagKey
}
if scope.TagValue != nil {
m["tag_value"] = *scope.TagValue
}
items = append(items, m)
return items
}
func expandConfigRuleScope(configured map[string]interface{}) *configservice.Scope {
scope := &configservice.Scope{}
if v, ok := configured["compliance_resource_id"].(string); ok && v != "" {
scope.ComplianceResourceId = aws.String(v)
}
if v, ok := configured["compliance_resource_types"]; ok {
l := v.(*schema.Set)
if l.Len() > 0 {
scope.ComplianceResourceTypes = expandStringList(l.List())
}
}
if v, ok := configured["tag_key"].(string); ok && v != "" {
scope.TagKey = aws.String(v)
}
if v, ok := configured["tag_value"].(string); ok && v != "" {
scope.TagValue = aws.String(v)
}
return scope
}
// Takes a value containing JSON string and passes it through
// the JSON parser to normalize it, returns either a parsing
// error or normalized JSON string.

View File

@ -893,3 +893,40 @@ func validateAppautoscalingServiceNamespace(v interface{}, k string) (ws []strin
}
return
}
func validateConfigRuleSourceOwner(v interface{}, k string) (ws []string, errors []error) {
validOwners := []string{
"CUSTOM_LAMBDA",
"AWS",
}
owner := v.(string)
for _, o := range validOwners {
if owner == o {
return
}
}
errors = append(errors, fmt.Errorf(
"%q contains an invalid owner %q. Valid owners are %q.",
k, owner, validOwners))
return
}
func validateConfigExecutionFrequency(v interface{}, k string) (ws []string, errors []error) {
validFrequencies := []string{
"One_Hour",
"Three_Hours",
"Six_Hours",
"Twelve_Hours",
"TwentyFour_Hours",
}
frequency := v.(string)
for _, f := range validFrequencies {
if frequency == f {
return
}
}
errors = append(errors, fmt.Errorf(
"%q contains an invalid freqency %q. Valid frequencies are %q.",
k, frequency, validFrequencies))
return
}

View File

@ -0,0 +1,135 @@
---
layout: "aws"
page_title: "AWS: aws_config_config_rule"
sidebar_current: "docs-aws-resource-config-config-rule"
description: |-
Provides an AWS Config Rule.
---
# aws\_config\_config\_rule
Provides an AWS Config Rule.
~> **Note:** Config Rule requires an existing [Configuration Recorder](/docs/providers/aws/r/config_configuration_recorder.html) to be present. Use of `depends_on` is recommended (as shown below) to avoid race conditions.
## Example Usage
```
resource "aws_config_config_rule" "r" {
name = "example"
source {
owner = "AWS"
source_identifier = "S3_BUCKET_VERSIONING_ENABLED"
}
depends_on = ["aws_config_configuration_recorder.foo"]
}
resource "aws_config_configuration_recorder" "foo" {
name = "example"
role_arn = "${aws_iam_role.r.arn}"
}
resource "aws_iam_role" "r" {
name = "my-awsconfig-role"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
POLICY
}
resource "aws_iam_role_policy" "p" {
name = "my-awsconfig-policy"
role = "${aws_iam_role.r.id}"
policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "config:Put*",
"Effect": "Allow",
"Resource": "*"
}
]
}
POLICY
}
```
## Argument Reference
The following arguments are supported:
* `name` - (Required) The name of the rule
* `description` - (Optional) Description of the rule
* `input_parameters` - (Optional) A string in JSON format that is passed to the AWS Config rule Lambda function (only valid if `source.owner` is `CUSTOM_LAMBDA`).
* `maximum_execution_frequency` - (Optional) The maximum frequency with which AWS Config runs evaluations for a rule.
* `scope` - (Optional) Scope defines which resources can trigger an evaluation for the rule as documented below.
* `source` - (Required) Source specifies the rule owner, the rule identifier, and the notifications that cause
the function to evaluate your AWS resources as documented below.
### `scope`
Defines which resources can trigger an evaluation for the rule.
If you do not specify a scope, evaluations are triggered when any resource in the recording group changes.
* `compliance_resource_id` - (Optional) The IDs of the only AWS resource that you want to trigger an evaluation for the rule.
If you specify a resource ID, you must specify one resource type for `compliance_resource_types`.
* `compliance_resource_types` - (Optional) A list of resource types of only those AWS resources that you want to trigger an
evaluation for the rule. e.g. `AWS::EC2::Instance`. You can only specify one type if you also specify
a resource ID for `compliance_resource_id`. See [relevant part of AWS Docs](http://docs.aws.amazon.com/config/latest/APIReference/API_ResourceIdentifier.html#config-Type-ResourceIdentifier-resourceType) for available types.
* `tag_key` - (Optional, Required if `tag_value` is specified) The tag key that is applied to only those AWS resources that you want you
want to trigger an evaluation for the rule.
* `tag_value` - (Optional) The tag value applied to only those AWS resources that you want to trigger an evaluation for the rule.
### `source`
Provides the rule owner (AWS or customer), the rule identifier, and the notifications that cause the function to evaluate your AWS resources.
* `owner` - (Required) Indicates whether AWS or the customer owns and manages the AWS Config rule.
The only valid value is `AWS` or `CUSTOM_LAMBDA`. Keep in mind that Lambda function will require `aws_lambda_permission` to allow AWSConfig to execute the function.
* `source_identifier` - (Required) For AWS Config managed rules, a predefined identifier from a list. For example,
`IAM_PASSWORD_POLICY` is a managed rule. To reference a managed rule, see [Using AWS Managed Config Rules](http://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_use-managed-rules.html).
For custom rules, the identifier is the ARN of the rule's AWS Lambda function, such as `arn:aws:lambda:us-east-1:123456789012:function:custom_rule_name`.
* `source_detail` - (Optional) Provides the source and type of the event that causes AWS Config to evaluate your AWS resources. Only valid if `owner` is `CUSTOM_LAMBDA`.
* `event_source` - (Optional) The source of the event, such as an AWS service, that triggers AWS Config
to evaluate your AWS resources. The only valid value is `aws.config`.
* `maximum_execution_frequency` - (Optional) The frequency that you want AWS Config to run evaluations for a rule that
is triggered periodically. If specified, requires `message_type` to be `ScheduledNotification`.
* `message_type` - (Optional) The type of notification that triggers AWS Config to run an evaluation for a rule. You can specify the following notification types:
* `ConfigurationItemChangeNotification` - Triggers an evaluation when AWS
Config delivers a configuration item as a result of a resource change.
* `OversizedConfigurationItemChangeNotification` - Triggers an evaluation
when AWS Config delivers an oversized configuration item. AWS Config may
generate this notification type when a resource changes and the notification
exceeds the maximum size allowed by Amazon SNS.
* `ScheduledNotification` - Triggers a periodic evaluation at the frequency
specified for `maximum_execution_frequency`.
* `ConfigurationSnapshotDeliveryCompleted` - Triggers a periodic evaluation
when AWS Config delivers a configuration snapshot.
## Attributes Reference
The following attributes are exported:
* `arn` - The ARN of the config rule
* `rule_id` - The ID of the config rule
## Import
Config Rule can be imported using the name, e.g.
```
$ terraform import aws_config_config_rule.foo example
```

View File

@ -0,0 +1,76 @@
---
layout: "aws"
page_title: "AWS: aws_config_configuration_recorder"
sidebar_current: "docs-aws-resource-config-configuration-recorder"
description: |-
Provides an AWS Config Configuration Recorder.
---
# aws\_config\_configuration\_recorder
Provides an AWS Config Configuration Recorder. Please note that this resource **does not start** the created recorder automatically.
~> **Note:** _Starting_ the Configuration Recorder requires a [delivery channel](/docs/providers/aws/r/config_delivery_channel.html) (while delivery channel creation requires Configuration Recorder). This is why [`aws_config_configuration_recorder_status`](/docs/providers/aws/r/config_configuration_recorder_status.html) is a separate resource.
## Example Usage
```
resource "aws_config_configuration_recorder" "foo" {
name = "example"
role_arn = "${aws_iam_role.r.arn}"
}
resource "aws_iam_role" "r" {
name = "awsconfig-example"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
POLICY
}
```
## Argument Reference
The following arguments are supported:
* `name` - (Optional) The name of the recorder. Defaults to `default`
* `role_arn` - (Required) Amazon Resource Name (ARN) of the IAM role
used to make read or write requests to the delivery channel and to describe the AWS resources associated with the account.
See [AWS Docs](http://docs.aws.amazon.com/config/latest/developerguide/iamrole-permissions.html) for more details.
* `recording_group` - (Optional) Recording group - see below.
### `recording_group`
* `all_supported` - (Optional) Specifies whether AWS Config records configuration changes
for every supported type of regional resource (which includes any new type that will become supported in the future).
Conflicts with `resource_types`. Defaults to `true`.
* `include_global_resource_types` - (Optional) Specifies whether AWS Config includes all supported types of *global resources*
with the resources that it records. Requires `all_supported = true`. Conflicts with `resource_types`.
* `resource_types` - (Optional) A list that specifies the types of AWS resources for which
AWS Config records configuration changes (for example, `AWS::EC2::Instance` or `AWS::CloudTrail::Trail`).
See [relevant part of AWS Docs](http://docs.aws.amazon.com/config/latest/APIReference/API_ResourceIdentifier.html#config-Type-ResourceIdentifier-resourceType) for available types.
## Attributes Reference
The following attributes are exported:
* `id` - Name of the recorder
## Import
Configuration Recorder can be imported using the name, e.g.
```
$ terraform import aws_config_configuration_recorder.foo example
```

View File

@ -0,0 +1,76 @@
---
layout: "aws"
page_title: "AWS: aws_config_configuration_recorder_status"
sidebar_current: "docs-aws-resource-config-configuration-recorder-status"
description: |-
Manages status of an AWS Config Configuration Recorder.
---
# aws\_config\_configuration\_recorder\_status
Manages status (recording / stopped) of an AWS Config Configuration Recorder.
~> **Note:** Starting Configuration Recorder requires a [Delivery Channel](/docs/providers/aws/r/config_delivery_channel.html) to be present. Use of `depends_on` (as shown below) is recommended to avoid race conditions.
## Example Usage
```
resource "aws_config_configuration_recorder_status" "foo" {
name = "${aws_config_configuration_recorder.foo.name}"
is_enabled = true
depends_on = ["aws_config_delivery_channel.foo"]
}
resource "aws_iam_role_policy_attachment" "a" {
role = "${aws_iam_role.r.name}"
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSConfigRole"
}
resource "aws_s3_bucket" "b" {
bucket = "awsconfig-example"
}
resource "aws_config_delivery_channel" "foo" {
name = "example"
s3_bucket_name = "${aws_s3_bucket.b.bucket}"
}
resource "aws_config_configuration_recorder" "foo" {
name = "example"
role_arn = "${aws_iam_role.r.arn}"
}
resource "aws_iam_role" "r" {
name = "example-awsconfig"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
POLICY
}
```
## Argument Reference
The following arguments are supported:
* `name` - (Required) The name of the recorder
* `is_enabled` - (Required) Whether the configuration recorder should be enabled or disabled.
## Import
Configuration Recorder Status can be imported using the name of the Configuration Recorder, e.g.
```
$ terraform import aws_config_configuration_recorder_status.foo example
```

View File

@ -0,0 +1,103 @@
---
layout: "aws"
page_title: "AWS: aws_config_delivery_channel"
sidebar_current: "docs-aws-resource-config-delivery-channel"
description: |-
Provides an AWS Config Delivery Channel.
---
# aws\_config\_delivery\_channel
Provides an AWS Config Delivery Channel.
~> **Note:** Delivery Channel requires a [Configuration Recorder](/docs/providers/aws/r/config_configuration_recorder.html) to be present. Use of `depends_on` (as shown below) is recommended to avoid race conditions.
## Example Usage
```
resource "aws_config_delivery_channel" "foo" {
name = "example"
s3_bucket_name = "${aws_s3_bucket.b.bucket}"
depends_on = ["aws_config_configuration_recorder.foo"]
}
resource "aws_s3_bucket" "b" {
bucket = "example-awsconfig"
force_destroy = true
}
resource "aws_config_configuration_recorder" "foo" {
name = "example"
role_arn = "${aws_iam_role.r.arn}"
}
resource "aws_iam_role" "r" {
name = "awsconfig-example"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "config.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
POLICY
}
resource "aws_iam_role_policy" "p" {
name = "awsconfig-example"
role = "${aws_iam_role.r.id}"
policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:*"
],
"Effect": "Allow",
"Resource": [
"${aws_s3_bucket.b.arn}",
"${aws_s3_bucket.b.arn}/*"
]
}
]
}
POLICY
}
```
## Argument Reference
The following arguments are supported:
* `name` - (Optional) The name of the delivery channel. Defaults to `default`.
* `s3_bucket_name` - (Required) The name of the S3 bucket used to store the configuration history.
* `s3_key_prefix` - (Optional) The prefix for the specified S3 bucket.
* `sns_topic_arn` - (Optional) The ARN of the SNS topic that AWS Config delivers notifications to.
* `snapshot_delivery_properties` - (Optional) Options for how AWS Config delivers configuration snapshots. See below
### `snapshot_delivery_properties`
* `delivery_frequency` - (Optional) - The frequency with which a AWS Config recurringly delivers configuration snapshots.
e.g. `One_Hour` or `Three_Hours`
## Attributes Reference
The following attributes are exported:
* `id` - The name of the delivery channel.
## Import
Delivery Channel can be imported using the name, e.g.
```
$ terraform import aws_config_delivery_channel.foo example
```

View File

@ -324,6 +324,29 @@
</ul>
</li>
<li<%= sidebar_current(/^docs-aws-resource-config/) %>>
<a href="#">Config Resources</a>
<ul class="nav nav-visible">
<li<%= sidebar_current("docs-aws-resource-config-config-rule") %>>
<a href="/docs/providers/aws/r/config_config_rule.html">aws_config_config_rule</a>
</li>
<li<%= sidebar_current("docs-aws-resource-config-configuration-recorder") %>>
<a href="/docs/providers/aws/r/config_configuration_recorder.html">aws_config_configuration_recorder</a>
</li>
<li<%= sidebar_current("docs-aws-resource-config-configuration-recorder-status") %>>
<a href="/docs/providers/aws/r/config_configuration_recorder_status.html">aws_config_configuration_recorder_status</a>
</li>
<li<%= sidebar_current("docs-aws-resource-config-delivery-channel") %>>
<a href="/docs/providers/aws/r/config_delivery_channel.html">aws_config_delivery_channel</a>
</li>
</ul>
</li>
<li<%= sidebar_current(/^docs-aws-resource-directory-service/) %>>
<a href="#">Directory Service Resources</a>
<ul class="nav nav-visible">