An IAM instance profile is the EC2 attachment that connects an IAM role to an instance. The role supplies permissions that applications and AWS agents running on the instance can use. section 5.3.5 section 3.1.1
CloudFormation models the profile separately from the role. Define an AWS::IAM::InstanceProfile resource, place the role reference in Roles, and assign the profile through the EC2 instance's IamInstanceProfile property. section 5.3.5
A typical setup proceeds as follows:
- Create an IAM role trusted by ec2.amazonaws.com, with the required identity policies. section 5.3.5
- Create an instance profile containing that role. section 5.3.5
- Attach the profile when launching the EC2 instance, or select it in the instance's advanced details. section 5.3.5 section 3.1.1
Self-stopping EC2 instance
An instance profile can provide permission for an EC2 instance to call ec2:StopInstances. A CloudFormation example restricts that action with a stack-identifying resource tag; startup commands then schedule the instance to stop after a configured lifetime. section 5.3.5
InstanceProfile:
Type: 'AWS::IAM::InstanceProfile'
Properties:
Roles:
- !Ref Role
Shows the minimal CloudFormation resource that places a role inside an instance profile. section 5.3.5
Instance: Type: 'AWS::EC2::Instance' Properties: # [...] IamInstanceProfile: !Ref InstanceProfile UserData: 'Fn::Base64': !Sub | #!/bin/bash -ex TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" \ -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` INSTANCEID=`curl -H "X-aws-ec2-metadata-token: $TOKEN" \ -s "http://169.254.169.254/latest/meta-data/instance-id"` echo "aws ec2 stop-instances --region ${AWS::Region} \ --instance-ids $INSTANCEID" | at now + ${Lifetime} minutes
Shows the EC2 resource consuming the profile through IamInstanceProfile. section 5.3.5

