github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/aws/resource_aws_iam_policy_attachment_test.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  
     7  	"github.com/aws/aws-sdk-go/aws"
     8  	"github.com/aws/aws-sdk-go/service/iam"
     9  	"github.com/hashicorp/terraform/helper/acctest"
    10  	"github.com/hashicorp/terraform/helper/resource"
    11  	"github.com/hashicorp/terraform/terraform"
    12  )
    13  
    14  func TestAccAWSPolicyAttachment_basic(t *testing.T) {
    15  	var out iam.ListEntitiesForPolicyOutput
    16  
    17  	user1 := fmt.Sprintf("test-user-%d", acctest.RandInt())
    18  	user2 := fmt.Sprintf("test-user-%d", acctest.RandInt())
    19  	user3 := fmt.Sprintf("test-user-%d", acctest.RandInt())
    20  
    21  	resource.Test(t, resource.TestCase{
    22  		PreCheck:     func() { testAccPreCheck(t) },
    23  		Providers:    testAccProviders,
    24  		CheckDestroy: testAccCheckAWSPolicyAttachmentDestroy,
    25  		Steps: []resource.TestStep{
    26  			resource.TestStep{
    27  				Config: testAccAWSPolicyAttachConfig(user1),
    28  				Check: resource.ComposeTestCheckFunc(
    29  					testAccCheckAWSPolicyAttachmentExists("aws_iam_policy_attachment.test-attach", 3, &out),
    30  					testAccCheckAWSPolicyAttachmentAttributes([]string{user1}, []string{"test-role"}, []string{"test-group"}, &out),
    31  				),
    32  			},
    33  			resource.TestStep{
    34  				Config: testAccAWSPolicyAttachConfigUpdate(user1, user2, user3),
    35  				Check: resource.ComposeTestCheckFunc(
    36  					testAccCheckAWSPolicyAttachmentExists("aws_iam_policy_attachment.test-attach", 6, &out),
    37  					testAccCheckAWSPolicyAttachmentAttributes([]string{user3, user3}, []string{"test-role2", "test-role3"}, []string{"test-group2", "test-group3"}, &out),
    38  				),
    39  			},
    40  		},
    41  	})
    42  }
    43  
    44  func TestAccAWSPolicyAttachment_paginatedEntities(t *testing.T) {
    45  	var out iam.ListEntitiesForPolicyOutput
    46  
    47  	resource.Test(t, resource.TestCase{
    48  		PreCheck:     func() { testAccPreCheck(t) },
    49  		Providers:    testAccProviders,
    50  		CheckDestroy: testAccCheckAWSPolicyAttachmentDestroy,
    51  		Steps: []resource.TestStep{
    52  			resource.TestStep{
    53  				Config: testAccAWSPolicyPaginatedAttachConfig,
    54  				Check: resource.ComposeTestCheckFunc(
    55  					testAccCheckAWSPolicyAttachmentExists("aws_iam_policy_attachment.test-paginated-attach", 101, &out),
    56  				),
    57  			},
    58  		},
    59  	})
    60  }
    61  
    62  func testAccCheckAWSPolicyAttachmentDestroy(s *terraform.State) error {
    63  	return nil
    64  }
    65  
    66  func testAccCheckAWSPolicyAttachmentExists(n string, c int64, out *iam.ListEntitiesForPolicyOutput) resource.TestCheckFunc {
    67  	return func(s *terraform.State) error {
    68  		rs, ok := s.RootModule().Resources[n]
    69  		if !ok {
    70  			return fmt.Errorf("Not found: %s", n)
    71  		}
    72  
    73  		if rs.Primary.ID == "" {
    74  			return fmt.Errorf("No policy name is set")
    75  		}
    76  
    77  		conn := testAccProvider.Meta().(*AWSClient).iamconn
    78  		arn := rs.Primary.Attributes["policy_arn"]
    79  
    80  		resp, err := conn.GetPolicy(&iam.GetPolicyInput{
    81  			PolicyArn: aws.String(arn),
    82  		})
    83  		if err != nil {
    84  			return fmt.Errorf("Error: Policy (%s) not found", n)
    85  		}
    86  		if c != *resp.Policy.AttachmentCount {
    87  			return fmt.Errorf("Error: Policy (%s) has wrong number of entities attached on initial creation", n)
    88  		}
    89  		resp2, err := conn.ListEntitiesForPolicy(&iam.ListEntitiesForPolicyInput{
    90  			PolicyArn: aws.String(arn),
    91  		})
    92  		if err != nil {
    93  			return fmt.Errorf("Error: Failed to get entities for Policy (%s)", arn)
    94  		}
    95  
    96  		*out = *resp2
    97  		return nil
    98  	}
    99  }
   100  
   101  func testAccCheckAWSPolicyAttachmentAttributes(users []string, roles []string, groups []string, out *iam.ListEntitiesForPolicyOutput) resource.TestCheckFunc {
   102  	return func(s *terraform.State) error {
   103  		uc := len(users)
   104  		rc := len(roles)
   105  		gc := len(groups)
   106  
   107  		for _, u := range users {
   108  			for _, pu := range out.PolicyUsers {
   109  				if u == *pu.UserName {
   110  					uc--
   111  				}
   112  			}
   113  		}
   114  		for _, r := range roles {
   115  			for _, pr := range out.PolicyRoles {
   116  				if r == *pr.RoleName {
   117  					rc--
   118  				}
   119  			}
   120  		}
   121  		for _, g := range groups {
   122  			for _, pg := range out.PolicyGroups {
   123  				if g == *pg.GroupName {
   124  					gc--
   125  				}
   126  			}
   127  		}
   128  		if uc != 0 || rc != 0 || gc != 0 {
   129  			return fmt.Errorf("Error: Number of attached users, roles, or groups was incorrect:\n expected %d users and found %d\nexpected %d roles and found %d\nexpected %d groups and found %d", len(users), len(users)-uc, len(roles), len(roles)-rc, len(groups), len(groups)-gc)
   130  		}
   131  		return nil
   132  	}
   133  }
   134  
   135  func testAccAWSPolicyAttachConfig(u1 string) string {
   136  	return fmt.Sprintf(`
   137  resource "aws_iam_user" "user" {
   138      name = "%s"
   139  }
   140  resource "aws_iam_role" "role" {
   141      name = "test-role"
   142  	  assume_role_policy = <<EOF
   143  {
   144    "Version": "2012-10-17",
   145    "Statement": [
   146      {
   147        "Action": "sts:AssumeRole",
   148        "Principal": {
   149          "Service": "ec2.amazonaws.com"
   150        },
   151        "Effect": "Allow",
   152        "Sid": ""
   153      }
   154    ]
   155  }
   156  EOF
   157  }
   158  resource "aws_iam_group" "group" {
   159      name = "test-group"
   160  }
   161  
   162  resource "aws_iam_policy" "policy" {
   163      name = "test-policy"
   164      description = "A test policy"
   165      policy = <<EOF
   166  {
   167    "Version": "2012-10-17",
   168    "Statement": [
   169      {
   170        "Action": [
   171          "iam:ChangePassword"
   172        ],
   173        "Resource": "*",
   174        "Effect": "Allow"
   175      }
   176    ]
   177  }
   178  EOF
   179  }
   180  
   181  resource "aws_iam_policy_attachment" "test-attach" {
   182      name = "test-attachment"
   183      users = ["${aws_iam_user.user.name}"]
   184      roles = ["${aws_iam_role.role.name}"]
   185      groups = ["${aws_iam_group.group.name}"]
   186      policy_arn = "${aws_iam_policy.policy.arn}"
   187  }`, u1)
   188  }
   189  
   190  func testAccAWSPolicyAttachConfigUpdate(u1, u2, u3 string) string {
   191  	return fmt.Sprintf(`
   192  resource "aws_iam_user" "user" {
   193      name = "%s"
   194  }
   195  resource "aws_iam_user" "user2" {
   196      name = "%s"
   197  }
   198  resource "aws_iam_user" "user3" {
   199      name = "%s"
   200  }
   201  resource "aws_iam_role" "role" {
   202      name = "test-role"
   203  	  assume_role_policy = <<EOF
   204  {
   205    "Version": "2012-10-17",
   206    "Statement": [
   207      {
   208        "Action": "sts:AssumeRole",
   209        "Principal": {
   210          "Service": "ec2.amazonaws.com"
   211        },
   212        "Effect": "Allow",
   213        "Sid": ""
   214      }
   215    ]
   216  }
   217  EOF
   218  }
   219  
   220  resource "aws_iam_role" "role2" {
   221      name = "test-role2"
   222  	  assume_role_policy = <<EOF
   223  {
   224    "Version": "2012-10-17",
   225    "Statement": [
   226      {
   227        "Action": "sts:AssumeRole",
   228        "Principal": {
   229          "Service": "ec2.amazonaws.com"
   230        },
   231        "Effect": "Allow",
   232        "Sid": ""
   233      }
   234    ]
   235  }
   236  EOF
   237  
   238  }
   239  resource "aws_iam_role" "role3" {
   240      name = "test-role3"
   241  	  assume_role_policy = <<EOF
   242  {
   243    "Version": "2012-10-17",
   244    "Statement": [
   245      {
   246        "Action": "sts:AssumeRole",
   247        "Principal": {
   248          "Service": "ec2.amazonaws.com"
   249        },
   250        "Effect": "Allow",
   251        "Sid": ""
   252      }
   253    ]
   254  }
   255  EOF
   256  
   257  }
   258  resource "aws_iam_group" "group" {
   259      name = "test-group"
   260  }
   261  resource "aws_iam_group" "group2" {
   262      name = "test-group2"
   263  }
   264  resource "aws_iam_group" "group3" {
   265      name = "test-group3"
   266  }
   267  
   268  resource "aws_iam_policy" "policy" {
   269      name = "test-policy"
   270      description = "A test policy"
   271      policy = <<EOF
   272  {
   273    "Version": "2012-10-17",
   274    "Statement": [
   275      {
   276        "Action": [
   277          "iam:ChangePassword"
   278        ],
   279        "Resource": "*",
   280        "Effect": "Allow"
   281      }
   282    ]
   283  }
   284  EOF
   285  }
   286  
   287  resource "aws_iam_policy_attachment" "test-attach" {
   288      name = "test-attachment"
   289      users = [
   290          "${aws_iam_user.user2.name}",
   291          "${aws_iam_user.user3.name}"
   292      ]
   293      roles = [
   294          "${aws_iam_role.role2.name}",
   295          "${aws_iam_role.role3.name}"
   296      ]
   297      groups = [
   298          "${aws_iam_group.group2.name}",
   299          "${aws_iam_group.group3.name}"
   300      ]
   301      policy_arn = "${aws_iam_policy.policy.arn}"
   302  }`, u1, u2, u3)
   303  }
   304  
   305  const testAccAWSPolicyPaginatedAttachConfig = `
   306  resource "aws_iam_user" "user" {
   307      count = 101
   308      name = "${format("paged-test-user-%d", count.index + 1)}"
   309  }
   310  
   311  resource "aws_iam_policy" "policy" {
   312      name = "test-policy"
   313      description = "A test policy"
   314      policy = <<EOF
   315  {
   316    "Version": "2012-10-17",
   317    "Statement": [
   318      {
   319        "Action": [
   320          "iam:ChangePassword"
   321        ],
   322        "Resource": "*",
   323        "Effect": "Allow"
   324      }
   325    ]
   326  }
   327  EOF
   328  }
   329  
   330  resource "aws_iam_policy_attachment" "test-paginated-attach" {
   331      name = "test-attachment"
   332      users = ["${aws_iam_user.user.*.name}"]
   333      policy_arn = "${aws_iam_policy.policy.arn}"
   334  }
   335  `