From 1fdd52ea202556ba6d2e178cbc47396a7b4a7b6c Mon Sep 17 00:00:00 2001 From: Radek Simko Date: Thu, 2 Feb 2017 22:29:13 +0000 Subject: [PATCH 1/4] provider/aws: Add aws_config_config_rule --- builtin/providers/aws/config.go | 3 + builtin/providers/aws/provider.go | 1 + .../aws/resource_aws_config_config_rule.go | 301 +++++++++++ .../resource_aws_config_config_rule_test.go | 473 ++++++++++++++++++ builtin/providers/aws/structure.go | 111 ++++ builtin/providers/aws/validators.go | 37 ++ .../aws/r/config_config_rule.html.markdown | 135 +++++ website/source/layouts/aws.erb | 11 + 8 files changed, 1072 insertions(+) create mode 100644 builtin/providers/aws/resource_aws_config_config_rule.go create mode 100644 builtin/providers/aws/resource_aws_config_config_rule_test.go create mode 100644 website/source/docs/providers/aws/r/config_config_rule.html.markdown diff --git a/builtin/providers/aws/config.go b/builtin/providers/aws/config.go index d15b0f4bc..1786285fc 100644 --- a/builtin/providers/aws/config.go +++ b/builtin/providers/aws/config.go @@ -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) diff --git a/builtin/providers/aws/provider.go b/builtin/providers/aws/provider.go index fcdcf5ca5..528af49e2 100644 --- a/builtin/providers/aws/provider.go +++ b/builtin/providers/aws/provider.go @@ -231,6 +231,7 @@ 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_autoscaling_lifecycle_hook": resourceAwsAutoscalingLifecycleHook(), "aws_cloudwatch_metric_alarm": resourceAwsCloudWatchMetricAlarm(), "aws_codedeploy_app": resourceAwsCodeDeployApp(), diff --git a/builtin/providers/aws/resource_aws_config_config_rule.go b/builtin/providers/aws/resource_aws_config_config_rule.go new file mode 100644 index 000000000..e4f2e5c6b --- /dev/null +++ b/builtin/providers/aws/resource_aws_config_config_rule.go @@ -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()) +} diff --git a/builtin/providers/aws/resource_aws_config_config_rule_test.go b/builtin/providers/aws/resource_aws_config_config_rule_test.go new file mode 100644 index 000000000..6540fc5de --- /dev/null +++ b/builtin/providers/aws/resource_aws_config_config_rule_test.go @@ -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 = < 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. diff --git a/builtin/providers/aws/validators.go b/builtin/providers/aws/validators.go index 526505bc9..3b9113775 100644 --- a/builtin/providers/aws/validators.go +++ b/builtin/providers/aws/validators.go @@ -891,3 +891,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 +} diff --git a/website/source/docs/providers/aws/r/config_config_rule.html.markdown b/website/source/docs/providers/aws/r/config_config_rule.html.markdown new file mode 100644 index 000000000..c57407895 --- /dev/null +++ b/website/source/docs/providers/aws/r/config_config_rule.html.markdown @@ -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 = < + > + Config Resources + + + > Directory Service Resources From a2b63f92c00ebf743bd2023197c6e22aacf167a6 Mon Sep 17 00:00:00 2001 From: Radek Simko Date: Thu, 2 Feb 2017 22:33:26 +0000 Subject: [PATCH 3/4] provider/aws: Add aws_config_configuration_recorder_status --- builtin/providers/aws/provider.go | 1 + ...ws_config_configuration_recorder_status.go | 122 +++++++++ ...nfig_configuration_recorder_status_test.go | 235 ++++++++++++++++++ ...onfiguration_recorder_status.html.markdown | 76 ++++++ website/source/layouts/aws.erb | 4 + 5 files changed, 438 insertions(+) create mode 100644 builtin/providers/aws/resource_aws_config_configuration_recorder_status.go create mode 100644 builtin/providers/aws/resource_aws_config_configuration_recorder_status_test.go create mode 100644 website/source/docs/providers/aws/r/config_configuration_recorder_status.html.markdown diff --git a/builtin/providers/aws/provider.go b/builtin/providers/aws/provider.go index 1471051d3..015088fb0 100644 --- a/builtin/providers/aws/provider.go +++ b/builtin/providers/aws/provider.go @@ -233,6 +233,7 @@ func Provider() terraform.ResourceProvider { "aws_cloudwatch_log_subscription_filter": resourceAwsCloudwatchLogSubscriptionFilter(), "aws_config_config_rule": resourceAwsConfigConfigRule(), "aws_config_configuration_recorder": resourceAwsConfigConfigurationRecorder(), + "aws_config_configuration_recorder_status": resourceAwsConfigConfigurationRecorderStatus(), "aws_autoscaling_lifecycle_hook": resourceAwsAutoscalingLifecycleHook(), "aws_cloudwatch_metric_alarm": resourceAwsCloudWatchMetricAlarm(), "aws_codedeploy_app": resourceAwsCodeDeployApp(), diff --git a/builtin/providers/aws/resource_aws_config_configuration_recorder_status.go b/builtin/providers/aws/resource_aws_config_configuration_recorder_status.go new file mode 100644 index 000000000..a2ba85b5d --- /dev/null +++ b/builtin/providers/aws/resource_aws_config_configuration_recorder_status.go @@ -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 +} diff --git a/builtin/providers/aws/resource_aws_config_configuration_recorder_status_test.go b/builtin/providers/aws/resource_aws_config_configuration_recorder_status_test.go new file mode 100644 index 000000000..3967bcb3a --- /dev/null +++ b/builtin/providers/aws/resource_aws_config_configuration_recorder_status_test.go @@ -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 = < **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 = <aws_config_configuration_recorder + > + aws_config_configuration_recorder_status + + From f2af02eb59ebd70267ea749fd62494b81dfe730a Mon Sep 17 00:00:00 2001 From: Radek Simko Date: Thu, 2 Feb 2017 22:33:55 +0000 Subject: [PATCH 4/4] provider/aws: Add aws_config_delivery_channel --- builtin/providers/aws/provider.go | 1 + .../resource_aws_config_delivery_channel.go | 171 +++++++++++ ...source_aws_config_delivery_channel_test.go | 279 ++++++++++++++++++ builtin/providers/aws/structure.go | 10 + .../r/config_delivery_channel.html.markdown | 103 +++++++ website/source/layouts/aws.erb | 4 + 6 files changed, 568 insertions(+) create mode 100644 builtin/providers/aws/resource_aws_config_delivery_channel.go create mode 100644 builtin/providers/aws/resource_aws_config_delivery_channel_test.go create mode 100644 website/source/docs/providers/aws/r/config_delivery_channel.html.markdown diff --git a/builtin/providers/aws/provider.go b/builtin/providers/aws/provider.go index 015088fb0..8d63bd07c 100644 --- a/builtin/providers/aws/provider.go +++ b/builtin/providers/aws/provider.go @@ -234,6 +234,7 @@ func Provider() terraform.ResourceProvider { "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(), diff --git a/builtin/providers/aws/resource_aws_config_delivery_channel.go b/builtin/providers/aws/resource_aws_config_delivery_channel.go new file mode 100644 index 000000000..e77836dc7 --- /dev/null +++ b/builtin/providers/aws/resource_aws_config_delivery_channel.go @@ -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 +} diff --git a/builtin/providers/aws/resource_aws_config_delivery_channel_test.go b/builtin/providers/aws/resource_aws_config_delivery_channel_test.go new file mode 100644 index 000000000..6f0d5fd4d --- /dev/null +++ b/builtin/providers/aws/resource_aws_config_delivery_channel_test.go @@ -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 = < **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 = <aws_config_configuration_recorder_status + > + aws_config_delivery_channel + +