Ansible playbook to launch an ec2 instance in AWS cloud.

Ansible Playbooks are the files where Ansible code is written. Playbooks are written in YAML format. Playbooks are one of the core features of ansible that contains a list of task which tells ansible what to do. If you want to launch an EC2 Instance in AWS with an Ansible playbook, this tutorial will walk you through the steps!

Learn how to do it here

We have already discussed the basics of ansible and learned how to configure it on our machine. If you still don’t know go through our previous blog posts.

Learn ansible from scratch.

How to install and Configure Ansible on ubuntu 20.04.

Here we are using the Ansible AWS module to create and manage our ec2 instance

What is Aws EC2?

Aws EC2 is a cloud computing service in Aws where we can launch various types of virtual servers and manage their security, networking, storage etc inside the AWS cloud.
It is a completely scalable service so we can increase or decrease its capacity based on our requirements as it is a pay-as-you-go service we also don’t need to invest in upfront costs.

Prerequisites

Must have an AWS user account with administrative access.

Step 1: Installing ansible on ubuntu server 20.04
Step 2: Aws IAM account creation and collecting other details.
  • Search IAM in the AWS search console.
  • Select the users and click on add user.
  • Under user, details select any user name to enable programmatically and AWS Management Console access.
  • Attach permission for this account you can either create a policy or directly attach any existing AWS permission for this demo I am attaching administrative access
  • Add any tags that are optional
  • Review and create the user, download the access and secret key from the download .csv option and save it in your local system.

Create a key pair in order to ssh into the ec2 instance.

Go to your ec2 dashboard and under the network and security section select key pair and click on create new key pair in order to create a new one.

I have created a new key pair with the name Ansible_ec2_key.

Note down the ami details of the ec2 instance.

You need to enter the AMI ID in the playbook in order to launch the instance for that we can go to the ec2 instance launch dashboard because we are creating ubuntu 22.0 I am copying the Ami id of that instance.

Step 3: Installing python and boto in the server

sudo apt-get install python3.6

python3 –version

As I am on python 3.10 i need to install boto3 on that specific version

To install the boto python package first install the python-pip package management

sudo apt install python3-pip

Next, install boto using the command

pip3.10 install boto3

Install the ansible-galaxy collection in order to manage AWS cloud

ansible-galaxy collection install amazon.aws

Now we have done with the server setup and requirements next we are going to create our playbook

Step 4: Creating an ansible-playbook.

1:Add localhost in /etc/Ansible/hosts file Similarly as shown below.

2: Use the vi editor to create a playbook with the .yml extension

The old ec2 module is deprecated so we are using the latest module in order to create the instance. You can find further details about the module in the below documentation.

https://docs.ansible.com/ansible/latest/collections/amazon/aws/ec2_module.html

- name: Ansible ec2 lauch
  hosts: local
  connection: local
  vars:
    awsaccesskey: <paste your IAM access key>
    awssecretkey: < paste your IAM secrect key>
  tasks:
  - name: configuring security group for the instance
    ec2_group:
        name: ansiblesecuritygroup
        description: security_group
        region: us-east-1
        access_key: "{{ awsaccesskey }}"
        secret_key: "{{ awssecretkey }}"
        rules:
            - proto: tcp
              from_port: 22
              to_port: 22
              cidr_ip: 0.0.0.0/0
            - proto: tcp
              from_port: 80
              to_port: 80
              cidr_ip: 0.0.0.0/0
        rules_egress:
            - proto: all
              cidr_ip: 0.0.0.0/0
  - name: creating ec2 instance
    ec2_instance:
        security_group: ansiblesecuritygroup
        name: ansibletestinstance
        key_name: <yourkeyname>
        access_key: "{{ awsaccesskey }}"
        secret_key: "{{ awssecretkey }}"
        instance_type: t2.micro
        image_id: ami-09d3b3274b6c5d4aa
        region: us-east-1
        count: 1

Before executing this playbook let me explain the playbook.

We are defining the IAM access_key and secret_key as variables at the top.

The ansible playbook host section of a playbook specifies the servers that the tasks should be run against. Here it is running in the localhost. Also, you can group your servers accordingly in the host’s file and call the servers in the playbook

For this example, there are 2 tasks which are executed inside the playbook.
one is Creating a security group and the other is launching an ec2 instance using the created security group. We are using the ssh key already created in our AWS account in order to launch the instance

Execute the playbook using the command

ansible-playbook <playbook_name.yaml>

If you have configured all the above steps without error you will get a similar output.
If you have encountered any error debug it using the command ansible-playbook <playbook_name> -vvv.

Modifying the playbook to attach volume and volume size while creating the instance.

- name: Ansible ec2 lauch
  hosts: local
  connection: local
  vars:
    awsaccesskey: <paste your IAM access key>
    awssecretkey: < paste your IAM secrect key>
  - name: configuring security group for the instance
    ec2_group:
        name: ansiblesecuritygroup
        description: security_group
        region: us-east-1
        access_key: "{{ awsaccesskey }}"
        secret_key: "{{ awssecretkey }}"
        rules:
            - proto: tcp
              from_port: 22
              to_port: 22
              cidr_ip: 0.0.0.0/0
            - proto: tcp
              from_port: 80
              to_port: 80
              cidr_ip: 0.0.0.0/0
        rules_egress:
            - proto: all
              cidr_ip: 0.0.0.0/0
  - name: creating ec2 instance
    ec2_instance:
        security_group: ansiblesecuritygroup
        name: ansibletestinstance
        key_name: ansible_sshkey
        access_key: "{{ awsaccesskey }}"
        secret_key: "{{ awssecretkey }}"
        instance_type: t2.micro
        image_id: ami-09d3b3274b6c5d4aa
        region: us-east-1
        count: 1
        volumes: 
          - device_name: /dev/xvda
            ebs: 
              volume_size: 8
              volume_type: gp2
              delete_on_termination: true

This is an example of an Ansible playbook that can be used to launch an EC2 instance on AWS. The playbook is composed of multiple tasks, each defined by a “name” field.

  • The first task, “configuring security group for the instance“, creates a new security group named “ansiblesecuritygroup” using the “ec2_group” module. The security group is created in the “us-east-1” region, and the access and secret key are passed as variables.
  • The security group has two rules, one that allows incoming traffic on port 22 (SSH) from any IP address, and another that allows incoming traffic on port 80 (HTTP) from any IP address. It also has a rule that allows all egress traffic from the instance to any IP address.
  • The second task, “creating ec2 instance“, creates an EC2 instance using the “ec2_instance” module. The instance is created in the “us-east-1” region, and the access and secret key are passed as variables.
  • The instance is named “ansibletestinstance” and is assigned to the “ansiblesecuritygroup” security group created in the first task. The instance is also assigned an SSH key named “ansible_sshkey” which is created in the AWS earlier.
  • The image id used to launch the instance is “ami-09d3b3274b6c5d4aa”, the instance type is t2-micro and only one instance is created. The playbook also creates a volume of 8GB and type gp2 which will be deleted on termination of the instance.
  • It’s important to note that this playbook uses the variables awsaccesskey and awssecretkey to access the AWS account. In a real-world scenario, these variables should be stored in a secure location, such as an encrypted file, rather than hardcoded in the playbook.

Summary:
We have learned how to launch an ec2 instance in AWS cloud using ansible-playbook


Leave a Reply

Your email address will not be published. Required fields are marked *