WaitCondition Controls the Pace of AWS CloudFormation Templates


AWS’s WaitCondition can be used with CloudFormation templates to ensure required resources are running.

WaitCondition for CloudFormationAs you may already be aware, AWS CloudFormation is used for infrastructure automation by allowing you to write JSON templates to automatically install, configure, and bootstrap your applications on Amazon EC2 instances. This allows you to replicate your environment, or update an existing installation, without making a manual change to the environment, saving you a lot of time and effort.

This post focuses on the CloudFormation WaitCondition resource, which can help you to initialize and configure your environment as per your requirement.

What is WaitCondition and who needs it?

WaitCondition can be considered as a timed semaphore that pauses the execution of your CloudFormation template and waits for a number of success signals before it continues a stack creation operation. There are scenarios where you need to pause the execution of your CloudFormation stack, such as resource dependencies or user experience. Some scenarios also include:

  • As a part of user experience, you want to pause completion of the CloudFormation template and display of the output section until all resources are properly provisioned and in a working state.
  • There are resource dependencies where some additional scripts and packages on your instance must be properly configured before other AWS resources can contact them. For example, for successful backend configuration, a front end application should be in a running state.
  • An environment in which Active Directory should be in a running state before other instances perform authentication.
  • A NAT instance should be in working state before private subnet instances try to fetch packages from the outside world.

When the WaitCondition resource is created, a timer is started. The WaitCondition becomes CREATE_COMPLETE after it receives a success signal. If no signal is received before the timeout, the WaitCondition enters the CREATE_FAILED state and the stack creation is rolled back.

CloudFormation Helper Configurations

To use WaitCondition with your CloudFormation template, you must have CloudFormation helper scripts configured on your instances. These helper scripts (cfn helper) are Python scripts that help you to install, configure and start services on your Amazon EC2 instances and are part of your stack creation process. If these scripts are not already configured on your Amazon EC2 instance, they can be configured as a part of your userdata.

Syntax:

{
   "Type" : "AWS::CloudFormation::WaitCondition",
   "Properties" : {
     "Count" : String,
     "Handle" : String,
     "Timeout" : String
   }
}

“Count” sets the number of success signals AWS CloudFormation must receive before it continues the stack creation process. If the wait condition does not receive the specified number of success signals before the Timeout period expires, CloudFormation assumes that the wait condition has failed and rolls the stack back.

“Handle” is a reference to the wait condition handle used to signal this wait condition. To use a wait condition in a stack, you have to declare an AWS::CloudFormation::WaitConditionHandle resource in the stack’s template. A wait condition handle has no properties; however, a reference to a WaitConditionHandle resource resolves to a presigned URL that you can use to signal success or failure to the WaitCondition.

Syntax:

{
"Type" : "AWS::CloudFormation::WaitConditionHandle",
"Properties" : {}
}

Anytime you add a WaitCondition resource during a stack update, you must associate the wait condition with a new WaitConditionHandle resource.

“Timeout” is the time (in seconds) to wait for the number of signals that the Count property specifies. The maximum time that can be specified for this property is 12 hours (43200 seconds). If you receive a positive signal before the timeout value, it will automatically stop the timer and execution of the template will start.

CloudFormation Helper Functions

For dynamically installing and configuring your application on Amazon EC2 instances, CloudFormation provides a set of helper scripts (written in Python) that, in conjunction with the resource metadata you defined in the template, can be used to install software and start services. These helper scripts are run on the Amazon EC2 instance.

This is how AWS’s CloudFormation documentation describes these helper scripts:

  • cfn-init: Retrieves and interprets the resource metadata to install packages, create files, and start services.
  • cfn-signal: A simple wrapper to signal an AWS CloudFormation WaitCondition for synchronizing other resources in the stack when the application is ready.
  • cfn-get-metadata: A wrapper script that retrieves either all metadata that is defined for a resource or path to a specific key or a subtree of the resource metadata.
  • cfn-hup: A daemon that checks for updates to metadata and executes custom hooks when changes are detected.

CloudFormation helper scripts are already available on Amazon Linux AMIs and Amazon Windows AMIs however, if you want to use them for other linux distributions, RPM and source code is available on AWS website. These scripts can be installed as a part of userdata.

If you create your own Windows image for use with CloudFormation you must set up a Windows instance with EC2ConfigService to work with the AWS CloudFormation bootstrapping tools.

Using WaitCondition on an Amazon Linux AMI Instance

It is recommend to use the latest version of the AWS CloudFormation bootstrap scripts when you launch an Amazon Linux AMI. To ensure that happens, add a yum update –y aws-cfn-bootstrap command to the user data script, as shown in the following example (a sample template using the ‘WaitConditions’ and ‘WaitCondition Handle’ Resources):

{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
   "MyInstance": {
     "Type": "AWS::EC2::Instance",
     "Properties": {
       "DisableApiTermination": "FALSE",
       "ImageId": "AmazonLinuxAMIId",
       "InstanceType": "t2.micro",
       "KeyName": "MyKeypair",
       "Monitoring": "false",
       "UserData": { "Fn::Base64" : { "Fn::Join" : ["", [
         "#!/bin/bash -xe\n",
         "yum update -y aws-cfn-bootstrap\n",
         "# Signal the status from cfn-init\n",
         "/opt/aws/bin/cfn-signal -e 0 -r \"Instance Creation Complete\" ", { "Ref" : "WaitHandle" },
         "'\n"
       ]]}},
       "Tags": [
         {
           "Key": "Name",
           "Value": "My_Instance"
         }
       ],
       "NetworkInterfaces": [
         {
           "DeleteOnTermination": "true",
           "Description": "Primary network interface",
           "DeviceIndex": 0,
           "AssociatePublicIpAddress": "true"
         }
       ]
     }
   },
   "WaitHandle" : {
     "Type" : "AWS::CloudFormation::WaitConditionHandle"
   },
   "WaitCondition" : {
     "Type" : "AWS::CloudFormation::WaitCondition",
     "DependsOn" : "MyInstance",
     "Properties" : {
         "Handle" : { "Ref" : "WaitHandle" },
         "Timeout" : "300"
       }
     }
}
}

Using WaitCondition on an Amazon Windows AMI instance

User data execution enables you to inject scripts into the instance metadata during the first launch. By default, all Amazon Windows AMIs have user data execution enabled for the initial boot. However, if you want to use any custom Windows AMI and want to enable userdata execution then you need to follow these instructions:

  1. Launch and connect to your Windows instance.
  2. From the Start menu, click All Programs, and then click EC2ConfigService Settings.
  3. On EC2 Service Properties under the Image tab, click on Shutdown with Sysprep regardless of the setting of the User Data check box under General
  4. After running Sysprep and shutting down the instance, you can create an AMI from the image.
  5. This new image is enabled with your custom userdata executed on every boot.

The following is a sample template for a Windows Base AMI using the ‘WaitConditions’ and ‘WaitCondition Handle’ resources.

{
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
   "MyInstance": {
     "Type": "AWS::EC2::Instance",
     "Metadata" : {
       "AWS::CloudFormation::Init" : {
         "config" : {
           "files" : {
             "c:\\cfn\\cfn-hup.conf" : {
               "content" : { "Fn::Join" : ["", [
                 "[main]\n",
                 "stack=", { "Ref" : "AWS::StackId" }, "\n",
                 "region=", { "Ref" : "AWS::Region" }, "\n"
                 ]]}
             },
             "c:\\cfn\\hooks.d\\cfn-auto-reloader.conf" : {
               "content": { "Fn::Join" : ["", [
                 "[cfn-auto-reloader-hook]\n",
                 "triggers=post.update\n",
           "path=Resources.MyInstance.Metadata.AWS::CloudFormation::Init\n",
                "action=cfn-init.exe -v -s ", { "Ref" : "AWS::StackId" },
                                                 " -r MyInstance",
                                                 " --region ", { "Ref" : "AWS::Region" }, "\n"
               ]]}
            },
            "c:\\scripts\\test.ps1" : {
               "content": { "Fn::Join" : ["", [
                 "Write-Host Hello World!\n"
               ]]}
             }
           },
           "commands" : {
             "1-run-script" : {
               "command" : { "Fn::Join" : [ "", [
                "Powershell.exe Set-ExecutionPolicy Unrestricted -force \n",
                "Powershell.exe C:\\scripts\\test.ps1"
                  ]]}}
                },
                "services": {
                   "windows": {
                      "cfn-hup": {
                                "enabled": "true",
                                "ensureRunning": "true",
                                "files": ["c:\\cfn\\cfn-hup.conf", "c:\\cfn\\hooks.d\\cfn-auto-reloader.conf"]
                                                                }
                                     }
                                                }
         }
                                }
                },
     "Properties": {
       "DisableApiTermination": "FALSE",
       "ImageId": "WindowsBaseAMIId",
       "InstanceType": "t2.micro",
       "KeyName": "MyKeypair",
       "Monitoring": "false",
       "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
         "<script>\n",
         "cfn-init.exe -v -s ", { "Ref" : "AWS::StackName" },
         " -r MyInstance",
         " --region ", { "Ref" : "AWS::Region" }, "\n",
         "cfn-signal.exe -e 0 ", { "Fn::Base64" : { "Ref" : "WindowsServerWaitHandle" }}, "\n",
         "</script>\n"
         ]]}},
       "Tags": [
         {
           "Key": "Name",
           "Value": "CloudAcademy_Instance"
         }
       ],
       "NetworkInterfaces": [
         {
           "DeleteOnTermination": "true",
           "Description": "Primary network interface",
           "DeviceIndex": 0,
           "AssociatePublicIpAddress": "true"
         }
       ]
     }
   },
   "WindowsServerWaitHandle": {
     "Type": "AWS::CloudFormation::WaitConditionHandle"
     },
   "WindowsServerWaitCondition": {
     "Type": "AWS::CloudFormation::WaitCondition",
     "DependsOn": "MyInstance",
     "Properties": {
         "Handle": { "Ref": "WindowsServerWaitHandle" },
         "Timeout": "1800"
       }
     }
}

 WaitCondition and DependsOn

The WaitCondition CloudFormation resource might look similar to the DependsOn attribute, but they’re actually different. DependsOn controls the order in which your CloudFormation resources are created, i.e., creation of a specific resource follows another. DependsOn doesn’t wait for success or failure signals from AWS resources before moving forward. While, on the other hand, WaitCondition waits for success signals from your AWS resources and resumes the execution of the CloudFormation template. However, WaitCondition and DependsOn can work together when there is a resource creation dependency requirement.

WaitCondition is a very useful AWS feature that’s widely used for building a complete automated deployment system. For more information on CloudFormation WaitCondition resource, refer to these links :

  1. AWS::CloudFormation::WaitCondition Resource
  2. Creating WaitConditions in a template

 

Avatar

Written by

Sanket Dangi

Head of Managed Services at REAN Cloud. Before joining REAN Cloud, I was CEO and Founder of StraightArc Solutions which was later acquired by REAN Cloud. I started my career working on cloud computing. Loves to talk about DevOps, System Administration, Scalability, High Availability, Disaster Recovery and Cloud Security. Apart from work, I love to meet people, travel and watch sports.

Related Posts

Avatar
Jeremy Cook
— September 17, 2019

Cloud Migration Risks & Benefits

If you’re like most businesses, you already have at least one workload running in the cloud. However, that doesn’t mean that cloud migration is right for everyone. While cloud environments are generally scalable, reliable, and highly available, those won’t be the only considerations dri...

Read more
  • AWS
  • Azure
  • Cloud Migration
Joe Nemer
Joe Nemer
— September 12, 2019

Real-Time Application Monitoring with Amazon Kinesis

Amazon Kinesis is a real-time data streaming service that makes it easy to collect, process, and analyze data so you can get quick insights and react as fast as possible to new information.  With Amazon Kinesis you can ingest real-time data such as application logs, website clickstre...

Read more
  • amazon kinesis
  • AWS
  • Stream Analytics
  • Streaming data
Joe Nemer
Joe Nemer
— September 6, 2019

Google Cloud Functions vs. AWS Lambda: The Fight for Serverless Cloud Domination

Serverless computing: What is it and why is it important? A quick background The general concept of serverless computing was introduced to the market by Amazon Web Services (AWS) around 2014 with the release of AWS Lambda. As we know, cloud computing has made it possible for users to ...

Read more
  • AWS
  • Azure
  • Google Cloud Platform
Joe Nemer
Joe Nemer
— September 3, 2019

Google Vision vs. Amazon Rekognition: A Vendor-Neutral Comparison

Google Cloud Vision and Amazon Rekognition offer a broad spectrum of solutions, some of which are comparable in terms of functional details, quality, performance, and costs. This post is a fact-based comparative analysis on Google Vision vs. Amazon Rekognition and will focus on the tech...

Read more
  • Amazon Rekognition
  • AWS
  • Google Cloud Platform
  • Google Vision
Alisha Reyes
Alisha Reyes
— August 30, 2019

New on Cloud Academy: CISSP, AWS, Azure, & DevOps Labs, Python for Beginners, and more…

As Hurricane Dorian intensifies, it looks like Floridians across the entire state might have to hunker down for another big one. If you've gone through a hurricane, you know that preparing for one is no joke. You'll need a survival kit with plenty of water, flashlights, batteries, and n...

Read more
  • AWS
  • Azure
  • Google Cloud Platform
  • New content
  • Product Feature
  • Python programming
Joe Nemer
Joe Nemer
— August 27, 2019

Amazon Route 53: Why You Should Consider DNS Migration

What Amazon Route 53 brings to the DNS table Amazon Route 53 is a highly available and scalable Domain Name System (DNS) service offered by AWS. It is named by the TCP or UDP port 53, which is where DNS server requests are addressed. Like any DNS service, Route 53 handles domain regist...

Read more
  • Amazon
  • AWS
  • Cloud Migration
  • DNS
  • Route 53
Alisha Reyes
Alisha Reyes
— August 22, 2019

How to Unlock Complimentary Access to Cloud Academy

Are you looking to get trained or certified on AWS, Azure, Google Cloud Platform, DevOps, Cloud Security, Python, Java, or another technical skill? Then you'll want to mark your calendars for August 23, 2019. Starting Friday at 12:00 a.m. PDT (3:00 a.m. EDT), Cloud Academy is offering c...

Read more
  • AWS
  • Azure
  • cloud academy content
  • complimentary access
  • GCP
  • on the house
Avatar
Michael Sheehy
— August 19, 2019

What Exactly Is a Cloud Architect and How Do You Become One?

One of the buzzwords surrounding the cloud that I'm sure you've heard is "Cloud Architect." In this article, I will outline my understanding of what a cloud architect does and I'll analyze the skills and certifications necessary to become one. I will also list some of the types of jobs ...

Read more
  • AWS
  • Cloud Computing
Avatar
Nitheesh Poojary
— August 19, 2019

Boto: Using Python to Automate AWS Services

Boto allows you to write scripts to automate things like starting AWS EC2 instances Boto is a Python package that provides programmatic connectivity to Amazon Web Services (AWS). AWS offers a range of services for dynamically scaling servers including the core compute service, Elastic...

Read more
  • Automated AWS Services
  • AWS
  • Boto
  • Python
Avatar
Andrew Larkin
— August 13, 2019

Content Roadmap: AZ-500, ITIL 4, MS-100, Google Cloud Associate Engineer, and More

Last month, Cloud Academy joined forces with QA, the UK’s largest B2B skills provider, and it put us in an excellent position to solve a massive skills gap problem. As a result of this collaboration, you will see our training library grow with additions from QA’s massive catalog of 500+...

Read more
  • AWS
  • Azure
  • content roadmap
  • Google Cloud Platform
Avatar
Adam Hawkins
— August 9, 2019

DevSecOps: How to Secure DevOps Environments

Security has been a friction point when discussing DevOps. This stems from the assumption that DevOps teams move too fast to handle security concerns. This makes sense if Information Security (InfoSec) is separate from the DevOps value stream, or if development velocity exceeds the band...

Read more
  • AWS
  • cloud security
  • DevOps
  • DevSecOps
  • Security
Avatar
Stefano Giacone
— August 8, 2019

Test Your Cloud Knowledge on AWS, Azure, or Google Cloud Platform

Cloud skills are in demand | In today's digital era, employers are constantly seeking skilled professionals with working knowledge of AWS, Azure, and Google Cloud Platform. According to the 2019 Trends in Cloud Transformation report by 451 Research: Business and IT transformations re...

Read more
  • AWS
  • Cloud skills
  • Google Cloud
  • Microsoft Azure