---
title: "How to Manage Virtual Machines With Ansible EC2 AWS Module"
description: "Learn how to manage multiple virtual machines, like AWS EC2 instances with the Ansible EC2 AWS module in this tutorial!"
canonical: "https://adamtheautomator.com/ansible-ec2/"
---

# How to Manage Virtual Machines With Ansible EC2 AWS Module

> Learn how to manage multiple virtual machines, like AWS EC2 instances with the Ansible EC2 AWS module in this tutorial!

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

---

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 Virtual Machines With Ansible EC2 AWS Module](https://adamtheautomator.com/wp-content/uploads/2022/01/How-to-Manage-Virtual-Machines-With-Ansible-EC2-AWS-Module.jpg)

# How to Manage Virtual Machines With Ansible EC2 AWS Module

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

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

Tags:[Ansible](/tag/ansible/)[AWS EC2](/tag/aws-ec2/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Creating or Restarting an EC2 Instance with Ad Hoc Commands](#creating-or-restarting-an-ec2-instance-with-ad-hoc-commands)
*   [Launching an EC2 Instance with Ansible Playbook](#launching-an-ec2-instance-with-ansible-playbook)
*   [Stopping Multiple AWS EC2 Instances](#stopping-multiple-aws-ec2-instances)
*   [Creating an Instance with Tag, Volume, and Cloud Watch Monitoring](#creating-an-instance-with-tag-volume-and-cloud-watch-monitoring)
*   [Conclusion](#conclusion)

When you manage existing [Amazon Web Service (AWS) EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) instances, clicking around the Management Console works fine. But as your infrastructure grows, managing instances takes a load of time and becomes complex. Is there a better way to manage instances? Yes! The [AWS Ansible EC2 module](https://docs.ansible.com/ansible/latest/collections/amazon/aws/ec2_instance_module.html#ansible-collections-amazon-aws-ec2-instance-module) can help.

Not a reader? Watch this related video tutorial!

**_Not seeing the video? Make sure your ad blocker is disabled._**

In this tutorial, you will learn how the Ansible AWS EC2 module gives you a powerful grip to manage AWS EC2 instances in an example-driven approach.

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.3 LTS machine.

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

*   A remote Linux computer to test out the amazon.aws.ec2\_instance Ansible module. This tutorial uses Ubuntu 20.04.3 LTS as the remote node.
*   An [AWS account](https://repost.aws/knowledge-center/create-and-activate-aws-account).
*   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 EC2 instances. This tutorial will use an IAM user called ec2_user_.

> _Ensure the IAM user is set up for [programmatic access](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html) and that you assign it to the existing policy of AmazonEC2FullAccess._

*   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.8.10 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 should be installed on the Ansible controller host and the remote node machine.

## Creating or Restarting an EC2 Instance with Ad Hoc Commands

If you plan to create or restart a single EC2 instance on an AWS account, running ad hoc commands will suffice. Ad hoc commands are a quick and efficient way to run a single command to create an EC2 instance or modify an AWS EC2 instance’s instance type.

Log onto your Ansible controller and run the below `ansible` command to connect (`-m amazon.aws.ec2_instance`) to the host (`web`).

The command passes an argument (`-a`) that tells Ansible to restart the AWS EC2 instance with `instance_tags=Name=Tag1`) in the `us-east-2` region. To authenticate the connection to the AWS account, you add `aws_access_key` and `aws_secret_key` details in the ad hoc command.

> _The tutorial performs all the actions in the us-east-2 region, but you can perform the same actions in [any AWS region](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/) of your choice._

```bash
ansible web -m amazon.aws.ec2 -a " state=restarted instance_tags=Name=Tag1 aws_access_key=AKIAVWOJMI5I2DPXXXX aws_secret_key=F9PaprqnPUn/XXXXXXXXXXXX region=us-east-2"
```

Once the command completes, you’ll see a **CHANGED** message, as shown below, that confirms Ansible successfully restarted the AWS EC2 instance.

![Running an Ad Hoc Command to Restart an Amazon EC2 Instance](https://adamtheautomator.com/wp-content/uploads/2022/01/image-20.png)

Running an Ad Hoc Command to Restart an Amazon EC2 Instance

## Launching an EC2 Instance with Ansible Playbook

You’ve just learned how to execute an Ansible ad hoc command, which is great for a one-off action! But perhaps you need to perform multiple tasks. If so, create an Ansible playbook that will launch an EC2 instance to run multiple tasks.

1\. Open the terminal in your Ansible controller host, then run the following commands to create a directory called `~/ansible_aws_ec2_module` and switch to that directory.

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 AWS EC2 module.

```yaml
mkdir ~/ansible_aws_ec2_module
cd ~/ansible_aws_ec2_module
```

2\. Next, open your favorite text editor, create a file called _main.yml_ in the _~/ansible\_aws\_ec2\_module_ directory. Populate the _main.yml_ file with the following YAML playbook contents.

The playbook below contains the task that starts an instance with a public IP address within a particular VPC in an AWS account.

Related:[Building an AWS VPC with Terraform Step-by-Step](https://adamtheautomator.com/terraform-vpc/)

> _From this point throughout the tutorial, replace `aws_access_key`, `aws_secret_key` values with your own._

```yaml
---
- name: Ansible EC2 instance Launch module demo
# Defining the remote server where the Ansible EC2 module will manage the objects
  hosts: web
  remote_user: ubuntu # Using Remote user as ubuntu
  tasks:
		# Task to start an AWS EC2 instance with a public IP
    - name: start an instance with a public IP address
      amazon.aws.ec2:
				# Setting the keyname 
        key_name: mykey
				# Define the instance_type, image, vpc_subnet_id, assign_public_ip, aws_region
        instance_type: t2.micro
        image: ami-0b9064170e32bde34
        wait: yes
        count: 1
        vpc_subnet_id: subnet-0dc9af4c75ad3e2ee
        assign_public_ip: yes
        aws_region: us-east-2
        aws_access_key: AKIAVWOJMI5XXXXXXXX
        aws_secret_key: F9PaprqnPUn/NP8lzQXXXXXXXXXXXXXXXXXX
```

3\. Run the command below to invoke the playbook (`main.yml`). The playbook then executes the tasks to create a new instance in the `us-east-2` region with instance type as t2.micro.

```bash
ansible-playbook main.yml
```

Below, you can see that some tasks show a **changed** status, which indicates Ansible created the instance successfully and modified the task’s state to run the command. In contrast, you see an **ok** status since some tasks don’t require changes.

![Executing a Playbook](https://adamtheautomator.com/wp-content/uploads/2022/01/image-21.png)

Executing a Playbook

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

5\. Finally, click on the search bar at the top of the console, search for **EC2**, and click on the **EC2** menu item. Doing so redirects your browser to the EC2 page.

![Searching the EC2 service in the AWS account](https://adamtheautomator.com/wp-content/uploads/2022/01/image-22.png)

Searching the EC2 service in the AWS account

On the EC2 page, you’ll see your newly created instance, as shown below.

![newly created instance](https://adamtheautomator.com/wp-content/uploads/2022/01/image-23.png)

newly created instance

## Stopping Multiple AWS EC2 Instances

Perhaps some AWS EC2 instances no longer serve a purpose. If so, you can stop or terminate multiple instances by executing an Ansible playbook. Specify the instance IDs and declare values in a task to set the Ansible EC2 AWS module’s behavior in stopping the instances.

1\. Create an Ansible playbook named _stop.yml_ and copy/paste the code below to the playbook.

The below playbook stops two instances (i-0d8c7eb4eb2c643a1 and i-0dbc17a67c0f7577c).

```yaml
---
- name: Stopping the already Launched EC2 instances using Ansible EC2 Module
# Defining the remote server where the Ansible EC2 module will manage the objects
  hosts: web
  gather_facts: false
  # Using Remote user as ubuntu
  remote_user: ubuntu 
  vars:
    instance_ids:
      - 'i-0d8c7eb4eb2c643a1'
      - 'i-0dbc17a67c0f7577c'
    region: us-east-2
  tasks:
    - name: Stopping the already launched AWS EC2 instances
      amazon.aws.ec2:
        instance_ids: '{{ instance_ids }}'
        region: '{{ region }}'
        state: stopped
        wait: True
        vpc_subnet_id: subnet-0dc9af4c75ad3e2ee
        assign_public_ip: yes
        aws_access_key: AKIAVWOJMI5XXXXXXXX
        aws_secret_key: F9PaprqnPUn/NP8lzQXXXXXXXXXXXXXXXXXX
```

> _If you prefer to terminate the instances rather than stop them, change the `state` value to `absent`._

2\. Now run the below command to execute the playbook (`stop.yml`), which will stop the instances you specified in the playbook. `ansible-playbook stop.yml`

```bash
ansible-playbook stop.yml
```

![Executing the Ansible playbook using the ansible-playbook command.](https://adamtheautomator.com/wp-content/uploads/2022/01/image-24.png)

Executing the Ansible playbook using the ansible-playbook command.

3\. Finally, navigate to your AWS instances in your web browser, and you’ll see that two successfully stopped instances, as shown below.

![Viewing Stopped Instances](https://adamtheautomator.com/wp-content/uploads/2022/01/image-25.png)

Viewing Stopped Instances

## Creating an Instance with Tag, Volume, and Cloud Watch Monitoring

Perhaps you need to provision your instance with more advanced components such as tagging, [monitoring with cloud watch alarms](https://aws.amazon.com/cloudwatch/), and [creating a volume for storage](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volumes.html) purposes. In that case, using the Ansible EC2 AWS module in a playbook will do the trick.

> _Tags are an excellent way to organize AWS resources and make efficient cost calculations of resources in the AWS Management Console._

1\. Create a new Ansible playbook named _advanced.yml_ and populate the playbook with the code below.

The below playbook will launch an AWS EC2 instance with (`volumes`—> `/dev/sdb`, monitoring and tag the instance with `Instance1`).

```yaml
---
- name: Adding Tag, Volumes, and cloud Watch Monitoring to an an instance
  hosts: web
  remote_user: ubuntu
  tasks:
    - name: Adding Tag, Volumes, and cloud Watch Monitoring to an an instance
      amazon.aws.ec2:
        instance_type: t2.micro
        image: ami-0b9064170e32bde34
        vpc_subnet_id: subnet-0dc9af4c75ad3e2ee
        region: us-east-2
        aws_access_key: AKIAVWOJMI5I2DXXXX
        aws_secret_key: F9PaprqnPUn/NP8lzQ5lWjXXXXXXXXXXXXXXXx
				# Creating the volumes and attaching to AWS EC2 instance of type io1
        volumes:
          - device_name: /dev/sdb
            volume_type: io1
            iops: 1000
            volume_size: 100
				# Enabling the cloud watch monitoring 
				# of the AWS EC2 instance that will be launched
        monitoring: yes
				# Tagging the AWS EC2 instance that will be launched
        instance_tags:
            Name: Instance1
```

2\. Now run the below command to execute the playbook (`advanced.yml`), which will launch an AWS EC2 instance with tag, volume, and cloud watch monitoring. `ansible-playbook advanced.yml`

```bash
ansible-playbook advanced.yml
```

![Executing the Ansible Playbook to Create an Instance with Tag, Volume, and Cloud Watch Monitoring](https://adamtheautomator.com/wp-content/uploads/2022/01/image-26.png)

Executing the Ansible Playbook to Create an Instance with Tag, Volume, and Cloud Watch Monitoring

3\. Navigate to the Storage tab of the instance you want to verify in the AWS EC2 console. Under **Block devices**, click on a **Volume ID** from the list to view the instance’s detailed information.

![Verifying the volume created in the AWS account for the AWS EC2 instance.](https://adamtheautomator.com/wp-content/uploads/2022/01/image-27.png)

Verifying the volume created in the AWS account for the AWS EC2 instance.

4\. Finally, click on the Tags tab in the instance’s summary information page. You’ll see the tag you set for the instance in the playbook (step one), like the one below.

![Verifying the tags in the AWS account for the AWS EC2 instance.](https://adamtheautomator.com/wp-content/uploads/2022/01/image-28.png)

Verifying the tags in the AWS account for the AWS EC2 instance.

## Conclusion

In this tutorial, you’ve taken advantage of the Ansible AWS EC2 module to manage AWS EC2 instances with a single command. You also learned how to tweak AWS EC2 instances such as restarting, terminating, adding tags, and so on.

Now that you have sound knowledge of the Ansible AWS EC2 module, are you willing to make the Ansible EC2 AWS module a part of your instance management routine? Perhaps you’d want to automate the task by adding a cron job?

Related:[How To Execute and List Cron Jobs for a Linux System via PHP](https://adamtheautomator.com/list-cron-jobs/)

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fansible-ec2%2F&text=How%20to%20Manage%20Virtual%20Machines%20With%20Ansible%20EC2%20AWS%20Module)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fansible-ec2%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fansible-ec2%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2021/09/Ansible-101-How-to-use-Ansibles-apt-to-Manage-Linux-Packages.jpg)

### [How to use the Ansible apt Module to Manage Linux Packages](/ansible-apt/)

If you're an Ansible user that needs to install some packages, you're in luck. In this tutorial on the Ansible apt module, you'll get a step-by-step introduction!

![](https://adamtheautomator.com/wp-content/uploads/2024/03/terragrunt.png)

### [Keeping Terraform Maintainable with Terragrunt](/terragrunt/)

Discover Terragrunt and embrace the power to simplify Terraform workflows—Ensure maintainability and organization of your infrastructure today!

![](https://adamtheautomator.com/wp-content/uploads/2021/05/How-to-Partition-and-Erase-Windows-Volumes-with-Diskpartx.jpg)

### [Mastering Diskpart : Erase and Partition Volumes with Ease](/diskpart/)

Learn how to create partitions, create volumes, delete volumes and partitions and manage unallocated space with the Windows Diskpart utility.

## 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/)
