---
title: "How To Manage IaC with Ansible CloudFormation in AWS"
description: "Learn how to manage infrastructure as code (IaC) with Ansible CloudFormation with different examples in this tutorial!"
canonical: "https://adamtheautomator.com/ansible-cloudformation/"
---

# How To Manage IaC with Ansible CloudFormation in AWS

> Learn how to manage infrastructure as code (IaC) with Ansible CloudFormation with different examples in this tutorial!

Source: https://adamtheautomator.com/ansible-cloudformation/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![How To Manage IaC with Ansible CloudFormation in AWS](https://adamtheautomator.com/wp-content/uploads/2022/03/How-To-Manage-IaC-with-Ansible-CloudFormation-in-AWS.jpg)

# How To Manage IaC with Ansible CloudFormation in AWS

[![](https://secure.gravatar.com/avatar/2beb65fca997135120ed98dc6a2e57dcdf1a7d7d2f5ff687b5d91dc7ccd7a6b5?s=192&d=mm&r=g)Sagar](https://adamtheautomator.com/author/shanky-mendiratta/)9 March 20226 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Ansible](/tag/ansible/)[AWS CloudFormation](/tag/aws-cloudformation/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Creating JSON to Create a CloudFormation stack in AWS](#creating-json-to-create-a-cloudformation-stack-in-aws)
*   [Building Ansible Playbook to deploy with the template parameter](#building-ansible-playbook-to-deploy-with-the-template-parameter)
*   [Verifying the CloudFormation stack in AWS Cloud](#verifying-the-cloudformation-stack-in-aws-cloud)
*   [Conclusion](#conclusion)

If you are looking to create or manage CloudFormation stacks on AWS Cloud, then automating with the [Ansible CloudFormation module](https://docs.ansible.com/ansible/latest/collections/amazon/aws/cloudformation_module.html) is one you must try! Deploying with the Ansible CloudFormation module only requires running a single Ansible command.

[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) is an AWS service that helps you set up your AWS resources to spend less time managing those resources and more time focusing on your applications that run in AWS.

In this tutorial, you’ll learn how to manage IaC with Ansible CloudFormation using different templates in the AWS Cloud.

Read on and get started!

## Prerequisites

This tutorial comprises step-by-step instructions. If you’d like to follow along, be sure you have the following in place:

*   An [Ansible controller host](https://docs.ansible.com/ansible/latest/installation_guide/index.html) – This tutorial uses Ansible v2.11.7 on an [Ubuntu 20.04.](https://adamtheautomator.com/install-ansible/)3 LTS machine.

Related:[Guide: How to Setup Ansible (Ubuntu, RHEL, CentOS, macOS)](https://adamtheautomator.com/install-ansible/)

*   A remote Linux computer to test out the Ansible CloudFormation module (amazon.aws.cloudformation) – This tutorial uses Ubuntu 20.04.3 LTS as the remote node called.
    
*   An [AWS account](https://repost.aws/knowledge-center/create-and-activate-aws-account) with an AWS S3 bucket.
    
*   An AWS IAM user, an [access key ID, and a secret key](https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html) [set up on your local machine](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) with access to create and manage Cloudformation stacks on AWS Cloud.
    

Related:[Learning Identity and Access Management (IAM) AWS Through Examples](https://adamtheautomator.com/iam-aws/)

*   An [inventory file](https://docs.ansible.com/ansible/latest/inventory_guide/intro_inventory.html) and one or more hosts are configured to run Ansible commands and playbooks. The remote Linux computer is called _myserver,_ and this tutorial uses an inventory group called _web_.
    
*   Python v3.6 or later installed on your Ansible controller host and the remote node machine – This tutorial uses Python v3.9 on an Ubuntu machine.
    

Related:[How Do You Install Python 3.6?](https://adamtheautomator.com/install-python-36/)

*   [Python modules boto3](https://zoomadmin.com/HowToInstall/UbuntuPackage/python-boto3) greater than 1.15.0 and [botocore](https://docs.aws.amazon.com/efs/latest/ug/install-botocore.html) greater than 1.18.0 installed on the Ansible controller host and the remote node machine.

Related:[Managing AWS S3 with Python Boto3](https://adamtheautomator.com/boto3-s3/)

## Creating JSON to Create a CloudFormation stack in AWS

If you need to create multiple CloudFormation stacks, manually doing so on the AWS console will consume lots of effort and time. Instead, using the Ansible playbook will be a good alternate.

Ansible Playbooks offer repeatable, re-usable configuration management and multi-machine deployment system with which you can launch as many Cloudformation stacks with a single command.

Kick off this tutorial by creating a CloudFormation stack with JSON template using the [`ansible-playbook`](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks.html) command.

1\. First, log in to your Ansible controller host using your favorite SSH client.

2\. Next, run the following commands to create a directory called `~/ansible_cloudformation_stacks_demo`. This directory will contain the [playbook](https://www.redhat.com/en/topics/automation/what-is-an-ansible-playbook#:~:text=An%20Ansible%C2%AE%20playbook%20is,make%20up%20an%20Ansible%20inventory). and all the required configuration files that you’ll use to invoke the Ansible CloudFormation module.

```yaml
# Creating the directory and switching to it.
mkdir ~/ansible_cloudformation_stacks_demo
cd ~/ansible_cloudformation_stacks_demo
```

3\. Switch to your remote node, and create a JSON file called _cloudformation-example.json_ in the _tmp_ directory with your preferred text editor. Populate the file with the following JSON template.

> _Apart from JSON templates, you can now create a CloudFormation stack with [Jinjatemplates, apart from JSON templates](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_templating.html). Jinja templates are template files that store variables used at runtime. When Playbooks are executed, these variables get replaced by actual values defined in Ansible playbooks._

Related:[How to Create Ansible Templates to Save Configuration Time](https://adamtheautomator.com/ansible-template/)

The JSON template below creates the AWS EC2 instance named (MyEC2Instance) with the Image id (ami-0fb653ca2d3203ac1), key (ps), and an Instancetype of t2.micro. An Amazon Machine Image (AMI) provides the information required to launch an instance to find the correct ami [click here](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html).

This JSON file will be rendered with Ansible Playbook when you execute the Ansible task with template parameter and create the Cloudformation stack. A CloudFormation Stack is a JSON or YAML formatted text file, or you can save these provide extension, such as .json, .yaml, .template, or .txt.

> _Comments are provided in this JSON file, but JSON does not support comments therefore remove them before utilizing the file._

```json
{
    "AWSTemplateFormatVersion" : "2010-09-09",
# Declaring the Resources that needs to be created in AWS cloud
    "Resources" : {
# Creating AWS EC2 instance in AWS cloud
      "MyEC2Instance" : {
        "Type" : "AWS::EC2::Instance",
# Setting the ami, key and Instance type of AWS EC2 instance  
        "Properties" : {
# Declaring the Amazon Machine Image 
          "ImageId" : "ami-0fb653ca2d3203ac1",
# Declaring the Instance type of AWS EC2 and key that will be assigned to the instance 
          "InstanceType" : "t2.micro",
          "KeyName" : "ps"
            }
         }
     }
}
```

## Building Ansible Playbook to deploy with the template parameter

Now that you have a JSON file created in your local machine, which is great, Next, you will need to create Ansible Playbooks that will execute the task containing the template parameter.

Ansible runs the JSON file templates using the [template module](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_module.html#template-module).

Let’s get into building the Ansible Playbook to deploy with the template parameter.

Assuming you are still logged into the Ansible controller host:

> _Instead of a template parameter, you can also use template\_path, template\_fullpath, template\_destpath to define the path of the file accordingly._

1\. Create a file called _main.yml_ in the _~/ansible\_cloudformation\_stacks\_demo_ directory into your Ansible controller host and copy/paste the following YAML playbook contents.

The playbook below creates the CloudFormation stack, ansible-cloudformation-ata to launch one instance with instance type t2.micro in the us-east-2 region. This playbook uses the template that you created in the previous section.

> _The tutorial creates a cloudformation stack in the us-east-2 region. But a list of_ [regions that AWS support](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) _is also available._

```yaml
---
- name: Ansible Cloudformation module example using a template parameter
# Defining the remote server where the Cloudformation module will run 
  hosts: web
# Defining the remote user (ubuntu) where the Cloudformation module will run 
  remote_user: ubuntu  
  tasks:
    - name: create a cloudformation stack
      amazon.aws.cloudformation:
        stack_name: "ansible-cloudformation-shanky"
# Ansible removes the CloudFormation from the AWS Cloud if you set the state value as absent.
# Ansible creates the CloudFormation in the AWS Cloud if you set the state value as present.
        state: "present"
        region: "us-east-2"
# create a cloudformation stack Using template parameter
        template: "files/cloudformation-example.json"
# If you need to create a cloudformation stack Using Jinja template
# uncomment the template_body parameter using lookup of Jinja2 template and comment template parameter
# template_body: "{{ lookup('template', 'cloudformation.j2') }}"
# Declaring the tags to the CLoudformation stack
        tags:
          Stack: "ansible-cloudformation"
```

2\. Now, run the command below to invoke the playbook (`main.yml`) that executes the tasks to create the CloudFormation stack on the AWS cloud.

```bash
# Executing the Ansible Playbook to create the CloudFormation stack on the AWS cloud
ansible-playbook main.yml
```

Below, you can see that TASK \[Gathering Facts\] shows an OK status, which indicates all the configuration files and parameters look good to Ansible.

The TASK \[create a cloudformation stack\] shows a changed status that tells you Ansible completed the task you specified in the Ansible playbook.

![Running the ansible-playbook to create the CloudFormation Stack in AWS Cloud.](https://adamtheautomator.com/wp-content/uploads/2022/03/image-91.png)

Running the ansible-playbook to create the CloudFormation Stack in AWS Cloud.

## Verifying the CloudFormation stack in AWS Cloud

At this point, you should have a CloudFormation stack built-in AWS Cloud but let’s verify to make sure in the AWS Management Console.

1\. Open your favorite web browser, navigate to the [AWS Management Console](https://aws.amazon.com/console/) and log in.

2\. Open your favorite web browser, and log in to the [AWS Management Console](https://aws.amazon.com/console/). Search for **Cloudformation** in the search box at the top of the console, and click on the **Stacks** menu item.

Below, you can see the Logical and Physical ID of the stack (ansible-cloudformation-shanky) you created previously with the Ansible Playbook.

> _If you no longer require the web application or AWS instance, you can delete the stack, deleting all related resources._

![Verifying the CloudFormation Stack in AWS account](https://adamtheautomator.com/wp-content/uploads/2022/03/image-92.png)

Verifying the CloudFormation Stack in AWS account

3\. Finally, navigate the AWS EC2 page to verify the AWS EC2 instance.

> _AWS CloudFormation rolls the stack back and automatically deletes any created resources if a resource can’t be created. And if a resource can’t be deleted, any remaining resources are retained until the stack can be successfully deleted._

Like the one below, you’ll see your newly created instance with the same ID from the CloudFormation stack (step two).

![Verifying the AWS EC2 Instance Created by CloudFormation Stack](https://adamtheautomator.com/wp-content/uploads/2022/03/image-93.png)

Verifying the AWS EC2 Instance Created by CloudFormation Stack

Again while verifying, you’ll see another CloudFormation stack if you would have created using Jinta templating(ansible-cloudformation-shanky-jinja) created in the AWS Cloud.

> _Creating a CloudFormation stack with JSON templates or with templates\_paramaters stored on your local machine could be risky as they can get lost or corrupted. It is recommended to store your template in cloud-based storage such as AWS S3 bucket and call it from the Ansible module using the [template\_url](https://docs.ansible.com/ansible/latest/collections/community/aws/cloudformation_stack_set_module.html#parameter-template_url) parameter._

![Verifying CloudFormation Stack Created with Jinja Template in the AWS Cloud](https://adamtheautomator.com/wp-content/uploads/2022/03/image-94.png)

Verifying CloudFormation Stack Created with Jinja Template in the AWS Cloud

## Conclusion

In this tutorial, you’ve taken advantage of the Ansible AWS CloudFormation module to manage AWS CloudFormation stacks with a single command. You also realized that there are many ways to create CloudFormation stacks, such as using JSON and Jinja templates.

Why not deploy [AWS services using the Ansible CloudFormation module](https://docs.ansible.com/ansible/latest/collections/amazon/aws/cloudformation_module.html) in your upcoming projects with this newfound knowledge?

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fansible-cloudformation%2F&text=How%20To%20Manage%20IaC%20with%20Ansible%20CloudFormation%20in%20AWS)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fansible-cloudformation%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fansible-cloudformation%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2022/05/Manage-Playbooks-and-Inventories-Easily-with-Ansible-Tower.jpg)

### [Ansible Tower Basics for Easy Playbook and Inventory Management](/ansible-tower/)

Master Ansible Tower for effortless playbook and inventory management, elevating your automation skills to the next level with practical, user-friendly strategies.

![](https://adamtheautomator.com/wp-content/uploads/2022/08/How-to-Manage-Services-With-the-Ansible-Service-Module.jpg)

### [How to Manage Services With the Ansible Service Module](/ansible-service/)

Learn how to manage, control, and integrate OS services with the Ansible Service module in this ATA Learning tutorial!

![](https://adamtheautomator.com/wp-content/uploads/2022/05/Secure-Your-Secrets-With-Ansible-Vault.jpg)

### [Secure Your Secrets With Ansible Vault](/ansible-vault/)

Make sure your playbook and environment secrets are secure with the Ansible Vault and level up your playbooks in this ATA Learning tutorial!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
