Follow these steps in order to use CloudFormation to create an instance role:
- Create a new CloudFormation template file, and add the first Resource parameter. This is going to be our role that contains references to the Managed Policies, and also to our Inline Policy:
AWSTemplateFormatVersion: '2010-09-09'
Resources:
ExampleRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- sts:AssumeRole
- Complete the definition of the role by adding policies:
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
- arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess
Path: /
Policies:
-
PolicyName: WriteToCloudWatchLogs
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
- logs:DescribeLogStreams
Resource: "*"
- We now need to create an InstanceProfile resource. A profile encapsulates a single IAM role and, roughly speaking, that's all it's used for. A profile can contain only a single IAM role, so it's not clear why AWS has built this extra layer of abstraction; presumably, they have plans to give profiles of other properties aside from roles:
ExampleInstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles:
- !Ref ExampleRole
Path: /
- For convenience, we'll add some Outputs parameters, which will provide the profile name and ARN to us, after the stack has been created:
Outputs:
ExampleInstanceProfile:
Value: !Ref ExampleInstanceProfile
ExampleInstanceProfileArn:
Value: !GetAtt ExampleInstanceProfile.Arn
- You can now create your instance role using CloudFormation via the web console:
aws cloudformation create-stack
--stack-name example-instance-profile
--template-body file://08-creating-instance-roles.yaml
--capabilities CAPABILITY_IAM
This role can now be assigned to your EC2 instances.