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

r/iam_role: Delete inline policies when force_detach_policies = true #2388

Merged
merged 4 commits into from
Jan 3, 2018
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
25 changes: 25 additions & 0 deletions aws/resource_aws_iam_role.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,31 @@ func resourceAwsIamRoleDelete(d *schema.ResourceData, meta interface{}) error {
}
}
}

// For inline policies
rolePolicyNames := make([]*string, 0)
err = iamconn.ListRolePoliciesPages(&iam.ListRolePoliciesInput{
RoleName: aws.String(d.Id()),
}, func(page *iam.ListRolePoliciesOutput, lastPage bool) bool {
for _, v := range page.PolicyNames {
rolePolicyNames = append(rolePolicyNames, v)
}
return len(page.PolicyNames) > 0
})
if err != nil {
return fmt.Errorf("Error listing inline Policies for IAM Role (%s) when trying to delete: %s", d.Id(), err)
}
if len(rolePolicyNames) > 0 {
for _, pname := range rolePolicyNames {
_, err := iamconn.DeleteRolePolicy(&iam.DeleteRolePolicyInput{
PolicyName: pname,
RoleName: aws.String(d.Id()),
})
if err != nil {
return fmt.Errorf("Error deleting inline policy of IAM Role %s: %s", d.Id(), err)
}
}
}
}

request := &iam.DeleteRoleInput{
Expand Down
119 changes: 119 additions & 0 deletions aws/resource_aws_iam_role_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,26 @@ func TestAccAWSIAMRole_badJSON(t *testing.T) {
})
}

func TestAccAWSIAMRole_force_detach_policies(t *testing.T) {
var conf iam.GetRoleOutput
rName := acctest.RandString(10)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSRoleDestroy,
Steps: []resource.TestStep{
{
Config: testAccAWSIAMRoleConfig_force_detach_policies(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSRoleExists("aws_iam_role.test", &conf),
testAccAddAwsIAMRolePolicy("aws_iam_role.test"),
),
},
},
})
}

func testAccCheckAWSRoleDestroy(s *terraform.State) error {
iamconn := testAccProvider.Meta().(*AWSClient).iamconn

Expand Down Expand Up @@ -210,6 +230,37 @@ func testAccCheckAWSRoleGeneratedNamePrefix(resource, prefix string) resource.Te
}
}

// Attach inline policy outside of terraform CRUD.
func testAccAddAwsIAMRolePolicy(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Resource not found")
}
if rs.Primary.ID == "" {
return fmt.Errorf("No Role name is set")
}

iamconn := testAccProvider.Meta().(*AWSClient).iamconn

input := &iam.PutRolePolicyInput{
RoleName: aws.String(rs.Primary.ID),
PolicyDocument: aws.String(`{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}
}`),
PolicyName: aws.String(resource.UniqueId()),
}

_, err := iamconn.PutRolePolicy(input)
return err
}
}

func testAccAWSIAMRoleConfig(rName string) string {
return fmt.Sprintf(`
resource "aws_iam_role" "role" {
Expand Down Expand Up @@ -375,3 +426,71 @@ POLICY
}
`, rName)
}

func testAccAWSIAMRoleConfig_force_detach_policies(rName string) string {
return fmt.Sprintf(`
resource "aws_iam_role_policy" "test" {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically we're not really testing the new functionality here IMO, because the policy will get destroyed first due to its relationship and force_destroy won't get chance to ever take action.
I think we'd need to remove those policies from state as part of the test in order to verify it actually works.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's right👍
But I couldn't have an idea to realize it... Could you give me advice?

Copy link
Member

@radeksimko radeksimko Dec 5, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So I think the easier way is to add policies outside of the config, instead of removing them from state. We could add testAccAddAWSIAMRolePolicy("aws_iam_role.test") to your new test:

		Steps: []resource.TestStep{
			{
				Config: testAccAWSIAMRoleConfig_force_detach_policies(rName),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAWSRoleExists("aws_iam_role.test", &conf),
					testAccAddAWSIAMRolePolicy("aws_iam_role.test"),
				),
			},
		},

which would just call the API to add a policy outside of any Terraform CRUD.

Testing framework will then attempt to destroy the role and exercise this new functionality.

name = "tf-iam-role-policy-%s"
role = "${aws_iam_role.test.id}"

policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"ec2:Describe*"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
EOF
}

resource "aws_iam_policy" "test" {
name = "tf-iam-policy-%s"
description = "A test policy"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"iam:ChangePassword"
],
"Resource": "*",
"Effect": "Allow"
}
]
}
EOF
}

resource "aws_iam_role_policy_attachment" "test" {
role = "${aws_iam_role.test.name}"
policy_arn = "${aws_iam_policy.test.arn}"
}

resource "aws_iam_role" "test" {
name = "tf-iam-role-%s"
force_detach_policies = true
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "ec2.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
`, rName, rName, rName)
}