テンプレートは下記のようになります。

suz-lab_iam-base.json

{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "SUZ-LAB Formation IAM Base",
"Mappings": {
"AvailabilityZoneMap": {
"ap-northeast-1": {
"AzA": "ap-northeast-1a",
"AzB": "ap-northeast-1b",
"AzC": "ap-northeast-1c"
}
}
},
"Parameters": {
"PowerUserName": {
"Default": "power-user",
"Description": "Power User Name",
"Type": "String"
}
},
"Resources": {
"IAMRolePowerUser": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Statement": [ {
"Effect": "Allow",
"Principal": { "Service": [ "ec2.amazonaws.com" ] },
"Action": [ "sts:AssumeRole" ]
} ]
},
"Path": "/"
}
},
"IAMPolicyPowerUser": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": { "Ref": "PowerUserName" },
"PolicyDocument": {
"Statement": [ {
"Effect": "Allow",
"NotAction": "iam:*",
"Resource": "*"
} ]
},
"Roles": [ { "Ref": "IAMRolePowerUser" } ]
}
},
"IAMInstanceProfilePowerUser": {
"Type": "AWS::IAM::InstanceProfile",
"Properties": {
"Path": "/",
"Roles": [ { "Ref": "IAMRolePowerUser" } ]
}
}
},
"Outputs": {
"GithubMarkdown": {
"Description": "Github Markdown",
"Value": "https://github.com/suz-lab/suz-lab-centos-ami/blob/master/share/cloudfromation/suz-lab_iam-base.md"
},
"GithubJson": {
"Description": "Github JSON",
"Value": "https://github.com/suz-lab/suz-lab-centos-ami/blob/master/share/cloudfromation/suz-lab_iam-base.json"
},
"S3JsonApNortheast1": {
"Description": "S3 JSON ap-northeast-1",
"Value": "http://ap-northeast-1.template.suz-lab.com.s3.amazonaws.com/template/suz-lab_iam-base/0.0.1.json"
},
"CacooImage": {
"Description": "Cacoo Image",
"Value": "https://cacoo.com/diagrams/XXXXXXXXXXXXXXXX-XXXXX.png"
}
}
}

上記のテンプレートで、CloudFormationのスタックを下記のように作成してみます。

IAMの方も、該当Roleが作成されています。

EC2起動時に、そのRoleを指定することも可能です。

こちらの記事はなかの人(suz-lab)監修のもと掲載しています。
元記事は、こちら