Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

provider/aws: Enabled Enhanced Monitoring for RDS #4945

Merged
merged 1 commit into from
Feb 22, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions builtin/providers/aws/resource_aws_db_instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
},
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
76 changes: 76 additions & 0 deletions builtin/providers/aws/resource_aws_db_instance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
}
`
36 changes: 36 additions & 0 deletions builtin/providers/aws/resource_aws_iam_policy_attachment.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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
}
Expand Down
4 changes: 4 additions & 0 deletions website/source/docs/providers/aws/r/db_instance.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down