DEV Community

Poojan Mehta
Poojan Mehta

Posted on • Originally published at Medium on

Setting Up Ansible for EC2 With Dynamic Inventory

Setting Up Ansible for EC2 With Dynamic Inventory🙂

In this article, I will demonstrate how to provision EC2 instance using ANSIBLE and how do set up a more agile environment using the DYNAMIC INVENTORY.

→Pre-requisites:

— >RedHat Ansible downloaded and configured in the local system.

Do check out my previous article for Ansible👇👇:

LINUX AUTOMATION WITH ANSIBLE

~Problem Statement:

♦️ Deploy Web Server on AWS through ANSIBLE!

🔹 Provision EC2 instance through ansible.

🔹 Retrieve the IP Address of instance using the dynamic inventory concept.

🔹 Configure the webserver through ansible!

  • As Ansible is built on top of python, a Python Software Development Kit (SDK) is required that enables the configuration of AWS services. The package is an object-oriented API named boto3.
pip3 install boto3 //assuming python3 is installed
Enter fullscreen mode Exit fullscreen mode

→STEP-1)

  • In the first step, I provisioned an ec2 instance with this playbook.
  • Here, the RedHat system itself calls the API for configuration on AWS, and this procedure is done on the local machine that’s why the host is supposed to be localhost.
  • For authentication to the AWS account, create one IAM user that has less privileged than the root account. The AWS_ACCESS_KEY and AWS_SECRET key are passed explicitly through an Ansible vault named secret.yml


Encrypted Vault🔒

- hosts: localhost
  vars_files:
      - secret.yml
  tasks:
   - name: Provision os in AWS
     ec2:
      key_name: "keytask" //keypair to be attached to the instance  
      instance_type: "t2.micro"
      image: "ami-0ebc1ac48dfd14136" //amazon linux 
      count: 1
      wait: yes
      vpc_subnet_id: "subnet-e7780dab"
      region: "ap-south-1" //asia-pecific-south region of AWS
      state: present
      assign_public_ip: yes
      group_id: "sg-0512d293cfb4af6e4" //security group 
      aws_access_key: "{{ myuser }}"
      aws_secret_key: "{{ mypass }}"
     register: ec2   

- debug:
       var: ec2.instances[0].public_ip
Enter fullscreen mode Exit fullscreen mode


ansible-playbook ec2.py — ask-vault-pass🚀

Ansible register allows the user to capture the output and store as variables and can be used in different scenarios. The variables will contain the value returned by the task.

The register variable will print the public IP address of the instance from Ansible facts it gathers.

→STEP-2)

The instance has been launched! Next what? 🤔🤔

We need to dump the IP address of this instance into the inventory file and do the further procedure!

Wondering I will simply write the IP in the host file🤭?? NAH ! Not manually 🤫🤫

AND THIS IS WHERE 🔥DYNAMIC INVENTORY🔥 COMES TO PLAY:

→Ansible dynamic inventory is a concept that contains scripts that work as external APIs and pulls the information(facts) of a particular provider.

→The gathered facts will be dynamically dumped into the host file and further, we can create groups of these hosts according to requirement.

→Copy the following files into the controller node to enable dynamic inventory.

[https://raw.githubusercontent.com/ansible/ansible/stable-1.9/plugins/inventory/ec2.py](https://raw.githubusercontent.com/ansible/ansible/stable-1.9/plugins/inventory/ec2.py)

[https://raw.githubusercontent.com/ansible/ansible/stable-1.9/plugins/inventory/ec2.ini](https://raw.githubusercontent.com/ansible/ansible/stable-1.9/plugins/inventory/ec2.ini)
Enter fullscreen mode Exit fullscreen mode

→Both files need to be in executable format:

chmod +x ec2.py
chmod +x ec2.ini
Enter fullscreen mode Exit fullscreen mode

→Also, for account authentication, pass AWS_ACCESS_KEY and AWS_SECRET_KEY in the ec2.ini file. This will contact to AWS on our behalf and retrieve the information of the ec2 instance.

→Edit the inventory file in the ANSIBLE.CFG configuration files too.

→Now, to see the output, run ./ec2.py - - list

→Also, run ansible all — — list-hosts to see the available hosts.


Host added dynamically😃

→STEP-3)

→With a defined host, now the final step is to deploy our application! In this example, I am deploying an apache webserver.

→Before that, enter the key file in the ansible configuration file.

private_key_file= /root/path-to-private-key 🔒
Enter fullscreen mode Exit fullscreen mode

This file also needs to be executable .. chmod 600 key_name.pem

🙌Out of the box yet important information about file access:

These numbers show different types of permissions given to a file or a directory.

the format is: chmod XYZ

x is the root or owner permissions

y is the group permissions

z is the permission for other users

Now let’s get to know what does these numbers mean. So, there are generally three types of permissions: read (r), write (w), and executable (x)

each number denotes some kind of permissions. They are:

0 = no permission

1 = only execute (- — x)

2 = only write (-w-)

3 = write an execute (-wx)

4 = only read (r — )

5 = read and execute (r-x)

6 = read and write (rw-)

7 = all (rwx)chmod 777: here, 7 means all permissions and three 7s means the rwx permission is given to all (owner, group, and other)

similarly, you can calculate the same for all the numbers.

Now, run one playbook that downloads the required packages into the instance and copy the code into the document root of the webserver.

- hosts: all
  become: yes
  remote_user: ec2-user //login as this user in the instance
  tasks:

- name: Download Httpd and Git in remote system
        package:
         name:
           - httpd
           - git
         state: present

- name: Clone code from GitHub
        git:
         repo: '[https://username:password@github.com/poojan1812/Ansible.git'](https://poojan1812:07Pm18120021@github.com/poojan1812/Ansible.git')
         dest: "/var/www/html/"

- name: start the services of httpd
        service:
         name: "httpd"
         state: restarted
Enter fullscreen mode Exit fullscreen mode


ansible-playbook server.yml

→The output of this playbook -


Service started and code copied from GitHub to the doc. root

FINAL OUTPUT-

THAT’S IT

→🤗All steps completed and the Problem statement matched successfully!!

THANKS, A LOT FOR READING THIS SO ATTENTIVELY

I’ll be grateful to have connections like you on Linkedl *n * 🧑‍💼


Top comments (0)