How to Manage Virtual Machines With Ansible EC2 AWS Module

Published:5 January 2022 - 7 min. read

Azure Cloud Labs: these FREE, on‑demand Azure Cloud Labs will get you into a real‑world environment and account, walking you through step‑by‑step how to best protect, secure, and recover Azure data.

When you manage existing Amazon Web Service (AWS) EC2 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 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:

Ensure the IAM user is set up for programmatic access and that you assign it to the existing policy of AmazonEC2FullAccess.

  • An inventory file 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.
  • Python modules boto3 greater than 1.15.0 and botocore 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 of your choice.

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
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 and all the required configuration files that you’ll use to invoke the Ansible AWS EC2 module.

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.

From this point throughout the tutorial, replace aws_access_key, aws_secret_key values with your own.

---
- 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.

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
Executing a Playbook

4. Now, open your favorite web browser, and log in to the AWS Management 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
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
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).

---
- 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

ansible-playbook stop.yml
Executing the Ansible playbook using the ansible-playbook command.
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
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, and creating a volume for storage 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).

---
- 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

ansible-playbook advanced.yml
Executing the Ansible Playbook to Create an Instance with Tag, Volume, and Cloud Watch Monitoring
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.
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.
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?

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!