Loading...
Devops

Ansible Phase 1

Ansible Definition
Ansible is a powerful, open-source automation tool designed to streamline IT tasks such as configuration management, application deployment, and orchestration. Its core strengths are its simplicity, scalability, and ease of use. Automation tasks in Ansible are defined using human-readable YAML files called Playbooks.

Key Features of Ansible

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.

Benefits of Using Ansible
● Automates repetitive IT tasks, saving time and effort.
● Reduces human error in configuration and system setup.
● Supports multiple operating systems and environments.
● Simple to learn, making it accessible even for teams new to automation.

Installation Steps

Ubuntu

sudo apt update
sudo apt install ansible

CentOS/RHEL

sudo yum install epel-release
sudo yum install ansible -y

macOS (using Homebrew)

brew install ansible

Practical Setup: Example with AWS EC2
Step 1: Launch EC2 Instances
● Create 4 EC2 instances:
○ 1 Master server (Ansible control node)
○ 2 Web servers
○ 1 Database server

Step 2: Install Ansible on the Master Server
SSH into the Master server:
ssh -i <key.pem> ubuntu@<server_ip>

Update packages and install Python:

sudo apt update
sudo apt install python3 python3-pip -y
sudo apt install ansible -y

Configure SSH Key Authentication
Generate SSH Keys on the Master Server

ssh-keygen

Copy the Public Key to Managed Nodes
cat ~/.ssh/id_rsa.pub
ssh-copy-id -i ~/.ssh/id_rsa.pub ubuntu@<target_ip>
Verify passwordless login:
ssh ubuntu@<target_ip>
Create Inventory and Test Connectivity
Inventory File Example
ini
[web_servers]
192.168.1.101
192.168.1.102
[db_server]
192.168.1.103

Test Connectivity
ansible all -i inventory -m ping

Writing and Running Playbooks
Example: Install and Start Nginx
yaml

– name: Install and configure Nginx
hosts: web_servers
become: yes
tasks:
– name: Install Nginx
apt:
name: nginx

state: present
– name: Start Nginx
service:
name: nginx
state: started

Playbooks Example

1. Simple Playbook to Install a Package
yaml

– name: Install Nginx web server
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.

2. Playbook to Start and Enable a Service
yaml

– name: Ensure Nginx is running
hosts: webservers
become: yes
tasks:
– name: Start Nginx service
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

– name: Configure Nginx
hosts: webservers
become: yes
tasks:
– name: Copy the Nginx configuration file
template:
src: /path/to/nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify:
– restart nginx
handlers:
– name: restart nginx
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.

4. Playbook to Install Multiple Packages
yaml


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

– name: Install Apache Web Server and Configure Virtual Host
hosts: webservers
become: yes
tasks:
– name: Install Apache
apt:
name: apache2
state: present
– name: Copy virtual host configuration file
template:
src: /path/to/vhost.conf.j2
dest: /etc/apache2/sites-available/vhost.conf
notify:
– restart apache
– name: Enable the virtual host
command: a2ensite vhost.conf
notify:
– restart apache
handlers:
– name: restart apache
service:
name: apache2

state: restarted

This playbook installs Apache, configures a virtual host using a template, and enables the virtual host configuration.

6. Playbook to Create Users and Set Permissions
yaml

– name: Create Users and Set Permissions
hosts: all
become: yes
tasks:
– name: Create a new user
user:
name: “{{ item.username }}”
state: present
shell: /bin/
loop:
– { username: “user1” }
– { username: “user2” }

– name: Create directory and set permissions
file:
path: “/home/{{ item.username }}/shared”
state: directory
mode: ‘0775’
owner: “{{ item.username }}”
group: “{{ item.username }}”
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

– name: Backup Directory
hosts: all
become: yes
tasks:
– name: Create backup directory
file:
path: “/backup”
state: directory
– name: Copy files to backup 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
– name: Display backup status
debug:
msg: “Backup created successfully”
when: backup_status.stat.exists

This playbook creates a backup of a directory (/path/to/important_data) to a /backup folder and verifies the backup.

8. Playbook to Set Up a MySQL Database
yaml

– name: Set up MySQL Database and User
hosts: dbservers
become: yes
vars:
db_name: mydatabase
db_user: dbuser
db_password: “secret”
tasks:
– name: Install MySQL server
apt:
name: mysql-server
state: present

– name: Start MySQL service
service:
name: mysql
state: started
enabled: yes
– name: Create a database
mysql_db:
name: “{{ db_name }}”
state: present

– name: Create a user and grant privileges
mysql_user:
name: “{{ db_user }}”
password: “{{ db_password }}”
priv: “{{ db_name }}.*:ALL”
state: present

This playbook installs MySQL, starts the MySQL service, creates a database (mydatabase), and creates a user with privileges on the database.

9. Playbook to Update System Packages
yaml

– name: Update System Packages
hosts: all
become: yes
tasks:
– name: Update apt cache
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.

10. Playbook to Manage a Firewall
yaml

– name: Manage Firewall Rules
hosts: all
become: yes
tasks:
– name: Ensure ufw is installed
apt:
name: ufw
state: present

– name: Allow SSH through firewall
ufw:
rule: allow
name: ‘OpenSSH’
– name: Deny all incoming traffic
ufw:
default: deny
direction: incoming
– name: Allow outgoing traffic
ufw:
default: allow
direction: outgoing
– name: Enable the firewall
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.

11. Playbook to Set Up a Node.js Application

yaml

– name: Set up Node.js Application
hosts: webservers
become: yes
tasks:
– name: Install Node.js
apt:
name: nodejs
state: present

– name: Install npm
apt:
name: npm
state: present

– name: Deploy application files
copy:
src: /path/to/app/
dest: /var/www/myapp/
mode: ‘0755’

– name: Install dependencies
npm:
path: /var/www/myapp/
state: present

– name: Start the application
shell: nohup node /var/www/myapp/app.js &
This playbook installs Node.js and npm, deploys the application files, installs dependencies, and starts the Node.js application.

Advanced Features in Playbooks:
● Conditionals: Run tasks based on specific conditions, using when.
● Loops: Repeat tasks using loop.
● Includes and Imports: Organize playbooks using include or import to reuse common tasks.
● Templates: Use Jinja2 templates to dynamically generate configuration files.

12. Playbook to Deploy a Web Application (Using Git)
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:
– name: Ensure git is installed
apt:
name: git
state: present

– name: Clone the web application from GitHub
git:
repo: “{{ app_repo }}”
dest: “{{ app_dest }}”
clone: yes
update: yes
– name: Install dependencies using npm
npm:
path: “{{ app_dest }}”

state: present

– name: Start the web application
shell: nohup node {{ app_dest }}/app.js &

This playbook clones a web application from a Git repository, installs dependencies using npm, and starts the application.

13. Playbook to Install Docker and Run a Container
yaml

– name: Install Docker and Run a Container
hosts: all
become: yes
tasks:
– name: Install Docker
apt:
name: docker.io
state: present

– name: Start Docker service
service:
name: docker
state: started
enabled: yes

– name: Pull the Docker image
docker_image:
name: nginx
source: pull

– name: Run the Docker container
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

– name: Set up Python Virtual Environment
hosts: all
become: yes
tasks:
– name: Install python3 and pip
apt:
name:
– python3
– python3-pip
state: present

– name: Install virtualenv package
pip:
name: virtualenv
state: present

– name: Create a virtual environment
command:
cmd: python3 -m venv /home/{{ ansible_user }}/myenv
creates: /home/{{ ansible_user }}/myenv
– name: Install dependencies in the virtual environment
pip:
requirements: /path/to/requirements.txt
virtualenv: /home/{{ ansible_user }}/myenv
This playbook installs Python, pip, and the virtualenv package, creates a virtual
environment, and installs dependencies from a requirements.txt file.

ansible-playbook -i inventory playbook.yml

Advanced Ansible Features
Using Variables
Variables enhance playbook flexibility.
yaml

vars:
package_name: nginx
tasks:

– name: Install a package
apt:
name: “{{ package_name }}”
state: present

Templates with Jinja2
Use templates for dynamic configurations.
yaml

– name: Apply Nginx configuration
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf

Handlers for Notifications
Trigger actions like service restarts when configurations change.

Roles for Reusability

Organize tasks into reusable roles using:
ansible-galaxy init <role_name>

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.

Basic Structure of a Playbook
A typical Ansible playbook contains:
● Hosts: Specifies the target systems (can be a group or individual machine).
● Tasks: Defines the actions to be performed, such as installing a package, copying files, or restarting services.
● Variables: Used to manage configurations dynamically.
● Handlers: Special tasks that are triggered only when notified by other tasks (e.g., restart a service if a configuration file is changed).

Leave a Reply

Your email address will not be published. Required fields are marked *