diff --git a/builtin/providers/aws/resource_aws_iam_role.go b/builtin/providers/aws/resource_aws_iam_role.go index f8ec7b358..f87c802dd 100644 --- a/builtin/providers/aws/resource_aws_iam_role.go +++ b/builtin/providers/aws/resource_aws_iam_role.go @@ -102,6 +102,27 @@ func resourceAwsIamRoleReadResult(d *schema.ResourceData, role *iam.Role) error func resourceAwsIamRoleDelete(d *schema.ResourceData, meta interface{}) error { iamconn := meta.(*AWSClient).iamconn + // Roles cannot be destroyed when attached to an existing Instance Profile + resp, err := iamconn.ListInstanceProfilesForRole(&iam.ListInstanceProfilesForRoleInput{ + RoleName: aws.String(d.Id()), + }) + if err != nil { + return fmt.Errorf("Error listing Profiles for IAM Role (%s) when trying to delete: %s", d.Id(), err) + } + + // Loop and remove this Role from any Profiles + if len(resp.InstanceProfiles) > 0 { + for _, i := range resp.InstanceProfiles { + _, err := iamconn.RemoveRoleFromInstanceProfile(&iam.RemoveRoleFromInstanceProfileInput{ + InstanceProfileName: i.InstanceProfileName, + RoleName: aws.String(d.Id()), + }) + if err != nil { + return fmt.Errorf("Error deleting IAM Role %s: %s", d.Id(), err) + } + } + } + request := &iam.DeleteRoleInput{ RoleName: aws.String(d.Id()), } diff --git a/builtin/providers/aws/resource_aws_iam_role_test.go b/builtin/providers/aws/resource_aws_iam_role_test.go index cbb75c3c4..e93221768 100644 --- a/builtin/providers/aws/resource_aws_iam_role_test.go +++ b/builtin/providers/aws/resource_aws_iam_role_test.go @@ -30,6 +30,31 @@ func TestAccAWSRole_normal(t *testing.T) { }) } +func TestAccAWSRole_testNameChange(t *testing.T) { + var conf iam.GetRoleOutput + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testAccCheckAWSRoleDestroy, + Steps: []resource.TestStep{ + resource.TestStep{ + Config: testAccAWSRolePre, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSRoleExists("aws_iam_role.role_update_test", &conf), + ), + }, + + resource.TestStep{ + Config: testAccAWSRolePost, + Check: resource.ComposeTestCheckFunc( + testAccCheckAWSRoleExists("aws_iam_role.role_update_test", &conf), + ), + }, + }, + }) +} + func testAccCheckAWSRoleDestroy(s *terraform.State) error { iamconn := testAccProvider.Meta().(*AWSClient).iamconn @@ -105,3 +130,101 @@ resource "aws_iam_role" "role" { assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}" } ` + +const testAccAWSRolePre = ` +resource "aws_iam_role" "role_update_test" { + name = "tf_old_name" + path = "/test/" + assume_role_policy = <