github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/aws/resource_aws_iam_role_test.go (about)

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"testing"
     7  
     8  	"regexp"
     9  
    10  	"github.com/aws/aws-sdk-go/aws"
    11  	"github.com/aws/aws-sdk-go/aws/awserr"
    12  	"github.com/aws/aws-sdk-go/service/iam"
    13  	"github.com/hashicorp/terraform/helper/resource"
    14  	"github.com/hashicorp/terraform/terraform"
    15  )
    16  
    17  func TestAccAWSRole_basic(t *testing.T) {
    18  	var conf iam.GetRoleOutput
    19  
    20  	resource.Test(t, resource.TestCase{
    21  		PreCheck:     func() { testAccPreCheck(t) },
    22  		Providers:    testAccProviders,
    23  		CheckDestroy: testAccCheckAWSRoleDestroy,
    24  		Steps: []resource.TestStep{
    25  			{
    26  				Config: testAccAWSRoleConfig,
    27  				Check: resource.ComposeTestCheckFunc(
    28  					testAccCheckAWSRoleExists("aws_iam_role.role", &conf),
    29  					testAccCheckAWSRoleAttributes(&conf),
    30  					resource.TestCheckResourceAttrSet(
    31  						"aws_iam_role.role", "create_date",
    32  					),
    33  				),
    34  			},
    35  		},
    36  	})
    37  }
    38  
    39  func TestAccAWSRole_namePrefix(t *testing.T) {
    40  	var conf iam.GetRoleOutput
    41  
    42  	resource.Test(t, resource.TestCase{
    43  		PreCheck:        func() { testAccPreCheck(t) },
    44  		IDRefreshName:   "aws_iam_role.role",
    45  		IDRefreshIgnore: []string{"name_prefix"},
    46  		Providers:       testAccProviders,
    47  		CheckDestroy:    testAccCheckAWSRoleDestroy,
    48  		Steps: []resource.TestStep{
    49  			{
    50  				Config: testAccAWSRolePrefixNameConfig,
    51  				Check: resource.ComposeTestCheckFunc(
    52  					testAccCheckAWSRoleExists("aws_iam_role.role", &conf),
    53  					testAccCheckAWSRoleGeneratedNamePrefix(
    54  						"aws_iam_role.role", "test-role-"),
    55  				),
    56  			},
    57  		},
    58  	})
    59  }
    60  
    61  func TestAccAWSRole_testNameChange(t *testing.T) {
    62  	var conf iam.GetRoleOutput
    63  
    64  	resource.Test(t, resource.TestCase{
    65  		PreCheck:     func() { testAccPreCheck(t) },
    66  		Providers:    testAccProviders,
    67  		CheckDestroy: testAccCheckAWSRoleDestroy,
    68  		Steps: []resource.TestStep{
    69  			{
    70  				Config: testAccAWSRolePre,
    71  				Check: resource.ComposeTestCheckFunc(
    72  					testAccCheckAWSRoleExists("aws_iam_role.role_update_test", &conf),
    73  				),
    74  			},
    75  
    76  			{
    77  				Config: testAccAWSRolePost,
    78  				Check: resource.ComposeTestCheckFunc(
    79  					testAccCheckAWSRoleExists("aws_iam_role.role_update_test", &conf),
    80  				),
    81  			},
    82  		},
    83  	})
    84  }
    85  
    86  func TestAccAWSRole_badJSON(t *testing.T) {
    87  	resource.Test(t, resource.TestCase{
    88  		PreCheck:     func() { testAccPreCheck(t) },
    89  		Providers:    testAccProviders,
    90  		CheckDestroy: testAccCheckAWSRoleDestroy,
    91  		Steps: []resource.TestStep{
    92  			{
    93  				Config:      testAccAWSRoleConfig_badJson,
    94  				ExpectError: regexp.MustCompile(`.*contains an invalid JSON:.*`),
    95  			},
    96  		},
    97  	})
    98  }
    99  
   100  func testAccCheckAWSRoleDestroy(s *terraform.State) error {
   101  	iamconn := testAccProvider.Meta().(*AWSClient).iamconn
   102  
   103  	for _, rs := range s.RootModule().Resources {
   104  		if rs.Type != "aws_iam_role" {
   105  			continue
   106  		}
   107  
   108  		// Try to get role
   109  		_, err := iamconn.GetRole(&iam.GetRoleInput{
   110  			RoleName: aws.String(rs.Primary.ID),
   111  		})
   112  		if err == nil {
   113  			return fmt.Errorf("still exist.")
   114  		}
   115  
   116  		// Verify the error is what we want
   117  		ec2err, ok := err.(awserr.Error)
   118  		if !ok {
   119  			return err
   120  		}
   121  		if ec2err.Code() != "NoSuchEntity" {
   122  			return err
   123  		}
   124  	}
   125  
   126  	return nil
   127  }
   128  
   129  func testAccCheckAWSRoleExists(n string, res *iam.GetRoleOutput) resource.TestCheckFunc {
   130  	return func(s *terraform.State) error {
   131  		rs, ok := s.RootModule().Resources[n]
   132  		if !ok {
   133  			return fmt.Errorf("Not found: %s", n)
   134  		}
   135  
   136  		if rs.Primary.ID == "" {
   137  			return fmt.Errorf("No Role name is set")
   138  		}
   139  
   140  		iamconn := testAccProvider.Meta().(*AWSClient).iamconn
   141  
   142  		resp, err := iamconn.GetRole(&iam.GetRoleInput{
   143  			RoleName: aws.String(rs.Primary.ID),
   144  		})
   145  		if err != nil {
   146  			return err
   147  		}
   148  
   149  		*res = *resp
   150  
   151  		return nil
   152  	}
   153  }
   154  
   155  func testAccCheckAWSRoleGeneratedNamePrefix(resource, prefix string) resource.TestCheckFunc {
   156  	return func(s *terraform.State) error {
   157  		r, ok := s.RootModule().Resources[resource]
   158  		if !ok {
   159  			return fmt.Errorf("Resource not found")
   160  		}
   161  		name, ok := r.Primary.Attributes["name"]
   162  		if !ok {
   163  			return fmt.Errorf("Name attr not found: %#v", r.Primary.Attributes)
   164  		}
   165  		if !strings.HasPrefix(name, prefix) {
   166  			return fmt.Errorf("Name: %q, does not have prefix: %q", name, prefix)
   167  		}
   168  		return nil
   169  	}
   170  }
   171  
   172  func testAccCheckAWSRoleAttributes(role *iam.GetRoleOutput) resource.TestCheckFunc {
   173  	return func(s *terraform.State) error {
   174  		if *role.Role.RoleName != "test-role" {
   175  			return fmt.Errorf("Bad name: %s", *role.Role.RoleName)
   176  		}
   177  
   178  		if *role.Role.Path != "/" {
   179  			return fmt.Errorf("Bad path: %s", *role.Role.Path)
   180  		}
   181  		return nil
   182  	}
   183  }
   184  
   185  const testAccAWSRoleConfig = `
   186  resource "aws_iam_role" "role" {
   187    name   = "test-role"
   188    path = "/"
   189    assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}"
   190  }
   191  `
   192  
   193  const testAccAWSRolePrefixNameConfig = `
   194  resource "aws_iam_role" "role" {
   195    name_prefix = "test-role-"
   196    path = "/"
   197    assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}"
   198  }
   199  `
   200  
   201  const testAccAWSRolePre = `
   202  resource "aws_iam_role" "role_update_test" {
   203    name = "tf_old_name"
   204    path = "/test/"
   205    assume_role_policy = <<EOF
   206  {
   207    "Version": "2012-10-17",
   208    "Statement": [
   209      {
   210        "Action": "sts:AssumeRole",
   211        "Principal": {
   212          "Service": "ec2.amazonaws.com"
   213        },
   214        "Effect": "Allow",
   215        "Sid": ""
   216      }
   217    ]
   218  }
   219  EOF
   220  }
   221  
   222  resource "aws_iam_role_policy" "role_update_test" {
   223    name = "role_update_test"
   224    role = "${aws_iam_role.role_update_test.id}"
   225    policy = <<EOF
   226  {
   227    "Version": "2012-10-17",
   228    "Statement": [
   229      {
   230        "Effect": "Allow",
   231        "Action": [
   232          "s3:GetBucketLocation",
   233          "s3:ListAllMyBuckets"
   234        ],
   235        "Resource": "arn:aws:s3:::*"
   236      }
   237    ]
   238  }
   239  EOF
   240  }
   241  
   242  resource "aws_iam_instance_profile" "role_update_test" {
   243    name = "role_update_test"
   244    path = "/test/"
   245    roles = ["${aws_iam_role.role_update_test.name}"]
   246  }
   247  
   248  `
   249  
   250  const testAccAWSRolePost = `
   251  resource "aws_iam_role" "role_update_test" {
   252    name = "tf_new_name"
   253    path = "/test/"
   254    assume_role_policy = <<EOF
   255  {
   256    "Version": "2012-10-17",
   257    "Statement": [
   258      {
   259        "Action": "sts:AssumeRole",
   260        "Principal": {
   261          "Service": "ec2.amazonaws.com"
   262        },
   263        "Effect": "Allow",
   264        "Sid": ""
   265      }
   266    ]
   267  }
   268  EOF
   269  }
   270  
   271  resource "aws_iam_role_policy" "role_update_test" {
   272    name = "role_update_test"
   273    role = "${aws_iam_role.role_update_test.id}"
   274    policy = <<EOF
   275  {
   276    "Version": "2012-10-17",
   277    "Statement": [
   278      {
   279        "Effect": "Allow",
   280        "Action": [
   281          "s3:GetBucketLocation",
   282          "s3:ListAllMyBuckets"
   283        ],
   284        "Resource": "arn:aws:s3:::*"
   285      }
   286    ]
   287  }
   288  EOF
   289  }
   290  
   291  resource "aws_iam_instance_profile" "role_update_test" {
   292    name = "role_update_test"
   293    path = "/test/"
   294    roles = ["${aws_iam_role.role_update_test.name}"]
   295  }
   296  
   297  `
   298  
   299  const testAccAWSRoleConfig_badJson = `
   300  	resource "aws_iam_role" "my_instance_role" {
   301    name = "test-role"
   302  
   303    assume_role_policy = <<POLICY
   304  {
   305      "Version": "2012-10-17",
   306      "Statement": [
   307          {
   308              "Action": "sts:AssumeRole",
   309              "Principal": {
   310                  "Service": "ec2.amazonaws.com",
   311              },
   312              "Effect": "Allow",
   313              "Sid": ""
   314          }
   315      ]
   316  }
   317  POLICY
   318  }`