This Task focuses on deploying a sample web application (Flask or Node.js) using Ansible to automate the setup of dependencies, configure the server, and manage the application as a systemd service.
Run the Ansible playbook to execute all tasks in sequence.
Run the following commands to install Ansible on your local machine or a dedicated Ansible control node:
sudo apt update && sudo apt install -y ansible
ansible --version
Create inventory.ini with the target server:
[web]
your-server-ip ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_rsa
---
- name: Deploy Sample Application
hosts: web
become: yes
tasks:
- name: Update and install required packages
apt:
name:
- python3
- python3-pip
- python3-venv
- git
- nginx
state: present
update_cache: yes
- name: Install Node.js (if deploying Node.js app)
shell: |
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
when: "'node_app' in group_names"
- name: Clone the application repository
git:
repo: "https://github.com/example/flask-sample-app.git"
dest: "/opt/app"
version: main
- name: Install Python dependencies
pip:
requirements: "/opt/app/requirements.txt"
virtualenv: "/opt/app/venv"
when: "'flask_app' in group_names"
- name: Install Node.js dependencies
command: npm install
args:
chdir: "/opt/app"
when: "'node_app' in group_names"
- name: Create a systemd service for the application
template:
src: app.service.j2
dest: /etc/systemd/system/app.service
notify: Restart Application
- name: Reload systemd and enable the application
systemd:
daemon_reload: yes
name: app
state: started
enabled: yes
- name: Configure Nginx reverse proxy
template:
src: nginx.conf.j2
dest: /etc/nginx/sites-available/app
notify: Restart Nginx
- name: Enable Nginx site
file:
src: /etc/nginx/sites-available/app
dest: /etc/nginx/sites-enabled/app
state: link
- name: Restart Nginx
systemd:
name: nginx
state: restarted
enabled: yes
handlers:
- name: Restart Application
systemd:
name: app
state: restarted
- name: Restart Nginx
systemd:
name: nginx
state: restarted
[Unit]
Description=Sample Application
After=network.target
[Service]
User=ubuntu
WorkingDirectory=/opt/app
ExecStart=/opt/app/venv/bin/python /opt/app/app.py
Restart=always
[Install]
WantedBy=multi-user.target
server {
listen 80;
server_name your-server-ip;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
ansible-playbook -i inventory.ini deploy_app.yml
sudo systemctl status app
sudo nginx -t
http://your-server-ip
in a browser.This project automates the deployment of a Flask or Node.js application using Ansible. It installs dependencies, sets up systemd
for application management, and configures Nginx as a reverse proxy. This setup ensures scalability, high availability, and automation for application deployment.