add works but need tests

This commit is contained in:
Patrick Gray 2015-06-17 10:56:33 -04:00
parent 73e8191983
commit 2135ff02b7
2 changed files with 431 additions and 161 deletions

View File

@ -1,185 +1,313 @@
package aws package aws
import ( import (
"fmt" "fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/iam" "github.com/aws/aws-sdk-go/service/iam"
"github.com/hashicorp/terraform/helper/schema" "github.com/hashicorp/terraform/helper/schema"
) )
func resourceAwsIamPolicyAttach() *schema.Resource { func resourceAwsIamPolicyAttachment() *schema.Resource {
return &schema.Resource{ return &schema.Resource{
Create: resourceAwsIamPolicyAttachCreate, Create: resourceAwsIamPolicyAttachmentCreate,
Read: resourceAwsIamPolicyAttachRead, Read: resourceAwsIamPolicyAttachmentRead,
Update: resourceAwsIamPolicyAttachUpdate, Update: resourceAwsIamPolicyAttachmentUpdate,
Delete: resourceAwsIamPolicyAttachDelete, Delete: resourceAwsIamPolicyAttachmentDelete,
Schema: map[]*schema.Schema{ Schema: map[string]*schema.Schema{
"name": &schema.Schema{ "name": &schema.Schema{
Type: schema.TypeString, Type: schema.TypeString,
Required: true, Required: true,
ForceNew: true, ForceNew: true,
}, },
"users": &schema.Schema{ "users": &schema.Schema{
Type: schema.TypeSet, Type: schema.TypeSet,
Optional: true, Optional: true,
Elem: &schema.Schema{Type: schema.TypeString}, Elem: &schema.Schema{Type: schema.TypeString},
}, Set: schema.HashString,
"roles": &schema.Schema{ },
Type: schema.TypeSet, "roles": &schema.Schema{
Optional: true, Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString}, Optional: true,
}, Elem: &schema.Schema{Type: schema.TypeString},
"groups": &schema.Schema{ Set: schema.HashString,
Type: schema.TypeSet, },
Optional: true, "groups": &schema.Schema{
Elem: &schema.Schema{Type: schema.TypeString}, Type: schema.TypeSet,
}, Optional: true,
"arn": &schema.Schema{ Elem: &schema.Schema{Type: schema.TypeString},
Type: schema.TypeString, Set: schema.HashString,
Required: true, },
}, "policy_arn": &schema.Schema{
}, Type: schema.TypeString,
} Required: true,
ForceNew: true,
},
},
}
} }
func resourceAwsIamPolicyAttachCreate(d *schema.ResourceData, meta interface{}) error { func resourceAwsIamPolicyAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).iamconn conn := meta.(*AWSClient).iamconn
name := d.Get("name").(string) name := d.Get("name").(string)
arn := d.Get("arn").(string) arn := d.Get("policy_arn").(string)
users := expandStringList(d.Get("users").(*schema.Set).List()) users := expandStringList(d.Get("users").(*schema.Set).List())
roles := expandStringList(d.Get("roles").(*schema.Set).List()) roles := expandStringList(d.Get("roles").(*schema.Set).List())
groups := expandStringList(d.Get("groups").(*schema.Set).List()) groups := expandStringList(d.Get("groups").(*schema.Set).List())
if users == nil && roles == nil && groups == nil { if users == nil && roles == nil && groups == nil {
return fmt.Errorf("[WARN] No Users, Roles, or Groups specified for %s", d.Get("name").(string)) return fmt.Errorf("[WARN] No Users, Roles, or Groups specified for %s", name)
} } else {
else { var userErr, roleErr, groupErr error
var userErr, roleErr, groupErr error if users != nil {
if users != nil { userErr = attachPolicyToUsers(conn, users, arn)
userErr = attachPolicyToUsers(conn, users, arn) }
} if roles != nil {
if roles != nil { roleErr = attachPolicyToRoles(conn, roles, arn)
roleErr = attachPolicyToRoles(conn, roles, arn) }
} if groups != nil {
if groups != nil { groupErr = attachPolicyToGroups(conn, groups, arn)
groupErr = attachPolicyToGroups(conn, groups, arn) }
} if userErr != nil || roleErr != nil || groupErr != nil {
if userErr != nil || roleErr != nil || groupErr != nil { return fmt.Errorf("[WARN] Error attaching policy with IAM Policy Attach (%s), error:\n users - %v\n roles - %v\n groups - %v", name, userErr, roleErr, groupErr)
return fmt.Errorf("[WARN] Error attaching policy with IAM Policy Attach (%s), error:\n users - %v\n roles - %v\n groups - %v", name, userErr, roleErr, groupErr) }
} }
} return resourceAwsIamPolicyAttachmentRead(d, meta)
return resourceAwsIamPolicyAttachRead(d, meta)
} }
func resourceAwsIamPolicyAttachRead(d *schema.ResourceData, meta interface{}) error { func resourceAwsIamPolicyAttachmentRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).iamconn conn := meta.(*AWSClient).iamconn
users := expandStringList(d.Get("users").(*schema.Set).List()) arn := d.Get("policy_arn").(string)
roles := expandStringList(d.Get("roles").(*schema.Set).List()) name := d.Get("name").(string)
groups := expandStringList(d.Get("groups").(*schema.Set).List())
_, err := conn.GetPolicy(&iam.GetPolicyInput{
PolicyARN: aws.String(arn),
})
return nil if err != nil {
} if awsErr, ok := err.(awserr.Error); ok {
func resourceAwsIamPolicyAttachUpdate(d *schema.ResourceData, meta interface{}) error { if awsErr.Code() == "NoSuchIdentity" {
conn := meta.(*AWSClient).iamconn d.SetId("")
return nil
}
}
return err
}
return nil policyEntities, err := conn.ListEntitiesForPolicy(&iam.ListEntitiesForPolicyInput{
PolicyARN: aws.String(arn),
})
if err != nil {
return err
}
ul := make([]string, 0, len(policyEntities.PolicyUsers))
rl := make([]string, 0, len(policyEntities.PolicyRoles))
gl := make([]string, 0, len(policyEntities.PolicyGroups))
for _, u := range policyEntities.PolicyUsers {
ul = append(ul, *u.UserName)
}
for _, r := range policyEntities.PolicyRoles {
rl = append(rl, *r.RoleName)
}
for _, g := range policyEntities.PolicyGroups {
gl = append(gl, *g.GroupName)
}
userErr := d.Set("users", ul)
roleErr := d.Set("roles", rl)
groupErr := d.Set("groups", gl)
if userErr != nil || roleErr != nil || groupErr != nil {
return fmt.Errorf("[WARN} Error setting user, role, or group list from IAM Policy Attach (%s):\n user error - %s\n role error - %s\n group error - %s", name, userErr, roleErr, groupErr)
}
return nil
} }
func resourceAwsIamPolicyAttachDelete(d *schema.ResourceData, meta interface{}) error { func resourceAwsIamPolicyAttachmentUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).iamconn conn := meta.(*AWSClient).iamconn
name := d.Get("name").(string) name := d.Get("name").(string)
arn := d.Id() var userErr, roleErr, groupErr error
users := expandStringList(d.Get("users").(*schema.Set).List())
roles := expandStringList(d.Get("roles").(*schema.Set).List()) if d.HasChange("users") {
groups := expandStringList(d.Get("groups").(*schema.Set).List()) userErr = updateUsers(conn, d, meta)
}
var userErr, roleErr, groupErr error if d.HasChange("roles") {
if users != nil { roleErr = updateRoles(conn, d, meta)
userErr = detachPolicyFromUsers(conn, users, arn) }
} if d.HasChange("groups") {
if roles != nil { groupErr = updateGroups(conn, d, meta)
roleErr = detachPolicyFromRoles(conn, roles, arn) }
} if userErr != nil || roleErr != nil || groupErr != nil {
if groups != nil { return fmt.Errorf("[WARN] Error updating user, role, or group list from IAM Policy Attach (%s):\n user error - %s\n role error - %s\n group error - %s", name, userErr, roleErr, groupErr)
groupErr = detachPolicyFromGroups(conn, groups, arn) }
} return nil
if userErr != nil || roleErr != nil || groupErr != nil {
return fmt.Errorf("Error detaching policy with IAM Policy Attach (%s), error:\n users - %v\n roles - %v\ groups - %v", name, userErr, roleErr, groupErr)
}
return nil
} }
func attachPolicyToUsers (conn *iam.IAM, users []*string, arn string) { func resourceAwsIamPolicyAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
for _, u := range users { conn := meta.(*AWSClient).iamconn
_, err := conn.AttachGroupPolicy(&iam.AttachGroupPolicy{ name := d.Get("name").(string)
GroupName: u, arn := d.Get("policy_arn").(string)
PolicyArn: aws.String(arn), users := expandStringList(d.Get("users").(*schema.Set).List())
}) roles := expandStringList(d.Get("roles").(*schema.Set).List())
if err != nil { groups := expandStringList(d.Get("groups").(*schema.Set).List())
return err
} var userErr, roleErr, groupErr error
} if users != nil {
return nil userErr = detachPolicyFromUsers(conn, users, arn)
}
if roles != nil {
roleErr = detachPolicyFromRoles(conn, roles, arn)
}
if groups != nil {
groupErr = detachPolicyFromGroups(conn, groups, arn)
}
if userErr != nil || roleErr != nil || groupErr != nil {
return fmt.Errorf("[WARN] Error removing user, role, or group list from IAM Policy Detach (%s), error:\n users - %v\n roles - %v\n groups - %v", name, userErr, roleErr, groupErr)
}
return nil
} }
func attachPolicyToRoles (conn *iam.IAM, roles []*string, arn string) { func attachPolicyToUsers(conn *iam.IAM, users []*string, arn string) error {
for _, r := range roles { for _, u := range users {
_, err := conn.AttachRolePolicy(&iam.AttachRolePolicy{ _, err := conn.AttachUserPolicy(&iam.AttachUserPolicyInput{
RoleName: u, UserName: u,
PolicyArn: aws.String(arn), PolicyARN: aws.String(arn),
}) })
if err != nil { if err != nil {
return err return err
} }
} }
return nil return nil
}
func attachPolicyToRoles(conn *iam.IAM, roles []*string, arn string) error {
for _, r := range roles {
_, err := conn.AttachRolePolicy(&iam.AttachRolePolicyInput{
RoleName: r,
PolicyARN: aws.String(arn),
})
if err != nil {
return err
}
}
return nil
}
func attachPolicyToGroups(conn *iam.IAM, groups []*string, arn string) error {
for _, g := range groups {
_, err := conn.AttachGroupPolicy(&iam.AttachGroupPolicyInput{
GroupName: g,
PolicyARN: aws.String(arn),
})
if err != nil {
return err
}
}
return nil
}
func updateUsers(conn *iam.IAM, d *schema.ResourceData, meta interface{}) error {
arn := d.Get("policy_arn").(string)
o, n := d.GetChange("users")
if o == nil {
o = new(schema.Set)
}
if n == nil {
n = new(schema.Set)
}
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove := expandStringList(os.Difference(ns).List())
add := expandStringList(ns.Difference(os).List())
if rErr := detachPolicyFromUsers(conn, remove, arn); rErr != nil {
return rErr
}
if aErr := attachPolicyToUsers(conn, add, arn); aErr != nil {
return aErr
}
return nil
}
func updateRoles(conn *iam.IAM, d *schema.ResourceData, meta interface{}) error {
arn := d.Get("policy_arn").(string)
o, n := d.GetChange("roles")
if o == nil {
o = new(schema.Set)
}
if n == nil {
n = new(schema.Set)
}
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove := expandStringList(os.Difference(ns).List())
add := expandStringList(ns.Difference(os).List())
if rErr := detachPolicyFromRoles(conn, remove, arn); rErr != nil {
return rErr
}
if aErr := attachPolicyToRoles(conn, add, arn); aErr != nil {
return aErr
}
return nil
}
func updateGroups(conn *iam.IAM, d *schema.ResourceData, meta interface{}) error {
arn := d.Get("policy_arn").(string)
o, n := d.GetChange("groups")
if o == nil {
o = new(schema.Set)
}
if n == nil {
n = new(schema.Set)
}
os := o.(*schema.Set)
ns := n.(*schema.Set)
remove := expandStringList(os.Difference(ns).List())
add := expandStringList(ns.Difference(os).List())
if rErr := detachPolicyFromGroups(conn, remove, arn); rErr != nil {
return rErr
}
if aErr := attachPolicyToGroups(conn, add, arn); aErr != nil {
return aErr
}
return nil
} }
func attachPolicyToGroups (conn *iam.IAM, groups []*string, arn string) { func detachPolicyFromUsers(conn *iam.IAM, users []*string, arn string) error {
for _, g := range groups { for _, u := range users {
_, err := conn.AttachGroupPolicy(&iam.AttachGroupPolicy{ _, err := conn.DetachUserPolicy(&iam.DetachUserPolicyInput{
GroupName: g, UserName: u,
PolicyArn: aws.String(arn), PolicyARN: aws.String(arn),
}) })
if err != nil { if err != nil {
return err return err
} }
} }
return nil return nil
} }
func detachPolicyFromUsers(conn *iam.IAM, users []*string, arn string) { func detachPolicyFromRoles(conn *iam.IAM, roles []*string, arn string) error {
for _, u := range users { for _, r := range roles {
_, err := conn.DetachUserPolicy(&iam.DetachUserPolicy{ _, err := conn.DetachRolePolicy(&iam.DetachRolePolicyInput{
UserName: u, RoleName: r,
PolicyArn: aws.String(arn), PolicyARN: aws.String(arn),
} })
if err != nil { if err != nil {
return err return err
} }
} }
return nil return nil
} }
func detachPolicyFromRoles(conn *iam.IAM, roles []*string, arn string) { func detachPolicyFromGroups(conn *iam.IAM, groups []*string, arn string) error {
for _, r := range roles { for _, g := range groups {
_, err := conn.DetachRolePolicy(&iam.DetachRolePolicy{ _, err := conn.DetachGroupPolicy(&iam.DetachGroupPolicyInput{
RoleName: r, GroupName: g,
PolicyArn: aws.String(arn), PolicyARN: aws.String(arn),
} })
if err != nil { if err != nil {
return err return err
} }
} }
return nil return nil
}
func detachPolicyFromGroups(conn *iam.IAM, groups []*string, arn string) {
for _, g := range groups {
_, err := conn.DetachGroupPolicy(&iam.DetachGroupPolicy{
GroupName: g,
PolicyArn: aws.String(arn),
}
if err != nil {
return err
}
}
return nil
} }

View File

@ -9,6 +9,148 @@ import (
"testing" "testing"
) )
const testAccAWSPolicyAttachConfig = ` func TestAccAWSPolicyAttach_basic(t *testing.T) {
var policy iam.GetPolicyOutput
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAWSPolicyAttachmentDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccAWSPolicyAttachConfig,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSPolicyAttachmentExists(),
testAccCheckAWSPolicyAttachmentAttributes(),
),
},
resource.TestStep{
Config: testAccAWSPolicyAttachConfigUpdate,
Check: resource.ComposeTestCheckFunc(
testAccCheckAWSPolicyAttachmentExists(),
testAccCheckAWSPolicyAttachmentAttributes(),
),
},
},
})
}
func testAccCheckAWSPolicyAttachmentDestroy(s *terraform.State) error {
return nil
}
func testAccCheckAWSPolicyAttachmentExists(s *terraform.State) error {
conn := testAccProvider.Meta().(*AWSClient).iamconn
return nil
}
func testAccCheckAWSPolicyAttachmentAttributes() error {
return nil
}
const testAccAWSPolicyAttachConfig = `
resource "aws_iam_user" "user" {
name = "test-user"
}
resource "aws_iam_role" "role" {
name = "test-role"
}
resource "aws_iam_group" "group" {
name = "test-group"
}
resource "aws_iam_policy" "policy" {
name = "test-policy"
description = "A test policy"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"iam:ChangePassword"
],
"Resource": "*",
"Effect": "Allow"
}
]
}
EOF
}
resource "aws_iam_policy_attach" "test-attach" {
name = "test-attachment"
users = ["${aws_iam_user.user.name}"]
roles = ["${aws_iam_role.role.name}"]
groups = ["${aws_iam_group.group.name}"]
policy_arn = "${aws_iam_policy.policy.arn}"
}
`
const testAccAWSPolicyAttachConfigUpdate = `
resource "aws_iam_user" "user" {
name = "test-user"
}
resource "aws_iam_user" "user2" {
name = "test-user2"
}
resource "aws_iam_user" "user3" {
name = "test-user3"
}
resource "aws_iam_role" "role" {
name = "test-role"
}
resource "aws_iam_role" "role2" {
name = "test-role2"
}
resource "aws_iam_role" "role3" {
name = "test-role3"
}
resource "aws_iam_group" "group" {
name = "test-group"
}
resource "aws_iam_group" "group2" {
name = "test-group2"
}
resource "aws_iam_group" "group3" {
name = "test-group3"
}
resource "aws_iam_policy" "policy" {
name = "test-policy"
description = "A test policy"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"iam:ChangePassword"
],
"Resource": "*",
"Effect": "Allow"
}
]
}
EOF
}
resource "aws_iam_policy_attach" "test-attach" {
name = "test-attachment"
users = [
"${aws_iam_user.user2.name}",
"${aws_iam_user.user3.name}"
]
roles = [
"${aws_iam_role.role2.name}",
"${aws_iam_role.role3.name}"
]
groups = [
"${aws_iam_group.group2.name}",
"${aws_iam_group.group3.name}"
]
policy_arn = "${aws_iam_policy.policy.arn}"
}
` `