Install and Configure NGINX on Multiple EC2 Instances Using Ansible

mishmish
2 min read

Step 1: Launch 3 EC2 Instances

  • Create 1 EC2 instance to act as the Ansible Master Node

  • Create 2 EC2 instances as Target Nodes

  • Make sure all instances:

    • Use Amazon Linux 2

    • Are in the same VPC/security group

    • Allow SSH (port 22) and HTTP (port 80) access


🔐 Step 2: Connect to Master Node and Install Ansible

Login to your master node via SSH:

ssh -i "my-key.pem" #3.147.75.129 ec2-user@<master-node-public-ip>#3.147.75.129

Once inside, check if Ansible is already installed:

ansible --version

If not installed, run:

sudo yum install ansible -y


🗝️ Step 3: Add EC2 Key for SSH Access to Targets

We need to add our .pem file to the master node so it can SSH into the target instances.

  1. Go to home directory:
cd /home/ec2-user/
  1. Create your key file:
vim ec2-key.pem

  1. Set proper permissions:
chmod 400 ec2-key.pem

🧠 Step 4: Configure Ansible Inventory File

Edit the inventory file:

sudo vim /etc/ansible/hosts

Add your target EC2 public IPs under a group:

[myservers]
18.225.95.209
18.118.141.148


🧪 Step 5: Create Your Playbook (install_nginx.yaml)

Here’s a simple playbook to install NGINX:

- name: Install NGINX on targets
  hosts: myservers
  become: yes
  tasks:
    - name: Install NGINX
      yum:
        name: nginx
        state: present

    - name: Start NGINX
      service:
        name: nginx
        state: started


🧩 Step 6: SSH Agent and Key Setup

Even though you added the key, you need to add it to the SSH agent:

Start SSH agent:

ssh-agent bash

Copy the key to the .ssh directory:

cp ec2-key.pem ~/.ssh/

Add the key:

ssh-add ~/.ssh/ec2-key.pem

After its added, it will be shown as below


🎯 Step 7: Run the Ansible Playbook!

Finally, run the playbook:

ansible-playbook install_nginx.yaml -v

If all went well, you’ll see successful tasks completed on both target servers.

0
Subscribe to my newsletter

Read articles from mish directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

mish
mish