How to Deploy a Web App Using Ansible in 10 Minutes
Source: Dev.to
What is Ansible?
Ansible is a powerful automation tool used for server configuration. It works over SSH, requires no agent, and uses YAML playbooks to automate tasks.
In this guide you will learn
- How to install Ansible
- How to set up a project structure
- How to add an SSH key
- How to test the SSH connection
- How to create static content files
- How to write a sample playbook
- How to configure the inventory file
- How to run the playbook
- How to verify the deployment
Step 1 – Install Ansible on Ubuntu
sudo apt update
sudo apt install ansible -y
ansible --version
Step 2 – Create Ansible Project Structure
# Create project folder
mkdir ansible_demo
cd ansible_demo
# Create inventory & playbooks directories
mkdir inventory playbooks
Inventory file
cd inventory
touch hosts.ini
Playbook file
cd ../playbooks
touch web_prac.yml
Step 3 – Add SSH Key to the Project
cd ..
mkdir ssh
cd ssh
touch nagios.pem
Paste your PEM key content into nagios.pem, then set proper permissions:
chmod 600 nagios.pem
Step 4 – Test SSH Connection with PEM
ssh -i ssh/nagios.pem ubuntu@
If you successfully log in, the connection is OK.
Step 5 – Create Files Folder for Static Content
cd ../playbooks
mkdir files
cd files
touch index.html
Add your HTML content inside index.html.
Step 6 – Sample Playbook (web_prac.yml)
---
- name: Setup Web Server
hosts: webserver
become: yes
tasks:
- name: Install NGINX
apt:
name: nginx
state: present
update_cache: yes
- name: Copy index.html to web server
copy:
src: files/index.html
dest: /var/www/html/index.html
owner: www-data
group: www-data
mode: '0644'
- name: Start and enable NGINX
service:
name: nginx
state: started
enabled: yes
Step 7 – Inventory File (hosts.ini)
[webserver]
13.201.29.244
ansible_user=ubuntu
ansible_ssh_private_key_file=../ssh/nagios.pem
Step 8 – Run the Ansible Playbook
From the ansible_demo directory:
ansible-playbook -i inventory/hosts.ini playbooks/web_prac.yml
If the run completes without errors, the deployment was successful.
Step 9 – Verify in Browser
Open a browser and navigate to:
http://
You should see the content of index.html served by NGINX.
Final Result
By the end of this guide you have:
- Installed Ansible
- Created a professional project structure
- Created an inventory file
- Written a YAML playbook
- Added an SSH key for authentication
- Automated the deployment of a web page using Ansible