From 1fdd52ea202556ba6d2e178cbc47396a7b4a7b6c Mon Sep 17 00:00:00 2001 From: Radek Simko Date: Thu, 2 Feb 2017 22:29:13 +0000 Subject: [PATCH] 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 d15b0f4bcc..1786285fc8 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 fcdcf5ca5e..528af49e21 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 0000000000..e4f2e5c6b3 --- /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 0000000000..6540fc5dea --- /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 526505bc92..3b91137751 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 0000000000..c574078952 --- /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