Enabled Enhanced Monitoring for RDS

This commit is contained in:
stack72 2016-02-01 22:32:38 +00:00
parent dce2994151
commit e87d3bb711
4 changed files with 164 additions and 0 deletions

View File

@ -270,6 +270,18 @@ func resourceAwsDbInstance() *schema.Resource {
Optional: true,
},
"monitoring_role_arn": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"monitoring_interval": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 0,
},
"tags": tagsSchema(),
},
}
@ -311,6 +323,14 @@ func resourceAwsDbInstanceCreate(d *schema.ResourceData, meta interface{}) error
opts.DBSubnetGroupName = aws.String(attr.(string))
}
if attr, ok := d.GetOk("monitoring_role_arn"); ok {
opts.MonitoringRoleArn = aws.String(attr.(string))
}
if attr, ok := d.GetOk("monitoring_interval"); ok {
opts.MonitoringInterval = aws.Int64(int64(attr.(int)))
}
log.Printf("[DEBUG] DB Instance Replica create configuration: %#v", opts)
_, err := conn.CreateDBInstanceReadReplica(&opts)
if err != nil {
@ -494,6 +514,14 @@ func resourceAwsDbInstanceCreate(d *schema.ResourceData, meta interface{}) error
opts.PubliclyAccessible = aws.Bool(attr.(bool))
}
if attr, ok := d.GetOk("monitoring_role_arn"); ok {
opts.MonitoringRoleArn = aws.String(attr.(string))
}
if attr, ok := d.GetOk("monitoring_interval"); ok {
opts.MonitoringInterval = aws.Int64(int64(attr.(int)))
}
log.Printf("[DEBUG] DB Instance create configuration: %#v", opts)
var err error
_, err = conn.CreateDBInstance(&opts)
@ -575,6 +603,14 @@ func resourceAwsDbInstanceRead(d *schema.ResourceData, meta interface{}) error {
d.Set("status", v.DBInstanceStatus)
d.Set("storage_encrypted", v.StorageEncrypted)
if v.MonitoringInterval != nil {
d.Set("monitoring_interval", v.MonitoringInterval)
}
if v.MonitoringRoleArn != nil {
d.Set("monitoring_role_arn", v.MonitoringRoleArn)
}
// list tags for resource
// set tags
conn := meta.(*AWSClient).rdsconn
@ -764,6 +800,18 @@ func resourceAwsDbInstanceUpdate(d *schema.ResourceData, meta interface{}) error
requestUpdate = true
}
if d.HasChange("monitoring_role_arn") {
d.SetPartial("monitoring_role_arn")
req.MonitoringRoleArn = aws.String(d.Get("monitoring_role_arn").(string))
requestUpdate = true
}
if d.HasChange("monitoring_interval") {
d.SetPartial("monitoring_interval")
req.MonitoringInterval = aws.Int64(int64(d.Get("monitoring_interval").(int)))
requestUpdate = true
}
if d.HasChange("vpc_security_group_ids") {
if attr := d.Get("vpc_security_group_ids").(*schema.Set); attr.Len() > 0 {
var s []*string

View File

@ -105,6 +105,26 @@ func TestAccAWSDBInstanceNoSnapshot(t *testing.T) {
})
}
func TestAccAWSDBInstance_enhancedMonitoring(t *testing.T) {
var dbInstance rds.DBInstance
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSDBInstanceNoSnapshot,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccSnapshotInstanceConfig_enhancedMonitoring,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSDBInstanceExists("aws_db_instance.enhanced_monitoring", &dbInstance),
resource.TestCheckResourceAttr(
"aws_db_instance.enhanced_monitoring", "monitoring_interval", "5"),
),
},
},
})
}
func testAccCheckAWSDBInstanceDestroy(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).rdsconn
@ -414,3 +434,59 @@ resource "aws_db_instance" "no_snapshot" {
final_snapshot_identifier = "foobarbaz-test-terraform-final-snapshot-2"
}
`
var testAccSnapshotInstanceConfig_enhancedMonitoring = `
provider "aws" {
region = "us-east-1"
}
resource "aws_iam_role" "enhanced_policy_role" {
name = "enhanced-monitoring-role"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "monitoring.rds.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
EOF
}
resource "aws_iam_policy_attachment" "test-attach" {
name = "enhanced-monitoring-attachment"
roles = [
"${aws_iam_role.enhanced_policy_role.name}",
]
policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonRDSEnhancedMonitoringRole"
}
resource "aws_db_instance" "enhanced_monitoring" {
identifier = "foobarbaz-test-terraform-enhanced-monitoring"
depends_on = ["aws_iam_policy_attachment.test-attach"]
allocated_storage = 5
engine = "mysql"
engine_version = "5.6.21"
instance_class = "db.t2.small"
name = "baz"
password = "barbarbarbar"
username = "foo"
backup_retention_period = 1
parameter_group_name = "default.mysql5.6"
monitoring_role_arn = "${aws_iam_role.enhanced_policy_role.arn}"
monitoring_interval = "5"
skip_final_snapshot = true
}
`

View File

@ -3,10 +3,13 @@ package aws
import (
"fmt"
"log"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
@ -210,6 +213,39 @@ func attachPolicyToRoles(conn *iam.IAM, roles []*string, arn string) error {
if err != nil {
return err
}
var attachmentErr error
attachmentErr = resource.Retry(2*time.Minute, func() error {
input := iam.ListRolePoliciesInput{
RoleName: r,
}
attachedPolicies, err := conn.ListRolePolicies(&input)
if err != nil {
return &resource.RetryError{Err: err}
}
if len(attachedPolicies.PolicyNames) > 0 {
var foundPolicy bool
for _, policyName := range attachedPolicies.PolicyNames {
if strings.HasSuffix(arn, *policyName) {
foundPolicy = true
break
}
}
if !foundPolicy {
return &resource.RetryError{Err: fmt.Errorf("Policy (%q) not yet found", arn)}
}
}
return nil
})
if attachmentErr != nil {
return attachmentErr
}
}
return nil
}

View File

@ -99,6 +99,10 @@ database, and to use this value as the source database. This correlates to the
* `license_model` - (Optional, but required for some DB engines, i.e. Oracle SE1) License model information for this DB instance.
* `auto_minor_version_upgrade` - (Optional) Indicates that minor engine upgrades will be applied automatically to the DB instance during the maintenance window. Defaults to true.
* `allow_major_version_upgrade` - (Optional) Indicates that major version upgrades are allowed. Changing this parameter does not result in an outage and the change is asynchronously applied as soon as possible.
* `monitoring_role_arn` - (Optional) The ARN for the IAM role that permits RDS to send
enhanced monitoring metrics to CloudWatch Logs. You can find more information on the [AWS Documentation](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Monitoring.html)
what IAM permissions are needed to allow Enhanced Monitoring for RDS Instances.
* `monitoring_interval` - (Optional) The interval, in seconds, between points when Enhanced Monitoring metrics are collected for the DB instance. To disable collecting Enhanced Monitoring metrics, specify 0. The default is 0. Valid Values: 0, 1, 5, 10, 15, 30, 60.
~> **NOTE:** Removing the `replicate_source_db` attribute from an existing RDS
Replicate database managed by Terraform will promote the database to a fully