AWS CloudFormation cfn-init and cfn-signal Overview
- cfn-init: Used to retrieve and interpret resource metadata, install packages, create files, and start services.
- cfn-signal: A script that is used to signal CloudFormation whether the EC2 instance has been configured successfully.
Using cfn-signal with WaitCondition
- WaitCondition: A CloudFormation resource that pauses the stack creation until it receives a signal indicating success or failure.
- Creation Policy: Attached to resources like EC2 instances or Auto Scaling groups to specify a timeout and count for the expected signals.
Workflow
- CloudFormation launches an EC2 instance.
- The instance runs
cfn-init to configure itself.
- After running
cfn-init, the instance sends a signal using cfn-signal.
- The signal is sent to a
WaitCondition resource in the CloudFormation template.
- The
WaitCondition waits for a success or failure signal within a specified timeout.
CloudFormation Template Snippet
AWSTemplateFormatVersion: '2010-09-09'
Description: EC2 instance with cfn-init and cfn-signal
Parameters:
KeyName:
Description: Name of an existing EC2 KeyPair to enable SSH access
Type: 'AWS::EC2::KeyPair::KeyName'
Resources:
MyEC2Instance:
Type: 'AWS::EC2::Instance'
Metadata:
'AWS::CloudFormation::Init':
config:
files:
"/home/ec2-user/hello.txt":
content: "Hello, World!"
Properties:
InstanceType: t2.micro
ImageId: ami-0abcdef1234567890 # Update this with a valid AMI ID
KeyName: !Ref KeyName
UserData:
Fn::Base64: !Sub |
#!/bin/bash -xe
yum update -y aws-cfn-bootstrap
/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource MyEC2Instance --region ${AWS::Region}
/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource MyEC2Instance --region ${AWS::Region}
WaitHandle:
Type: 'AWS::CloudFormation::WaitConditionHandle'
WaitCondition:
Type: 'AWS::CloudFormation::WaitCondition'
DependsOn: MyEC2Instance
Properties:
Handle: !Ref WaitHandle
Timeout: '300'
Execution Steps
- Create a stack with the CloudFormation template.
- Monitor the creation of resources like the security group and EC2 instance.
- Observe the
WaitCondition resource's status.
- Once the EC2 instance finishes its bootstrap and signals back, the
WaitCondition status will change to complete.
Outcome