AWS CloudFormation cfn-init and cfn-signal Overview

Using cfn-signal with WaitCondition

Workflow

  1. CloudFormation launches an EC2 instance.
  2. The instance runs cfn-init to configure itself.
  3. After running cfn-init, the instance sends a signal using cfn-signal.
  4. The signal is sent to a WaitCondition resource in the CloudFormation template.
  5. 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

  1. Create a stack with the CloudFormation template.
  2. Monitor the creation of resources like the security group and EC2 instance.
  3. Observe the WaitCondition resource's status.
  4. Once the EC2 instance finishes its bootstrap and signals back, the WaitCondition status will change to complete.

Outcome