Deploying Applications
Deploying an application involves multiple steps: pulling code, installing dependencies, configuring services, and restarting. Ansible playbooks can automate the entire deployment process.
Example: Deploy a Python Web App (Flask)
Assume we have a Flask app in a Git repository. The playbook below deploys it to a server.
---
- name: Deploy Flask application
hosts: webservers
become: yes
vars:
app_user: flaskapp
app_dir: /opt/flaskapp
tasks:
- name: Ensure system packages are installed
apt:
name:
- python3-pip
- python3-venv
- git
state: present
update_cache: yes
- name: Create application user
user:
name: "{{ app_user }}"
system: yes
state: present
- name: Clone repository
git:
repo: https://github.com/example/flaskapp.git
dest: "{{ app_dir }}"
version: main
force: yes
notify: restart app
- name: Create virtual environment
command: python3 -m venv venv
args:
chdir: "{{ app_dir }}"
become_user: "{{ app_user }}"
- name: Install dependencies
pip:
requirements: "{{ app_dir }}/requirements.txt"
virtualenv: "{{ app_dir }}/venv"
virtualenv_command: python3 -m venv
become_user: "{{ app_user }}"
- name: Copy systemd service file
template:
src: flaskapp.service.j2
dest: /etc/systemd/system/flaskapp.service
notify: restart app
- name: Start and enable service
service:
name: flaskapp
state: started
enabled: yes
handlers:
- name: restart app
systemd:
name: flaskapp
state: restarted
daemon_reload: yesUsing a Deployment Role
For production, consider creating a role. It makes the deployment reusable across projects. The role could have variables for repo URL, branch, and service name.
Blue‑Green Deployment (Simple Approach)
You can use Ansible to switch symlinks or update load balancer configurations. For example, clone the new version to a separate directory, test it, then switch the symlink:
- name: Deploy new version to staging directory
git:
repo: "{{ repo_url }}"
dest: "{{ app_dir }}_{{ timestamp }}"
version: "{{ version }}"
- name: Run smoke tests (custom module or script)
command: "{{ app_dir }}_{{ timestamp }}/test.sh"
- name: Switch symlink
file:
src: "{{ app_dir }}_{{ timestamp }}"
dest: "{{ app_dir }}"
state: link
notify: restart appRollbacks
Keep previous releases. To roll back, simply point the symlink to the previous directory and restart.
Two Minute Drill
- Automate code checkout with
gitmodule. - Use
pipmodule with virtual environments for Python apps. - Deploy as a systemd service using templates.
- Implement blue‑green by switching symlinks for zero‑downtime.
Need more clarification?
Drop us an email at career@quipoinfotech.com
