Ansible Guide
Ansible Guide
Agentless Operation
Ansible does not require additional software or agents on managed systems. It
connects using SSH for Linux/Unix or WinRM for Windows.
Push-based Model
The control node sends commands directly to the managed nodes, ensuring
efficient task execution.
Platform Independence
Ansible works seamlessly across diverse environments—cloud, on-premises, or
hybrid.
Security by Design
Uses OpenSSH for secure communication and avoids storing sensitive information
by default.
Installation Steps
Ubuntu
CentOS/RHEL
ssh-keygen
ini
[web_servers]
192.168.1.101
192.168.1.102
[db_server]
192.168.1.103
Test Connectivity
yaml
---
hosts: web_servers
become: yes
tasks:
apt:
name: nginx
state: present
service:
name: nginx
state: started
Playbooks Example
yaml
---
hosts: webservers
become: yes
tasks:
apt:
name: nginx
state: present
In this example, the playbook installs the Nginx web server on a group of hosts
called webservers.
yaml
---
hosts: webservers
become: yes
tasks:
service:
name: nginx
state: started
enabled: yes
This playbook ensures the Nginx service is started and enabled to start on boot.
yaml
---
- name: Configure Nginx
hosts: webservers
become: yes
tasks:
template:
src: /path/to/nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify:
- restart nginx
handlers:
service:
name: nginx
state: restarted
This playbook copies a customized Nginx configuration file using the template
module and restarts the Nginx service if the configuration changes.
yaml
---
hosts: all
become: yes
tasks:
apt:
name:
- curl
- vim
- git
state: present
This playbook installs multiple packages (curl, vim, and git) on all specified hosts.
yaml
---
hosts: webservers
become: yes
tasks:
- name: Install Apache
apt:
name: apache2
state: present
template:
src: /path/to/vhost.conf.j2
dest: /etc/apache2/sites-available/vhost.conf
notify:
- restart apache
notify:
- restart apache
handlers:
service:
name: apache2
state: restarted
This playbook installs Apache, configures a virtual host using a template, and
enables the virtual host configuration.
yaml
---
hosts: all
become: yes
tasks:
user:
state: present
shell: /bin/
loop:
- { username: "user1" }
- { username: "user2" }
file:
path: "/home/{{ item.username }}/shared"
state: directory
mode: '0775'
loop:
- { username: "user1" }
- { username: "user2" }
This playbook creates two users (user1 and user2), and it also sets up a shared
directory for each user with appropriate permissions.
yaml
---
hosts: all
become: yes
tasks:
file:
path: "/backup"
state: directory
- name: Copy files to backup directory
copy:
src: "/path/to/important_data"
dest: "/backup/"
remote_src: yes
mode: '0644'
stat:
path: "/backup/important_data"
register: backup_status
debug:
when: backup_status.stat.exists
yaml
---
hosts: dbservers
become: yes
vars:
db_name: mydatabase
db_user: dbuser
db_password: "secret"
tasks:
apt:
name: mysql-server
state: present
service:
name: mysql
state: started
enabled: yes
- name: Create a database
mysql_db:
state: present
mysql_user:
state: present
This playbook installs MySQL, starts the MySQL service, creates a database
(mydatabase), and creates a user with privileges on the database.
yaml
---
hosts: all
become: yes
tasks:
update_cache: yes
apt:
upgrade: dist
This playbook updates the system’s package cache and performs a full system
upgrade.
yaml
---
hosts: all
become: yes
tasks:
apt:
name: ufw
state: present
rule: allow
name: 'OpenSSH'
ufw:
default: deny
direction: incoming
ufw:
default: allow
direction: outgoing
ufw:
state: enabled
This playbook installs the ufw firewall, configures firewall rules to allow SSH and
deny incoming traffic by default while allowing outgoing traffic.
---
hosts: webservers
become: yes
tasks:
apt:
name: nodejs
state: present
apt:
name: npm
state: present
copy:
src: /path/to/app/
dest: /var/www/myapp/
mode: '0755'
- name: Install dependencies
npm:
path: /var/www/myapp/
state: present
This playbook installs Node.js and npm, deploys the application files, installs
dependencies, and starts the Node.js application.
yaml
---
become: yes
vars:
app_repo: "https://github.com/username/repository.git"
app_dest: "/var/www/myapp"
tasks:
apt:
name: git
state: present
git:
clone: yes
update: yes
npm:
yaml
---
hosts: all
become: yes
tasks:
apt:
name: docker.io
state: present
- name: Start Docker service
service:
name: docker
state: started
enabled: yes
docker_image:
name: nginx
source: pull
docker_container:
name: nginx_container
image: nginx
state: started
published_ports:
- "8080:80"
This playbook installs Docker, pulls an Nginx image, and runs it in a container,
exposing port 8080 on the host machine.
14. Playbook to Set Up a Python Virtual Environment
yaml
---
hosts: all
become: yes
tasks:
apt:
name:
- python3
- python3-pip
state: present
pip:
name: virtualenv
state: present
- name: Create a virtual environment
command:
pip:
requirements: /path/to/requirements.txt
This playbook installs Python, pip, and the virtualenv package, creates a virtual
environment, and installs dependencies from a requirements.txt file.
Using Variables
Variables enhance playbook flexibility.
yaml
vars:
package_name: nginx
tasks:
- name: Install a package
apt:
state: present
yaml
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
Summary
Ansible simplifies IT automation with its agentless architecture, human-readable
Playbooks, and robust features for managing tasks across diverse environments.
Whether you’re deploying applications, configuring servers, or orchestrating
complex workflows, Ansible is a versatile solution for all.
Ansible Playbooks
yaml
---
hosts: webservers
become: yes
tasks:
- name: Install nginx package
apt:
name: nginx
state: present
In this example, the playbook installs the Nginx web server on a group of hosts
called webservers.
yaml
---
hosts: webservers
become: yes
tasks:
service:
name: nginx
state: started
enabled: yes
This playbook ensures the Nginx service is started and enabled to start on boot.
3. Playbook to Configure a File
yaml
---
hosts: webservers
become: yes
tasks:
template:
src: /path/to/nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify:
- restart nginx
handlers:
service:
name: nginx
state: restarted
This playbook copies a customized Nginx configuration file using the template
module and restarts the Nginx service if the configuration changes.
yaml
---
hosts: all
become: yes
tasks:
apt:
name:
- curl
- vim
- git
state: present
This playbook installs multiple packages (curl, vim, and git) on all specified hosts.
5. Playbook to Install Apache Web Server and Configure Virtual Host
yaml
---
hosts: webservers
become: yes
tasks:
apt:
name: apache2
state: present
template:
src: /path/to/vhost.conf.j2
dest: /etc/apache2/sites-available/vhost.conf
notify:
- restart apache
- name: Enable the virtual host
notify:
- restart apache
handlers:
service:
name: apache2
state: restarted
This playbook installs Apache, configures a virtual host using a template, and
enables the virtual host configuration.
yaml
---
hosts: all
become: yes
tasks:
- name: Create a new user
user:
state: present
shell: /bin/
loop:
- { username: "user1" }
- { username: "user2" }
file:
state: directory
mode: '0775'
loop:
- { username: "user1" }
- { username: "user2" }
This playbook creates two users (user1 and user2), and it also sets up a shared
directory for each user with appropriate permissions.
7. Playbook to Backup a Directory
yaml
---
hosts: all
become: yes
tasks:
file:
path: "/backup"
state: directory
copy:
src: "/path/to/important_data"
dest: "/backup/"
remote_src: yes
mode: '0644'
- name: Verify backup
stat:
path: "/backup/important_data"
register: backup_status
debug:
when: backup_status.stat.exists
yaml
---
hosts: dbservers
become: yes
vars:
db_name: mydatabase
db_user: dbuser
db_password: "secret"
tasks:
apt:
name: mysql-server
state: present
service:
name: mysql
state: started
enabled: yes
mysql_db:
state: present
- name: Create a user and grant privileges
mysql_user:
state: present
This playbook installs MySQL, starts the MySQL service, creates a database
(mydatabase), and creates a user with privileges on the database.
yaml
---
hosts: all
become: yes
tasks:
apt:
update_cache: yes
- name: Upgrade all packages
apt:
upgrade: dist
This playbook updates the system’s package cache and performs a full system
upgrade.
yaml
---
hosts: all
become: yes
tasks:
apt:
name: ufw
state: present
ufw:
rule: allow
name: 'OpenSSH'
ufw:
default: deny
direction: incoming
ufw:
default: allow
direction: outgoing
ufw:
state: enabled
This playbook installs the ufw firewall, configures firewall rules to allow SSH and
deny incoming traffic by default while allowing outgoing traffic.
---
hosts: webservers
become: yes
tasks:
apt:
name: nodejs
state: present
apt:
name: npm
state: present
copy:
src: /path/to/app/
dest: /var/www/myapp/
mode: '0755'
- name: Install dependencies
npm:
path: /var/www/myapp/
state: present
This playbook installs Node.js and npm, deploys the application files, installs
dependencies, and starts the Node.js application.
yaml
---
- name: Deploy a Web Application from Git
hosts: webservers
become: yes
vars:
app_repo: "https://github.com/username/repository.git"
app_dest: "/var/www/myapp"
tasks:
apt:
name: git
state: present
git:
clone: yes
update: yes
npm:
path: "{{ app_dest }}"
state: present
yaml
---
hosts: all
become: yes
tasks:
apt:
name: docker.io
state: present
- name: Start Docker service
service:
name: docker
state: started
enabled: yes
docker_image:
name: nginx
source: pull
docker_container:
name: nginx_container
image: nginx
state: started
published_ports:
- "8080:80"
This playbook installs Docker, pulls an Nginx image, and runs it in a container,
exposing port 8080 on the host machine.
14. Playbook to Set Up a Python Virtual Environment
yaml
---
hosts: all
become: yes
tasks:
apt:
name:
- python3
- python3-pip
state: present
pip:
name: virtualenv
state: present
pip:
requirements: /path/to/requirements.txt
This playbook installs Python, pip, and the virtualenv package, creates a virtual
environment, and installs dependencies from a requirements.txt file.
yaml
---
hosts: all
become: yes
tasks:
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?PermitRootLogin'
notify:
- restart ssh
ufw:
rule: allow
name: 'OpenSSH'
user:
name: "remoteuser"
state: present
shell: /bin/
lineinfile:
path: /etc/ssh/sshd_config
regexp: '^#?PasswordAuthentication'
line: 'PasswordAuthentication no'
notify:
- restart ssh
handlers:
service:
name: ssh
state: restarted
yaml
---
hosts: dbservers
become: yes
tasks:
apt:
name: redis-server
state: present
service:
name: redis-server
state: started
enabled: yes
lineinfile:
path: /etc/redis/redis.conf
notify:
- restart redis
handlers:
- name: restart redis
service:
name: redis-server
state: restarted
This playbook installs Redis, starts the service, and configures it to listen on all IP
addresses by modifying the configuration file.
yaml
---
hosts: dbservers
become: yes
tasks:
command:
args:
chdir: /tmp
environment:
MYSQL_PWD: "{{ mysql_root_password }}"
stat:
register: backup_status
debug:
when: backup_status.stat.exists
This playbook creates a backup of a MySQL database using mysqldump and stores
it in a specified backup directory. It verifies the existence of the backup file and
prints a message.
yaml
---
hosts: mailservers
become: yes
tasks:
apt:
name: postfix
state: present
lineinfile:
path: /etc/postfix/main.cf
regexp: '^#?relayhost'
notify:
- restart postfix
handlers:
service:
name: postfix
state: restarted
This playbook installs the Postfix mail server, configures it to relay emails through
a remote SMTP server, and restarts the service.
19. Playbook to Perform System Cleanup
yaml
---
hosts: all
become: yes
tasks:
apt:
autoclean: yes
apt:
autoremove: yes
file:
state: absent
loop:
- auth.log
- syslog
- dpkg.log
yaml
---
hosts: jenkins_servers
become: yes
tasks:
apt:
name: openjdk-11-jdk
state: present
state: present
apt:
name: jenkins
state: present
service:
name: jenkins
state: started
enabled: yes
This playbook installs Java, adds the Jenkins repository, installs Jenkins, and starts
the Jenkins service.
yaml
---
hosts: all
become: yes
tasks:
apt:
name: ntp
state: present
service:
name: ntp
state: started
enabled: yes
path: /etc/ntp.conf
regexp: '^server'
notify:
- restart ntp
handlers:
service:
name: ntp
state: restarted
This playbook installs the ntp package, configures the NTP server to synchronize
with an NTP source (e.g., time.nist.gov), and ensures the NTP service is running.
yaml
---
hosts: webservers
become: yes
tasks:
apt:
name: apache2
state: present
service:
name: apache2
state: started
enabled: yes
copy:
src: /local/path/to/website/
dest: /var/www/html/
owner: www-data
group: www-data
mode: '0755'
- name: Configure Apache virtual host
template:
src: /local/path/to/vhost.conf.j2
dest: /etc/apache2/sites-available/000-default.conf
notify:
- restart apache
handlers:
service:
name: apache2
state: restarted
This playbook installs Apache, starts the service, copies website files to the web
server's document root, and configures a virtual host using a template file.
yaml
---
become: yes
tasks:
apt:
name: mariadb-server
state: present
service:
name: mariadb
state: started
enabled: yes
mysql_secure_installation:
login_user: root
set_root_password: yes
remove_anonymous_users: yes
disallow_root_login_remotely: yes
remove_test_db: yes
state: present
This playbook installs MariaDB, ensures the service is running, and secures the
installation by setting the root password and disabling remote root login.
yaml
---
hosts: redis_nodes
become: yes
tasks:
apt:
name: redis-server
state: present
path: /etc/redis/redis.conf
regexp: '^#?cluster-enabled'
notify:
- restart redis
ufw:
rule: allow
port: '6379:6380'
handlers:
service:
name: redis-server
state: restarted
This playbook installs Redis, configures it for clustering, and opens the required
ports on the firewall.
25. Playbook to Install and Configure a Filebeat Agent (for Log Shipping)
yaml
---
hosts: all
become: yes
tasks:
apt:
name: filebeat
state: present
template:
src: /local/path/to/filebeat.yml.j2
dest: /etc/filebeat/filebeat.yml
notify:
- restart filebeat
name: filebeat
state: started
enabled: yes
handlers:
service:
name: filebeat
state: restarted
This playbook installs Filebeat, configures it using a template file to ship logs to a
centralized log management system, and ensures the Filebeat service is started.
yaml
---
hosts: jenkins_agents
become: yes
tasks:
- name: Install Java
apt:
name: openjdk-11-jdk
state: present
get_url:
url: "https://<jenkins-url>/jnlpJars/agent.jar"
dest: /opt/jenkins/agent.jar
async: 60
poll: 0
This playbook installs Java, downloads the Jenkins agent JAR, and runs the agent
as a background process to connect to the Jenkins master.
yaml
---
- name: Install and Configure Vault Server
hosts: vault_servers
become: yes
tasks:
apt:
name: vault
state: present
systemd:
name: vault
enabled: yes
state: started
register: vault_init
when: vault_init.rc != 0
when: vault_init.rc == 0
This playbook installs HashiCorp Vault, starts the service, and initializes and
unseals Vault on the first run.
yaml
---
hosts: kubernetes_workers
become: yes
tasks:
apt:
name:
- kubelet
- kubeadm
- kubectl
state: present
- name: Join the Kubernetes cluster
service:
name: kubelet
state: started
enabled: yes
This playbook installs the necessary Kubernetes packages on worker nodes, joins
the node to the Kubernetes cluster, and ensures the kubelet service is running.
yaml
---
hosts: swarm_masters
become: yes
tasks:
name: docker.io
state: present
This playbook configures a Docker Swarm cluster with master and worker nodes
by initializing the swarm on the master and joining worker nodes.
yaml
---
hosts: prometheus_servers
become: yes
tasks:
apt:
name: prometheus
state: present
template:
src: /local/path/to/prometheus.yml.j2
dest: /etc/prometheus/prometheus.yml
notify:
- restart prometheus
service:
name: prometheus
state: started
enabled: yes
handlers:
name: prometheus
state: restarted
This playbook installs Prometheus, configures it with a template file, and ensures
the Prometheus service is started and enabled.
yaml
---
hosts: webservers
become: yes
tasks:
apt:
name: nginx
state: present
template:
src: /local/path/to/nginx_reverse_proxy.conf.j2
dest: /etc/nginx/sites-available/default
notify:
- restart nginx
service:
name: nginx
state: started
enabled: yes
handlers:
service:
name: nginx
state: restarted
This playbook installs Nginx, configures it as a reverse proxy using a template file,
and ensures that the service is running and enabled on the system.
yaml
---
hosts: all
become: yes
tasks:
apt:
name: ufw
state: present
ufw:
rule: allow
name: OpenSSH
ufw:
rule: allow
state: enabled
default: deny
This playbook installs and configures the Uncomplicated Firewall (UFW) to allow
SSH and HTTP traffic while denying other inbound connections.
yaml
---
hosts: all
become: yes
tasks:
get_url:
url:
https://github.com/prometheus/node_exporter/releases/download/v1.3.1/node_expo
rter-1.3.1.linux-amd64.tar.gz
dest: /tmp/node_exporter.tar.gz
src: /tmp/node_exporter.tar.gz
dest: /opt/
remote_src: yes
copy:
content: |
[Unit]
After=network.target
[Service]
User=nobody
ExecStart=/opt/node_exporter-1.3.1.linux-amd64/node_exporter
[Install]
WantedBy=multi-user.target
dest: /etc/systemd/system/node_exporter.service
notify:
- reload systemd
- name: Start Node Exporter
service:
name: node_exporter
state: started
enabled: yes
handlers:
systemd:
daemon_reload: yes
This playbook installs the Prometheus Node Exporter, creates a systemd service for
it, and ensures the service is started and enabled.
yaml
---
hosts: dbservers
become: yes
tasks:
apt:
name:
- mysql-client
- cron
state: present
file:
path: /var/backups/mysql
state: directory
mode: '0755'
cron:
minute: "0"
hour: "2"
state: present
This playbook installs the MySQL client and cron service, creates a backup
directory, and sets up a cron job to back up the MySQL databases every day at 2
AM.
yaml
---
hosts: jenkins_masters
become: yes
tasks:
apt:
name: openjdk-11-jdk
state: present
apt_key:
url: https://pkg.jenkins.io/jenkins.io.key
apt:
name: jenkins
state: present
service:
name: jenkins
state: started
enabled: yes
This playbook installs Java (required by Jenkins), adds the Jenkins repository, and
installs Jenkins on the master node, ensuring the service is started and enabled.
yaml
---
become: yes
tasks:
apt:
name: openjdk-11-jdk
state: present
apt_key:
url: https://artifacts.elastic.co/GPG-KEY-elasticsearch
apt_repository:
apt:
name: elasticsearch
state: present
- name: Start Elasticsearch service
service:
name: elasticsearch
state: started
enabled: yes
yaml
---
hosts: registry_servers
become: yes
tasks:
apt:
name: docker.io
state: present
- name: Create Docker Registry directory
file:
path: /var/lib/registry
state: directory
docker_container:
name: registry
image: registry:2
state: started
ports:
- "5000:5000"
volumes:
- /var/lib/registry:/var/lib/registry
This playbook installs Docker, creates a directory for storing Docker images, and
runs the Docker Registry container.
yaml
---
- name: Install and Configure GitLab CI/CD Runner
hosts: ci_cd_servers
become: yes
tasks:
apt:
name: gitlab-runner
state: present
service:
name: gitlab-runner
state: started
enabled: yes
This playbook installs the GitLab CI/CD runner, registers it with the GitLab
instance using a registration token, and ensures the service is started.
39. Playbook to Set Up a Redis Sentinel Cluster
yaml
---
hosts: redis_sentinels
become: yes
tasks:
apt:
name: redis-server
state: present
template:
src: /local/path/to/sentinel.conf.j2
dest: /etc/redis/sentinel.conf
notify:
name: redis-sentinel
state: started
enabled: yes
handlers:
service:
name: redis-sentinel
state: restarted
This playbook installs Redis and sets up Redis Sentinel to provide high availability
and failover for a Redis cluster.
yaml
---
hosts: master_nodes
become: yes
tasks:
- name: Deploy Kubernetes Dashboard
kubernetes:
name: kubernetes-dashboard
state: present
api_version: apps/v1
kind: Deployment
namespace: kube-system
definition:
apiVersion: apps/v1
kind: Deployment
metadata:
name: kubernetes-dashboard
namespace: kube-system
spec:
replicas: 1
selector:
matchLabels:
k8s-app: kubernetes-dashboard
template:
metadata:
labels:
k8s-app: kubernetes-dashboard
spec:
containers:
- name: kubernetes-dashboard
image: kubernetesui/dashboard:v2.0.0
ports:
- containerPort: 9090
yaml
---
hosts: all
become: yes
tasks:
apt:
update_cache: yes
name:
- apt-transport-https
- ca-certificates
- curl
- software-properties-common
state: present
apt_key:
url: https://download.docker.com/linux/ubuntu/gpg
apt_repository:
apt:
name: docker-ce
state: present
- name: Start and enable Docker service
service:
name: docker
state: started
enabled: yes
This playbook installs Docker on an Ubuntu machine, adds the official Docker
repository, and ensures the service is started and enabled.
yaml
---
hosts: all
become: yes
tasks:
apt:
name: ntp
state: present
- name: Start and enable NTP service
service:
name: ntp
state: started
enabled: yes
lineinfile:
path: /etc/ntp.conf
regexp: '^server'
notify:
- restart ntp
handlers:
service:
name: ntp
state: restarted
This playbook installs the NTP service, configures a specific NTP server, and
ensures the service is running and enabled.
43. Playbook to Install and Configure MySQL Server
yaml
---
hosts: dbservers
become: yes
tasks:
apt:
name: mysql-server
state: present
service:
name: mysql
state: started
enabled: yes
name: example_db
state: present
mysql_user:
name: example_user
state: present
priv: "example_db.*:ALL"
This playbook installs MySQL, creates a new database and user, and grants the
necessary privileges.
yaml
---
hosts: kafka_nodes
become: yes
tasks:
name: openjdk-11-jdk
state: present
get_url:
url: https://downloads.apache.org/kafka/2.8.0/kafka_2.13-2.8.0.tgz
dest: /tmp/kafka.tgz
unarchive:
src: /tmp/kafka.tgz
dest: /opt/
remote_src: yes
copy:
content: |
[Unit]
Description=Apache Kafka
After=network.target
[Service]
User=nobody
ExecStart=/opt/kafka_2.13-2.8.0/bin/kafka-server-start.sh
/opt/kafka_2.13-2.8.0/config/server.properties
[Install]
WantedBy=multi-user.target
dest: /etc/systemd/system/kafka.service
notify:
- reload systemd
service:
name: kafka
state: started
enabled: yes
handlers:
systemd:
daemon_reload: yes
This playbook installs Apache Kafka, configures a systemd service for it, and
ensures the service is running.
yaml
---
hosts: localhost
gather_facts: no
tasks:
ec2_instance:
instance_type: t2.micro
image_id: ami-0c55b159cbfafe1f0
wait: yes
count: 1
instance_tags:
Name: "MyEC2Instance"
assign_public_ip: yes
register: ec2_instances
debug:
var: ec2_instances.instances
This playbook launches an EC2 instance in AWS, waits for it to be ready, and
outputs the instance details.
yaml
---
hosts: all
become: yes
tasks:
name: elasticsearch
state: present
service:
name: elasticsearch
state: started
enabled: yes
apt:
name: kibana
state: present
service:
name: kibana
state: started
enabled: yes
This playbook installs and starts both Elasticsearch and Kibana services on the
server.
47. Playbook to Install and Configure Nginx as a Load Balancer
yaml
---
hosts: load_balancer
become: yes
tasks:
apt:
name: nginx
state: present
template:
src: /local/path/to/nginx_load_balancer.conf.j2
dest: /etc/nginx/nginx.conf
notify:
- restart nginx
- name: Start Nginx service
service:
name: nginx
state: started
enabled: yes
handlers:
service:
name: nginx
state: restarted
This playbook installs Nginx and configures it as a load balancer using a template
file for the configuration.
yaml
---
hosts: all
become: yes
tasks:
apt:
name: redis-server
state: present
service:
name: redis-server
state: started
enabled: yes
lineinfile:
path: /etc/redis/redis.conf
notify:
- restart redis
handlers:
- name: restart redis
service:
name: redis-server
state: restarted
This playbook installs Redis, configures it to listen on all IPs, and ensures the
service is running.
yaml
---
hosts: all
become: yes
tasks:
apt:
name: prometheus
state: present
- name: Ensure Prometheus is started
service:
name: prometheus
state: started
enabled: yes
yaml
---
hosts: swarm_masters
become: yes
tasks:
Ansible Project
LAMP Stack Setup and Web Application
Deployment with Ansible
This Ansible project demonstrates automating the setup of a LAMP stack (Linux,
Apache, MySQL, PHP) and deploying a simple PHP-based web application. The
tasks are modularized into separate playbooks, ensuring clarity and flexibility for
managing each stack component.
Project Overview
● Goal: Automate the installation of a LAMP stack and deployment of a
PHP-based web application.
● Technologies: Ansible, Apache, MySQL, PHP.
● Environment: Ubuntu 20.04 (can be adapted for other distributions).
Project Structure
graphql
lamp_project/
├── ansible/
│ └── files/
├── README.md
└── playbooks/
Configuration Files
ini
[web_servers]
webserver1 ansible_host=192.168.1.10
webserver2 ansible_host=192.168.1.11
[db_servers]
dbserver1 ansible_host=192.168.1.20
yaml
apache_package: apache2
mysql_root_password: "rootpassword"
php_packages:
- php
- libapache2-mod-php
- php-mysql
webapp_name: "myapp"
Playbooks
yaml
---
hosts: web_servers
become: yes
tasks:
apt:
state: present
service:
name: apache2
state: started
enabled: yes
yaml
---
hosts: web_servers
become: yes
tasks:
apt:
state: present
service:
name: apache2
state: restarted
yaml
---
hosts: db_servers
become: yes
tasks:
apt:
name: mysql-server
state: present
- name: Set MySQL root password
mysql_user:
name: root
host: "localhost"
state: present
service:
name: mysql
state: started
enabled: yes
yaml
---
become: yes
tasks:
copy:
src: files/index.php
dest: /var/www/html/index.php
file:
path: /var/www/html/index.php
owner: www-data
group: www-data
mode: '0644'
service:
name: apache2
state: restarted
yaml
---
hosts: all
become: yes
tasks:
import_playbook: playbooks/install_apache.yml
import_playbook: playbooks/install_php.yml
import_playbook: playbooks/install_mysql.yml
- name: Deploy PHP application
import_playbook: playbooks/deploy_application.yml
php
<?php
?>
ansible-playbook -i ansible/inventory.ini
ansible/lamp_playbook.yml
Summary
This project simplifies LAMP stack deployment using Ansible. The modular
design allows you to extend or customize components, such as adding virtual hosts,
configuring advanced MySQL settings, or deploying a more complex web
application.
Basic Questions
What is Ansible, and why is it used?
Ansible is an open-source automation tool used for configuration management,
application deployment, and task automation. It uses YAML-based Playbooks and
operates without agents, connecting to managed nodes via SSH or WinRM.
yaml
tasks:
template:
src: config.j2
dest: /etc/myapp/config
handlers:
service:
name: myapp
state: restarted
What is a Dynamic Inventory?
Dynamic Inventory retrieves host information from external sources at runtime
(e.g., AWS, Azure). It’s defined by custom scripts or plugins.
What is gather_facts?
gather_facts collects system information about managed nodes (e.g., OS, IP). It's
enabled by default but can be turned off:
yaml
gather_facts: no
yaml
tasks:
apt:
with_items:
- nginx
- git
dependencies:
- role: common
- role: webserver
Advanced Questions
yaml
tasks:
command: uptime
delegate_to: 192.168.1.100
yaml
tasks:
- name: Retrieve file content
debug:
yaml
tasks:
- debug:
var: my_variable
yaml
tasks:
- block:
command: /bin/true
rescue:
debug:
always:
- name: Cleanup
debug:
Scenario-Based Questions
yaml
tasks:
apt:
name: nginx=1.18.0
state: present
apt:
name: nginx
state: absent
Scenario: How do you manage different environments like dev, staging, and
production?
yaml
tasks:
copy:
dest: /tmp/example.txt
owner: root
group: root
mode: '0644'
yaml
tasks:
- debug:
Advanced Questions
yaml
tasks:
- debug:
yaml
tasks:
command: df -h
register: disk_space
- debug:
var: disk_space.stdout
yaml
tasks:
name: nginx
state: present
become: yes
Scenario-Based Questions
yaml
- hosts: webservers
tasks:
apt:
name: apache2
state: present
service:
name: apache2
state: started
enabled: yes
Scenario: Copy a file to multiple hosts only if it doesn’t already exist.
yaml
tasks:
copy:
src: /local/path/to/file
dest: /remote/path/to/file
remote_src: yes
creates: /remote/path/to/file
yaml
tasks:
uri:
url: http://localhost:8080/health
status_code: 200
register: health_check
Troubleshooting Questions
{{ variable_name | default('default_value') }}
●
● Set DEFAULT_UNDEFINED_VAR_BEHAVIOR in ansible.cfg.
Miscellaneous Questions