DEV Community

Udoh Deborah
Udoh Deborah

Posted on

Day 59: Ansible Project – Deploying a Simple Web App with Nginx

Step 1 – Create 3 EC2 Instances
• Go to AWS Console → EC2 → Launch Instances.
• Create 3 Ubuntu servers (e.g., t2.micro if on free tier).
• Use the same key pair for all three (so Ansible can connect easily).
• Tag them for easy identification (ansible_host, web1, web2).

Step 2 – Install Ansible on the Host Server (Ansible Control Node)

SSH into your chosen host server (Ansible Host):

ssh -i yourkey.pem ubuntu@<Ansible_Host_Public_IP>
Enter fullscreen mode Exit fullscreen mode

Install Ansible:

sudo apt update
sudo apt install ansible -y
Enter fullscreen mode Exit fullscreen mode

Step 3 – Copy Private Key to Ansible Host

From your local machine, upload the key to the Ansible Host:

scp -i yourkey.pem yourkey.pem ubuntu@<Ansible_Host_Public_IP>:/home/ubuntu/.ssh/
Enter fullscreen mode Exit fullscreen mode

On the Ansible Host:

chmod 600 ~/.ssh/yourkey.pem
Enter fullscreen mode Exit fullscreen mode

Step 4 – Configure the Inventory File

Edit the Ansible inventory file:

sudo vim /etc/ansible/hosts
Enter fullscreen mode Exit fullscreen mode

Add your web servers:

[webservers]
web1 ansible_host=<Public_IP_of_Web1> ansible_user=ubuntu ansible_ssh_private_key_file=/home/ubuntu/.ssh/yourkey.pem
web2 ansible_host=<Public_IP_of_Web2> ansible_user=ubuntu ansible_ssh_private_key_file=/home/ubuntu/.ssh/yourkey.pem
Enter fullscreen mode Exit fullscreen mode

Save and exit.

Step 5 – Create Ansible Playbook to Install Nginx

Create a playbook file:

vim install_nginx.yml
Enter fullscreen mode Exit fullscreen mode

Add:

- name: Install Nginx on web servers
  hosts: webservers
  become: true
  tasks:
    - name: Update apt packages
      apt:
        update_cache: yes

    - name: Install Nginx
      apt:
        name: nginx
        state: present
Enter fullscreen mode Exit fullscreen mode

Run it:

ansible-playbook install_nginx.yml

Enter fullscreen mode Exit fullscreen mode

Step 6 – Deploy a Sample Web Page

Create a new playbook:

vim deploy_web.yml

Add:

- name: Deploy Sample Web Page
  hosts: webservers
  become: true
  tasks:
    - name: Copy index.html to servers
      copy:
        src: /home/ubuntu/index.html
        dest: /var/www/html/index.html
Enter fullscreen mode Exit fullscreen mode

First, create your sample file on the Ansible Host:

echo "<h1>Welcome to my Ansible Web Project 🚀</h1>" > index.html
Enter fullscreen mode Exit fullscreen mode

Run the playbook:

ansible-playbook deploy_web.yml
Enter fullscreen mode Exit fullscreen mode

Step 7 – Test Your Deployment
• Visit http:// and http:// in your browser.
• You should see: Welcome to my Ansible Web Project

With this, you’ve automated the installation of Nginx and the deployment of a web page across multiple servers using Ansible.

Top comments (0)