Ends in
00
days
00
hrs
00
mins
00
secs
ENROLL NOW

Get any AWS Specialty Mock Test for FREE when you Buy 2 AWS Pro-Level Practice Tests – as LOW as $10.49 USD each ONLY!

How to Implement CloudFormation Creation Policy on Ubuntu

Home » Others » How to Implement CloudFormation Creation Policy on Ubuntu

How to Implement CloudFormation Creation Policy on Ubuntu

Welcome to our guide on implementing AWS CloudFormation Creation Policy on Ubuntu! If you’re diving into cloud infrastructure management with AWS CloudFormation, understanding Creation Policies is crucial for ensuring smooth stack creation and resource management.

In this article, we’ll delve into CloudFormation Creation Policy, a vital attribute for orchestrating resource creation in AWS CloudFormation. While focusing on Ubuntu, we’ll also cover the essential installation of CloudFormation helper scripts, which facilitate the signaling process between EC2 instances and CloudFormation.

What is CloudFormation Creation Policy?

The CloudFormation creation policy is an attribute that allows you to prevent a resource from reaching the “create complete” state until CloudFormation receives a specified number of success signals or the timeout period is exceeded. This is useful when you want to wait for resource configuration actions to complete before the stack creation proceeds.

Currently, the following CloudFormation resources support creation policies: AWS::AppStream::Fleet, AWS::AutoScaling::AutoScalingGroup, AWS::EC2::Instance, and AWS::CloudFormation::WaitCondition.

In real-world AWS CloudFormation deployments, Creation Policies ensure resource provisioning reliability and consistency. Let’s explore two practical scenarios where Creation Policies prove invaluable:

  1. Custom Software Configuration: In scenarios where you’re deploying custom software or applications on EC2 instances, specific configurations or installations may be required during instance initialization. Utilizing a Creation Policy ensures CloudFormation waits until these configurations are successfully completed before considering the instance creation process complete.
  2. Multi-tier Application Stacks: Deploying multi-tier application stacks, such as web servers, application servers, and databases, necessitates orchestrating resource creation in a specific order to maintain application integrity. Creation Policies orchestrate the sequential creation of resources, ensuring dependencies are met before proceeding to the next tier.

Why Install CloudFormation Helper Script on Ubuntu?

The CloudFormation helper scripts are a set of scripts that provide helper functions to interact with CloudFormation. These scripts need to be manually installed on Ubuntu instances because they are not included by default, unlike AWS’s own Linux distribution, which is preconfigured. The main reason to install these scripts is to enable the cfn-signal command, which is used to send success or failure signals during resource creation. This command is often utilized to send these signals to CloudFormation for resources created using the creation policy.

Steps to Install CloudFormation Helper Script on Ubuntu

  1. Update Package Repository: Ensure that the package repository is up to date by running:
    sudo apt-get update -y
  2. Install Python3 and pip: CloudFormation helper scripts require Python3 and pip. Install them using the following command:
    sudo apt-get -y install python3-pip
  3. Create Directory for CloudFormation Helper Scripts: Create a directory to store the CloudFormation helper scripts.
    sudo mkdir -p /opt/aws/

    The command sudo mkdir -p /opt/aws/ creates a directory named “aws” within the “/opt” directory, creating the “/opt” directory if it doesn’t already exist, and it’s executed with administrative privileges.

  4. Install CloudFormation Helper Scripts: Use pip to install the CloudFormation helper scripts.
    sudo pip3 install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz
  5. Create Symbolic Link: Create a symbolic link for the CloudFormation helper scripts to ensure they are accessible.
    sudo ln -s /usr/local/init/ubuntu/cfn-hup /etc/init.d/cfn-hup

Supported Ubuntu Versions

The CloudFormation helper script installation process outlined above is compatible with the following Ubuntu LTS releases:

Tutorials dojo strip
  • Ubuntu 16.04 LTS
  • Ubuntu 18.04 LTS 
  • Ubuntu 20.04 LTS
  • Ubuntu 22.04 LTS 

Example Usage of CreationPolicy

Let’s integrate an example of using CreationPolicy in a CloudFormation template. Below is an example  CloudFormation template where a CreationPolicy is applied to an EC2 instance resource, and we added the above commands in the UserData for installing the CloudFormation Helper Script:

AWSTemplateFormatVersion: '2010-09-09'
Description: A template to deploy an EC2 instance with a security group and an S3 bucket.

Parameters:
  LatestAmiId:
    Description: "AMI for EC2"
    Type: String 
    Default: "YOUR_AMI_ID_HERE" # ensure that the AMI is in the list of Supported Ubuntu versions

Resources:
  InstanceSecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      GroupDescription: Enable SSH and HTTP access via port 22 and port 80
      SecurityGroupIngress:
        - Description: 'Allow SSH IPv4 IN'
          IpProtocol: tcp
          FromPort: 22 
          ToPort: 22
          CidrIp: '0.0.0.0/0'
        - Description: 'Allow HTTP IPv4 IN'
          IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: '0.0.0.0/0'

  Instance:
    Type: 'AWS::EC2::Instance'
    CreationPolicy:
      ResourceSignal:
        Timeout: PT15M
    Properties:
      InstanceType: "t2.micro"
      ImageId: !Ref LatestAmiId
      SecurityGroupIds: 
        - !GetAtt InstanceSecurityGroup.GroupId
      KeyName: mykeypair # Add keypair here
      Tags:
        - Key: Name
          Value: ubuntu-test
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash -xe
          sudo apt-get update -y
          sudo apt-get -y install python3-pip
          sudo mkdir -p /opt/aws/
          sudo pip3 install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz
          sudo ln -s /usr/local/init/ubuntu/cfn-hup /etc/init.d/cfn-hup
          
          # Install Apache
          sudo apt-get -y install apache2

          # Enable and start Apache service
          sudo systemctl enable apache2
          sudo systemctl start apache2

          # Create the test page
          sudo bash -c 'cat <<EOF > /var/www/html/index.html
              <html>
                <head>
                  <title>Amazing test page</title>
                </head>
                <body>
                  <h1><center>Perlas ng Silangan</center></h1>
                </body>
              </html>
              EOF'
          sudo /usr/local/bin/cfn-signal -e $? --stack ${AWS::StackId} --resource Instance --region ${AWS::Region}

In this example:

  •  We use a CreationPolicy section to specify a timeout of 15 minutes, ensuring that CloudFormation waits for signals from the resource before considering the creation process as complete.
  • We installed the CloudFormation Helper Script by adding the commands in the UserData Script to facilitate the process.
  • The last command of the UserData script sends a signal to CloudFormation, indicating the completion status of the resource creation process.

To send signals to CloudFormation:

  • /usr/local/bin/cfn-signal: This is the path to the CloudFormation signal command (cfn-signal). This command is provided by the CloudFormation Helper Scripts and is used to send signals to CloudFormation.

  • -e $?: The -e flag specifies the exit status code. $? is a special shell variable that holds the exit status of the previous command. In this context, it captures the exit status of the UserData execution. If the UserData scripts are executed successfully (i.e., exit status code 0), CloudFormation receives a success signal. If there is an error during UserData execution, CloudFormation receives a failure signal.

  • --stack ${AWS::StackId}: This flag specifies the name or unique ID of the CloudFormation stack. ${AWS::StackId} is a pseudo parameter that resolves to the ID of the stack in which the resource is being created.

  • --resource Instance: This flag specifies the logical name of the resource within the CloudFormation stack. In this case, it is named Instance.

  • --region ${AWS::Region}: This flag specifies the AWS region in which the CloudFormation stack is being created. ${AWS::Region} is another pseudo parameter that resolves to the region in which the stack is being created.

Result

By using the above example CloudFormation Template, we successfully installed CloudFormation Helper Script using the UserData Script in the CloudFormation. Notice the “Received SUCCESS signal.” This means the last command in the UserData script was successfully executed, and that also means that the CloudFormation Helper Script was installed.

How to Implement CloudFormation Creation Policy on Ubuntu

To cross-check that all the UserData scripts are executed properly, you can check it by connecting to the instance via SSH and opening the cloud-init-output.log. Here is a sample snippet of the log file:

How to Implement CloudFormation Creation Policy on Ubuntu

Conclusion

We have discussed in this article the importance of CloudFormation Creation Policy and the necessity of installing CloudFormation helper scripts on Ubuntu. Following these steps lets you ensure that your Ubuntu-based EC2 instances seamlessly integrate with CloudFormation, allowing for reliable and efficient infrastructure provisioning.

References:

https://repost.aws/knowledge-center/install-cloudformation-scripts

https://github.com/aws-cloudformation/aws-cloudformation-templates/blob/main/aws/solutions/OperatingSystems/ubuntu18.04_cfn-hup.yaml

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-helper-scripts-reference.html

Get any AWS Specialty Mock Test for FREE when you Buy 2 AWS Pro-Level Practice Tests – as LOW as $10.49 USD each ONLY!

Tutorials Dojo portal

Learn AWS with our PlayCloud Hands-On Labs

Tutorials Dojo Exam Study Guide eBooks

tutorials dojo study guide eBook

FREE AWS Exam Readiness Digital Courses

Subscribe to our YouTube Channel

Tutorials Dojo YouTube Channel

FREE AWS, Azure, GCP Practice Test Samplers

Follow Us On Linkedin

Recent Posts

Written by: Neil Rico

Neil, fueled by a passion for technology, now dedicates himself to architecting and optimizing cloud solutions, particularly within the dynamic realm of Amazon Web Services (AWS). He's always learning because life is a journey of discovering and growing.

AWS, Azure, and GCP Certifications are consistently among the top-paying IT certifications in the world, considering that most companies have now shifted to the cloud. Earn over $150,000 per year with an AWS, Azure, or GCP certification!

Follow us on LinkedIn, YouTube, Facebook, or join our Slack study group. More importantly, answer as many practice exams as you can to help increase your chances of passing your certification exams on your first try!

View Our AWS, Azure, and GCP Exam Reviewers Check out our FREE courses

Our Community

~98%
passing rate
Around 95-98% of our students pass the AWS Certification exams after training with our courses.
200k+
students
Over 200k enrollees choose Tutorials Dojo in preparing for their AWS Certification exams.
~4.8
ratings
Our courses are highly rated by our enrollees from all over the world.

What our students say about us?