provider/aws: Add aws_config_config_rule

This commit is contained in:
Radek Simko 2017-02-02 22:29:13 +00:00
parent d2aaa4557d
commit 1fdd52ea20
No known key found for this signature in database
GPG Key ID: 6823F3DCCE01BB19
8 changed files with 1072 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

@ -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(),

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

@ -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"
@ -1630,6 +1631,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

@ -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
}

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

@ -316,6 +316,17 @@
</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>
</ul>
</li>
<li<%= sidebar_current(/^docs-aws-resource-directory-service/) %>>
<a href="#">Directory Service Resources</a>
<ul class="nav nav-visible">