provider/aws: Add aws_config_delivery_channel

This commit is contained in:
Radek Simko 2017-02-02 22:33:55 +00:00
parent a2b63f92c0
commit f2af02eb59
No known key found for this signature in database
GPG Key ID: 6823F3DCCE01BB19
6 changed files with 568 additions and 0 deletions

View File

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

View File

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

View File

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

View File

@ -963,6 +963,16 @@ func flattenConfigRecordingGroup(g *configservice.RecordingGroup) []map[string]i
return []map[string]interface{}{m}
}
func flattenConfigSnapshotDeliveryProperties(p *configservice.ConfigSnapshotDeliveryProperties) []map[string]interface{} {
m := make(map[string]interface{}, 0)
if p.DeliveryFrequency != nil {
m["delivery_frequency"] = *p.DeliveryFrequency
}
return []map[string]interface{}{m}
}
func pointersMapToStringList(pointers map[string]*string) map[string]interface{} {
list := make(map[string]interface{}, len(pointers))
for i, v := range pointers {

View File

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

View File

@ -332,6 +332,10 @@
<a href="/docs/providers/aws/r/config_configuration_recorder_status.html">aws_config_configuration_recorder_status</a>
</li>
<li<%= sidebar_current("docs-aws-resource-config-delivery-channel") %>>
<a href="/docs/providers/aws/r/config_delivery_channel.html">aws_config_delivery_channel</a>
</li>
</ul>
</li>