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

service/iam: Import inline IAM user policies on terraform import of IAM user #2931

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 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
65 changes: 65 additions & 0 deletions aws/import_aws_iam_user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package aws

import (
"fmt"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/schema"
)

func awsIamUserInlinePolicies(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
results := make([]*schema.ResourceData, 0)
conn := meta.(*AWSClient).iamconn
policyNames := make([]*string, 0)
err := conn.ListUserPoliciesPages(&iam.ListUserPoliciesInput{
UserName: aws.String(d.Id()),
}, func(page *iam.ListUserPoliciesOutput, lastPage bool) bool {
for _, policyName := range page.PolicyNames {
policyNames = append(policyNames, policyName)
}

return lastPage
})
if err != nil {
return nil, err
}

for _, policyName := range policyNames {
policy, err := conn.GetUserPolicy(&iam.GetUserPolicyInput{
PolicyName: policyName,
UserName: aws.String(d.Id()),
})
if err != nil {
return nil, errwrap.Wrapf("Error importing AWS IAM User Policy: {{err}}", err)
}

policyResource := resourceAwsIamUserPolicy()
pData := policyResource.Data(nil)
pData.SetId(fmt.Sprintf("%s:%s", *policy.UserName, *policy.PolicyName))
pData.SetType("aws_iam_user_policy")
pData.Set("name", policy.PolicyName)
pData.Set("policy", policy.PolicyDocument)
pData.Set("user", policy.UserName)
results = append(results, pData)
}

return results, nil
}

func resourceAwsIamUserImportState(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
results := make([]*schema.ResourceData, 1)
results[0] = d

policyData, err := awsIamUserInlinePolicies(d, meta)
if err != nil {
return nil, err
}

for _, data := range policyData {
results = append(results, data)
}

return results, nil
}
54 changes: 54 additions & 0 deletions aws/import_aws_iam_user_policy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package aws

import (
"fmt"
"testing"

"github.com/hashicorp/terraform/helper/resource"
)

func testAccAwsIamUserPolicyConfig(suffix string) string {
return fmt.Sprintf(`
resource "aws_iam_user" "user_%[1]s" {
name = "tf_test_user_test_%[1]s"
path = "/"
}

resource "aws_iam_user_policy" "foo_%[1]s" {
name = "tf_test_policy_test_%[1]s"
user = "${aws_iam_user.user_%[1]s.name}"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}
}
EOF
}
`, suffix)
}

func TestAccAWSIAMUserPolicy_importBasic(t *testing.T) {
suffix := randomString(10)
resourceName := fmt.Sprintf("aws_iam_user_policy.foo_%s", suffix)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckIAMUserPolicyDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAwsIamUserPolicyConfig(suffix),
},

resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}
52 changes: 52 additions & 0 deletions aws/import_aws_iam_user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSUser_importBasic(t *testing.T) {
Expand All @@ -32,3 +33,54 @@ func TestAccAWSUser_importBasic(t *testing.T) {
},
})
}

func TestAccAWSUser_importWithPolicy(t *testing.T) {
resourceName := "aws_iam_user.user"

rInt := acctest.RandInt()

checkFn := func(s []*terraform.InstanceState) error {
// Expect 2: user + policy
if len(s) != 2 {
return fmt.Errorf("expected 2 states: %#v", s)
}

// TODO: Is this order guaranteed?
policyState, userState := s[0], s[1]

expectedUserId := fmt.Sprintf("test_user_%d", rInt)
expectedPolicyId := fmt.Sprintf("test_user_%d:foo_policy_%d", rInt, rInt)

if userState.ID != expectedUserId {
return fmt.Errorf("expected user of ID %s, %s received",
expectedUserId, userState.ID)
}

if policyState.ID != expectedPolicyId {
return fmt.Errorf("expected policy of ID %s, %s received",
expectedPolicyId, policyState.ID)
}

return nil
}

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSUserDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccIAMUserPolicyConfig(rInt),
},

resource.TestStep{
ResourceName: resourceName,
ImportState: true,
ImportStateCheck: checkFn,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{
"force_destroy"},
},
},
})
}
2 changes: 1 addition & 1 deletion aws/resource_aws_iam_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func resourceAwsIamUser() *schema.Resource {
Update: resourceAwsIamUserUpdate,
Delete: resourceAwsIamUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
State: resourceAwsIamUserImportState,
},

Schema: map[string]*schema.Schema{
Expand Down
30 changes: 25 additions & 5 deletions aws/resource_aws_iam_user_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ func resourceAwsIamUserPolicy() *schema.Resource {
Create: resourceAwsIamUserPolicyPut,
Update: resourceAwsIamUserPolicyPut,

Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Read: resourceAwsIamUserPolicyRead,
Delete: resourceAwsIamUserPolicyDelete,

Expand Down Expand Up @@ -81,14 +85,16 @@ func resourceAwsIamUserPolicyPut(d *schema.ResourceData, meta interface{}) error
func resourceAwsIamUserPolicyRead(d *schema.ResourceData, meta interface{}) error {
iamconn := meta.(*AWSClient).iamconn

user, name := resourceAwsIamUserPolicyParseId(d.Id())
user, name, err := resourceAwsIamUserPolicyParseId(d.Id())
if err != nil {
return err
}

request := &iam.GetUserPolicyInput{
PolicyName: aws.String(name),
UserName: aws.String(user),
}

var err error
getResp, err := iamconn.GetUserPolicy(request)
if err != nil {
if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" { // XXX test me
Expand All @@ -106,13 +112,22 @@ func resourceAwsIamUserPolicyRead(d *schema.ResourceData, meta interface{}) erro
if err != nil {
return err
}
return d.Set("policy", policy)
if err := d.Set("policy", policy); err != nil {
return err
}
if err := d.Set("name", name); err != nil {
return err
}
return d.Set("user", user)
}

func resourceAwsIamUserPolicyDelete(d *schema.ResourceData, meta interface{}) error {
iamconn := meta.(*AWSClient).iamconn

user, name := resourceAwsIamUserPolicyParseId(d.Id())
user, name, err := resourceAwsIamUserPolicyParseId(d.Id())
if err != nil {
return err
}

request := &iam.DeleteUserPolicyInput{
PolicyName: aws.String(name),
Expand All @@ -125,8 +140,13 @@ func resourceAwsIamUserPolicyDelete(d *schema.ResourceData, meta interface{}) er
return nil
}

func resourceAwsIamUserPolicyParseId(id string) (userName, policyName string) {
func resourceAwsIamUserPolicyParseId(id string) (userName, policyName string, err error) {
parts := strings.SplitN(id, ":", 2)
if len(parts) != 2 {
err = fmt.Errorf("user_policy id must be of the form <user name>:<policy name>")
return
}

userName = parts[0]
policyName = parts[1]
return
Expand Down
16 changes: 11 additions & 5 deletions aws/resource_aws_iam_user_policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,14 +190,16 @@ func testAccCheckIAMUserPolicyDestroy(s *terraform.State) error {
continue
}

user, name := resourceAwsIamUserPolicyParseId(rs.Primary.ID)
user, name, err := resourceAwsIamUserPolicyParseId(rs.Primary.ID)
if err != nil {
return err
}

request := &iam.GetUserPolicyInput{
PolicyName: aws.String(name),
UserName: aws.String(user),
}

var err error
getResp, err := iamconn.GetUserPolicy(request)
if err != nil {
if iamerr, ok := err.(awserr.Error); ok && iamerr.Code() == "NoSuchEntity" {
Expand All @@ -208,7 +210,7 @@ func testAccCheckIAMUserPolicyDestroy(s *terraform.State) error {
}

if getResp != nil {
return fmt.Errorf("Found IAM user policy, expected none: %s", getResp)
return fmt.Errorf("Found IAM User, expected none: %s", getResp)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

pulled in post-merge, we should remove this.

}
}

Expand All @@ -234,8 +236,12 @@ func testAccCheckIAMUserPolicy(
}

iamconn := testAccProvider.Meta().(*AWSClient).iamconn
username, name := resourceAwsIamUserPolicyParseId(policy.Primary.ID)
_, err := iamconn.GetUserPolicy(&iam.GetUserPolicyInput{
username, name, err := resourceAwsIamUserPolicyParseId(policy.Primary.ID)
if err != nil {
return err
}

_, err = iamconn.GetUserPolicy(&iam.GetUserPolicyInput{
UserName: aws.String(username),
PolicyName: aws.String(name),
})
Expand Down