Skip to content

Instantly share code, notes, and snippets.

@mvanholsteijn
Last active August 31, 2025 17:52
Show Gist options
  • Select an option

  • Save mvanholsteijn/a85dc4355985477a0aec2aeb3c27eab1 to your computer and use it in GitHub Desktop.

Select an option

Save mvanholsteijn/a85dc4355985477a0aec2aeb3c27eab1 to your computer and use it in GitHub Desktop.
A sample CloudFormation template integrating cloud-init and cfn-signal
---
AWSTemplateFormatVersion: '2010-09-09'
Description: cloud-init and cfn-signal
Parameters:
SubnetId:
Type: AWS::EC2::Subnet::Id
Description: The subnet to deploy the instance in
Default: "subnet-026f62073564ba8fe"
AL2023:
Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64
Description: Latest Amazon Linux 2023 AMI from SSM
ExitCode:
Type: Number
MinValue: 0
MaxValue: 255
Default: 0
Resources:
AutoScalingGroup:
Type: AWS::AutoScaling::AutoScalingGroup
Properties:
AutoScalingGroupName: Demo
LaunchTemplate:
LaunchTemplateId: !Ref 'LaunchTemplate'
Version: !GetAtt 'LaunchTemplate.LatestVersionNumber'
MinSize: '1'
MaxSize: '2'
DesiredCapacity: '1'
VPCZoneIdentifier:
- !Ref SubnetId
UpdatePolicy:
AutoScalingRollingUpdate:
MinInstancesInService: 1
MaxBatchSize: 10
WaitOnResourceSignals: true
CreationPolicy:
ResourceSignal:
Count: 1
Timeout: PT5M
LaunchTemplate:
Type: AWS::EC2::LaunchTemplate
Properties:
LaunchTemplateName: SampleTemplate
LaunchTemplateData:
ImageId: !Ref AL2023
InstanceType: t3.micro
IamInstanceProfile:
Arn: !GetAtt InstanceProfile.Arn
UserData: !Base64
Fn::Sub: |
#cloud-config
write_files:
- path: /etc/systemd/system/cfn-signal.service
permissions: '0644'
content: |
#
# When cloud-init completed successfully, report this to CFN
# using cfn-signal
#
[Unit]
Description=Signal completion of cloud-init to CFN
Wants=cloud-init.target
After=cloud-init.target
[Service]
Type=oneshot
ExecStart=/bin/bash -c '\
cloud-init status --wait | grep -q "^status: done$"; \
/opt/aws/bin/cfn-signal \
--stack "$STACK_NAME" \
--resource "$LOGICAL_RESOURCE_ID" \
--region "$AWS_REGION" \
--exit-code $? \
'
[Install]
WantedBy=default.target
- path: /etc/systemd/system/cfn-signal.service.d/override.conf
permissions: '0644'
content: |
[Service]
Environment="AWS_REGION=${AWS::Region}"
Environment="STACK_NAME=${AWS::StackName}"
Environment="LOGICAL_RESOURCE_ID=AutoScalingGroup"
runcmd:
- sudo systemctl daemon-reload
- sudo systemctl enable --now --no-block cfn-signal
- exit ${ExitCode}
SSMRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles:
- !Ref SSMRole
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment