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

resource/aws_iam_role: Add permissions_boundary argument #5184

Merged
merged 1 commit into from
Jul 26, 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
88 changes: 58 additions & 30 deletions aws/resource_aws_iam_role.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"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"
Expand Down Expand Up @@ -85,6 +84,12 @@ func resourceAwsIamRole() *schema.Resource {
ForceNew: true,
},

"permissions_boundary": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(20, 2048),
},

"description": {
Type: schema.TypeString,
Optional: true,
Expand Down Expand Up @@ -151,6 +156,10 @@ func resourceAwsIamRoleCreate(d *schema.ResourceData, meta interface{}) error {
request.MaxSessionDuration = aws.Int64(int64(v.(int)))
}

if v, ok := d.GetOk("permissions_boundary"); ok {
request.PermissionsBoundary = aws.String(v.(string))
}

var createResp *iam.CreateRoleOutput
err := resource.Retry(30*time.Second, func() *resource.RetryError {
var err error
Expand Down Expand Up @@ -178,7 +187,8 @@ func resourceAwsIamRoleRead(d *schema.ResourceData, meta interface{}) error {

getResp, err := iamconn.GetRole(request)
if err != nil {
if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" { // XXX test me
if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") { // XXX test me
log.Printf("[WARN] IAM Role %q not found, removing from state", d.Id())
d.SetId("")
return nil
}
Expand All @@ -187,31 +197,18 @@ func resourceAwsIamRoleRead(d *schema.ResourceData, meta interface{}) error {

role := getResp.Role

if err := d.Set("name", role.RoleName); err != nil {
return err
}
if err := d.Set("max_session_duration", role.MaxSessionDuration); err != nil {
return err
}
if err := d.Set("arn", role.Arn); err != nil {
return err
}
if err := d.Set("path", role.Path); err != nil {
return err
}
if err := d.Set("unique_id", role.RoleId); err != nil {
return err
}
d.Set("arn", role.Arn)
if err := d.Set("create_date", role.CreateDate.Format(time.RFC3339)); err != nil {
return err
}

if role.Description != nil {
// the description isn't present in the response to CreateRole.
if err := d.Set("description", role.Description); err != nil {
return err
}
d.Set("description", role.Description)
d.Set("max_session_duration", role.MaxSessionDuration)
d.Set("name", role.RoleName)
d.Set("path", role.Path)
if role.PermissionsBoundary != nil {
d.Set("permissions_boundary", role.PermissionsBoundary.PermissionsBoundaryArn)
}
d.Set("unique_id", role.RoleId)

assumRolePolicy, err := url.QueryUnescape(*role.AssumeRolePolicyDocument)
if err != nil {
Expand All @@ -233,7 +230,7 @@ func resourceAwsIamRoleUpdate(d *schema.ResourceData, meta interface{}) error {
}
_, err := iamconn.UpdateAssumeRolePolicy(assumeRolePolicyInput)
if err != nil {
if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" {
if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") {
d.SetId("")
return nil
}
Expand All @@ -248,7 +245,7 @@ func resourceAwsIamRoleUpdate(d *schema.ResourceData, meta interface{}) error {
}
_, err := iamconn.UpdateRoleDescription(roleDescriptionInput)
if err != nil {
if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" {
if isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") {
d.SetId("")
return nil
}
Expand All @@ -271,7 +268,29 @@ func resourceAwsIamRoleUpdate(d *schema.ResourceData, meta interface{}) error {
}
}

return nil
if d.HasChange("permissions_boundary") {
permissionsBoundary := d.Get("permissions_boundary").(string)
if permissionsBoundary != "" {
input := &iam.PutRolePermissionsBoundaryInput{
PermissionsBoundary: aws.String(permissionsBoundary),
RoleName: aws.String(d.Id()),
}
_, err := iamconn.PutRolePermissionsBoundary(input)
if err != nil {
return fmt.Errorf("error updating IAM Role permissions boundary: %s", err)
}
} else {
input := &iam.DeleteRolePermissionsBoundaryInput{
RoleName: aws.String(d.Id()),
}
_, err := iamconn.DeleteRolePermissionsBoundary(input)
if err != nil {
return fmt.Errorf("error deleting IAM Role permissions boundary: %s", err)
}
}
}

return resourceAwsIamRoleRead(d, meta)
}

func resourceAwsIamRoleDelete(d *schema.ResourceData, meta interface{}) error {
Expand Down Expand Up @@ -358,16 +377,25 @@ func resourceAwsIamRoleDelete(d *schema.ResourceData, meta interface{}) error {
}
}

request := &iam.DeleteRoleInput{
deleteRolePermissionsBoundaryInput := &iam.DeleteRolePermissionsBoundaryInput{
RoleName: aws.String(d.Id()),
}

log.Println("[DEBUG] Delete IAM Role Permissions Boundary request:", deleteRolePermissionsBoundaryInput)
_, err = iamconn.DeleteRolePermissionsBoundary(deleteRolePermissionsBoundaryInput)
if err != nil && !isAWSErr(err, iam.ErrCodeNoSuchEntityException, "") {
return fmt.Errorf("Error deleting IAM Role %s Permissions Boundary: %s", d.Id(), err)
}

deleteRoleInput := &iam.DeleteRoleInput{
RoleName: aws.String(d.Id()),
}

// IAM is eventually consistent and deletion of attached policies may take time
return resource.Retry(30*time.Second, func() *resource.RetryError {
_, err := iamconn.DeleteRole(request)
_, err := iamconn.DeleteRole(deleteRoleInput)
if err != nil {
awsErr, ok := err.(awserr.Error)
if ok && awsErr.Code() == "DeleteConflict" {
if isAWSErr(err, iam.ErrCodeDeleteConflictException, "") {
return resource.RetryableError(err)
}

Expand Down
76 changes: 74 additions & 2 deletions aws/resource_aws_iam_role_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,63 @@ func TestAccAWSIAMRole_MaxSessionDuration(t *testing.T) {
})
}

func TestAccAWSIAMRole_PermissionsBoundary(t *testing.T) {
var role iam.GetRoleOutput

rName := acctest.RandString(10)
resourceName := "aws_iam_role.role"

permissionsBoundary1 := fmt.Sprintf("arn:%s:iam::aws:policy/AdministratorAccess", testAccGetPartition())
permissionsBoundary2 := fmt.Sprintf("arn:%s:iam::aws:policy/ReadOnlyAccess", testAccGetPartition())

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSUserDestroy,
Steps: []resource.TestStep{
// Test creation
{
Config: testAccCheckIAMRoleConfig_PermissionsBoundary(rName, permissionsBoundary1),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSRoleExists(resourceName, &role),
resource.TestCheckResourceAttr(resourceName, "permissions_boundary", permissionsBoundary1),
),
},
// Test update
{
Config: testAccCheckIAMRoleConfig_PermissionsBoundary(rName, permissionsBoundary2),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSRoleExists(resourceName, &role),
resource.TestCheckResourceAttr(resourceName, "permissions_boundary", permissionsBoundary2),
),
},
// Test import
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"force_destroy"},
},
// Test removal
{
Config: testAccAWSIAMRoleConfig(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSRoleExists(resourceName, &role),
resource.TestCheckResourceAttr(resourceName, "permissions_boundary", ""),
),
},
// Test addition
{
Config: testAccCheckIAMRoleConfig_PermissionsBoundary(rName, permissionsBoundary1),
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSRoleExists(resourceName, &role),
resource.TestCheckResourceAttr(resourceName, "permissions_boundary", permissionsBoundary1),
),
},
},
})
}

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

Expand Down Expand Up @@ -313,6 +370,17 @@ resource "aws_iam_role" "test" {
`, rName, maxSessionDuration)
}

func testAccCheckIAMRoleConfig_PermissionsBoundary(rName, permissionsBoundary string) string {
return fmt.Sprintf(`
resource "aws_iam_role" "role" {
assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}"
name = "test-role-%s"
path = "/"
permissions_boundary = %q
}
`, rName, permissionsBoundary)
}

func testAccAWSIAMRoleConfig(rName string) string {
return fmt.Sprintf(`
resource "aws_iam_role" "role" {
Expand Down Expand Up @@ -357,6 +425,8 @@ resource "aws_iam_role" "role" {

func testAccAWSIAMRolePre(rName string) string {
return fmt.Sprintf(`
data "aws_partition" "current" {}

resource "aws_iam_role" "role_update_test" {
name = "tf_old_name_%s"
path = "/test/"
Expand Down Expand Up @@ -390,7 +460,7 @@ resource "aws_iam_role_policy" "role_update_test" {
"s3:GetBucketLocation",
"s3:ListAllMyBuckets"
],
"Resource": "arn:aws:s3:::*"
"Resource": "arn:${data.aws_partition.current.partition}:s3:::*"
}
]
}
Expand All @@ -407,6 +477,8 @@ resource "aws_iam_instance_profile" "role_update_test" {

func testAccAWSIAMRolePost(rName string) string {
return fmt.Sprintf(`
data "aws_partition" "current" {}

resource "aws_iam_role" "role_update_test" {
name = "tf_new_name_%s"
path = "/test/"
Expand Down Expand Up @@ -440,7 +512,7 @@ resource "aws_iam_role_policy" "role_update_test" {
"s3:GetBucketLocation",
"s3:ListAllMyBuckets"
],
"Resource": "arn:aws:s3:::*"
"Resource": "arn:${data.aws_partition.current.partition}:s3:::*"
}
]
}
Expand Down
1 change: 1 addition & 0 deletions website/docs/r/iam_role.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ The following arguments are supported:
* `description` - (Optional) The description of the role.

* `max_session_duration` - (Optional) The maximum session duration (in seconds) that you want to set for the specified role. If you do not specify a value for this setting, the default maximum of one hour is applied. This setting can have a value from 1 hour to 12 hours.
* `permissions_boundary` - (Optional) The ARN of the policy that is used to set the permissions boundary for the role.

## Attributes Reference

Expand Down