Configuring EC2 Instance using Ansible

Last updated: October 23, 2024

Introduction

This guide provides detailed steps to configure an AWS EC2 instance using Ansible. It covers dynamic inventories, installing web servers (Nginx/Apache), deploying Node.js/Django applications, and using best practices.

Dynamic Inventory

A dynamic inventory dynamically fetches host details during runtime. Use the following configuration for AWS EC2:


plugin: aws_ec2
regions:
  - us-east-1
filters:
  instance-state-name: running
  "tag:owner": ujwal.budha
hostnames:
  - instance-id
      

Enable the plugin in ansible.cfg:

[inventory]
enable_plugins = aws_ec2

Ansible File Structure

Below is the file structure used for this setup:


ansible/
├── ansible.cfg
├── aws_ec2.yml
├── playbook.yml
└── roles/
    ├── nginx/
    │   ├── handlers/
    │   │   └── main.yml
    │   └── tasks/
    │       └── main.yml
    └── node/
        ├── tasks/
        │   └── main.yml
        └── vars/
            └── main.yml
      

Playbook Configuration

The playbook.yml file defines the playbook execution:


---
- hosts: aws_ec2
  become: true
  gather_facts: true
  roles:
    - node
    - nginx
  vars:
    ansible_connection: aws_ssm
    ansible_aws_ssm_bucket_name: sujata-static-website-one
    ansible_aws_ssm_profile: default
      

Roles

Node Role


- name: Update apt cache
  ansible.builtin.apt:
    update_cache: yes
- name: Install npm, nodejs
  ansible.builtin.apt:
    name:
      - npm
      - nodejs
    state: latest
      

Nginx Role


- name: Install nginx
  ansible.builtin.apt:
    name: nginx
    state: latest
- name: Configure Nginx
  ansible.builtin.template:
    src: nginx.j2
    dest: /etc/nginx/sites-enabled/default
  notify: restart nginx
      

Template for Reverse Proxy


server {
	listen 80 default_server;
	server_name _;
	location / {
		proxy_pass http://localhost:3000;
	}
}
      

Running the Playbook

Execute the playbook with the following command:

ansible-playbook -i aws_ec2.yml playbook.yml
DynamoDB Table Creation

Hosted Website

and finally to check the output we will visit the public ip of our instance

DynamoDB Table Creation

Reference