provider/aws: Add aws_config_configuration_recorder_status

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

View File

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

View File

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

View File

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

View File

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

View File

@ -328,6 +328,10 @@
<a href="/docs/providers/aws/r/config_configuration_recorder.html">aws_config_configuration_recorder</a>
</li>
<li<%= sidebar_current("docs-aws-resource-config-configuration-recorder-status") %>>
<a href="/docs/providers/aws/r/config_configuration_recorder_status.html">aws_config_configuration_recorder_status</a>
</li>
</ul>
</li>