Search⌘ K
AI Features

EC2 User Data In CloudFormation (cfn init, wait, and signal)

Understand how to use EC2 UserData for initial instance setup and how cfn-init simplifies configuring EC2 instances within CloudFormation. Explore implementing wait conditions and cfn-signal to ensure successful configuration, and learn troubleshooting methods for common failures and timeouts to manage AWS infrastructure effectively.

Introduction

The EC2 resource in CloudFormation has a UserData property that allows users to pass EC2 user data to the instances created by a template. The UserData property isn’t required for EC2 resources, and we can create an EC2 instance without specifying any value for this property, as we did in the previous lesson.

Note: User data is used to specify commands that have to run when the EC2 instance is launched. Generally, it contains commands to update the EC2 software and download any dependencies required for EC2 to perform its actions.

The outputs of a user data script are stored in the /var/log/cloud-init-output.log file.

The following code sample uses the CloudFormation intrinsic function Base64 to encode the user data script as a Base64 string. Creating an EC2 instance with this user data will automatically start an httpd web server on the instance.

YAML
Resources:
EducativeEC2Instance:
Type: AWS::EC2::Instance
Properties:
UserData:
# All text below the pipe symbol (|) is included in the Base64 function.
Fn::Base64: |
#!/bin/bash
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Educattive EC2 instance.</h1>" > /var/www/html/index.html
OtherProperty:

The Sub function in UserData

By using the UserData property with Base64 and Sub functions, it’s also possible to pass CloudFormation ...