+92 345 2180748     info@hysec.com.pk
Hysec - AWS Documentation
DevOps Job Ready Program

Learn • Practice • Get Hired

Ansible Installation Guide

1. Introduction

Ansible Installation involves setting up an Ansible Control Node that will manage remote servers (Managed Nodes) using SSH.

Ansible requires: Python, SSH connectivity, Inventory configuration, and User authentication.

HYSEC Image
Architecture:
Ansible Control Node
        |
        | SSH
-----------------------------
|         |         |
Web Server  DB Server  App Server
Managed    Managed    Managed
Node       Node       Node

2. System Requirements

Control Node Requirements:

ComponentRequirement
Operating SystemUbuntu 20.04/22.04/24.04
CPU2 Core
RAM2 GB+
PythonPython 3.x
NetworkSSH Access

Managed Node Requirements: Linux Server, SSH service enabled, Python installed, User with sudo access.

3. Install Ansible on Ubuntu

Step 1: Update System Packages

sudo apt update && sudo apt upgrade -y

Step 2: Install Required Packages

sudo apt install software-properties-common -y

Step 3: Add Ansible Repository

sudo add-apt-repository --yes --update ppa:ansible/ansible

Step 4: Install Ansible

sudo apt install ansible -y

Step 5: Verify Installation

ansible --version

4. Install Ansible on RHEL / CentOS / Rocky Linux

sudo dnf update -y
sudo dnf install epel-release -y
sudo dnf install ansible -y
ansible --version

5. Ansible Configuration Files

Main directory: /etc/ansible/

Main Configuration File: /etc/ansible/ansible.cfg

Inventory File: /etc/ansible/hosts

[webservers]
web01 ansible_host=192.168.1.10
web02 ansible_host=192.168.1.11

[database]
db01 ansible_host=192.168.1.20

6. Configure SSH Authentication

Generate SSH Key: ssh-keygen

Copy SSH Key: ssh-copy-id username@server-ip

Test Connection: ssh ubuntu@192.168.1.10

7. Configure Ansible Inventory

sudo nano /etc/ansible/hosts
[web]
192.168.1.10
192.168.1.11

[database]
192.168.1.20

8. Test Ansible Connection

ansible all -m ping

9. Run First Ansible Command

ansible all -m shell -a "uptime"

10. Configure Ansible User

[webservers]
web01 ansible_user=ubuntu
web02 ansible_user=ubuntu

11. Install Ansible Using Python (pip)

sudo apt install python3-pip -y
pip3 install ansible
ansible --version
pip install ansible-navigator
ansible-navigator --version

13. Ansible Directory Structure

ansible-project/
├── inventory/
│   └── hosts
├── playbooks/
│   └── webserver.yml
├── roles/
├── group_vars/
├── host_vars/
└── ansible.cfg

14. Configure ansible.cfg

[defaults]
inventory = ./inventory/hosts
remote_user = ubuntu
host_key_checking = False

15. Common Ansible Commands

HYSEC Image

16. Troubleshooting Installation

17. Ansible Installation in DevOps Environment

Developer -> GitHub -> Jenkins CI/CD -> Ansible Controller -> (AWS, Docker, Kubernetes)

Summary

Ansible installation involves: Installing Ansible on Control Node, Configuring Inventory, Setting up SSH Authentication, Testing Managed Nodes, and Creating Automation Playbooks.

Ansible Inventory Management

What is Ansible Inventory?

Ansible Inventory is a file that contains information about the servers, network devices, and cloud resources that Ansible manages.

It defines:

The inventory tells Ansible "which machines to automate and how to connect with them."

Ansible Inventory Architecture

                Ansible Controller
                        |
                        |
                 Inventory File
                        |
        --------------------------------
        |               |              |
    Web Servers     Database      Application
                     Servers        Servers

Default Inventory Location: /etc/ansible/hosts
Check inventory: ansible-inventory --list

Types of Ansible Inventory

Ansible supports two main inventory types:

1. Static Inventory

Static inventory is a manually maintained file containing server details. Supported formats: INI, YAML.

INI Inventory Example:

[webservers]
web01 ansible_host=192.168.1.10
web02 ansible_host=192.168.1.11

[databases]
db01 ansible_host=192.168.1.20

Run command: ansible webservers -m ping

YAML Inventory Example:

all:
  children:
    webservers:
      hosts:
        web01:
          ansible_host: 192.168.1.10
        web02:
          ansible_host: 192.168.1.11
    databases:
      hosts:
        db01:
          ansible_host: 192.168.1.20

Inventory Groups

Groups organize servers based on their role.

[production]
web01
web02

[testing]
test01
test02

Parent and Child Groups

Large environments use nested groups.

[webservers]
web01
web02

[databases]
db01
db02

[production:children]
webservers
databases

Variables

Host Variables: Define specific settings for individual servers.
Example: [webservers] web01 ansible_host=10.0.0.10 http_port=80

Group Variables: Variables applied to a complete group.
Example: [webservers:vars] ansible_user=ubuntu environment=production

Connection Variables

Using Custom Inventory File

Create: production.ini
Run: ansible all -i production.ini -m ping

Inventory Commands

List All Hosts: ansible all --list-hosts

Show Inventory Details: ansible-inventory --list

Graph Inventory Structure: ansible-inventory --graph

2. Dynamic Inventory

What is Dynamic Inventory? Automatically retrieves server information from external sources (AWS EC2, Azure, Google Cloud, Kubernetes, VMware).

AWS Dynamic Inventory Example

Install AWS collection: ansible-galaxy collection install amazon.aws
Configuration File: aws_ec2.yml

plugin: amazon.aws.aws_ec2
regions:
  - us-east-1
filters:
  instance-state-name:
    - running

Run: ansible-inventory -i aws_ec2.yml --list

Inventory Variables Directory

For enterprise projects:

inventory/
├── hosts
├── group_vars/
│     └── webservers.yml
└── host_vars/
      └── web01.yml

Inventory with Jenkins CI/CD

Example Jenkins command: ansible-playbook -i production.ini deploy.yml

Inventory Best Practices

  1. Use Groups: Organize servers (web, database, application, monitoring).
  2. Separate Environments: inventory/development, inventory/testing, inventory/production.
  3. Do Not Store Passwords: Avoid plain text; use Ansible Vault or SSH Keys.
  4. Use Descriptive Names: Use prod-web-01 instead of server1.
  5. Maintain Inventory in Git: Keep inventory, playbooks, and roles in one repository.

Inventory Troubleshooting

Summary

Ansible Inventory Management is the foundation of Ansible automation. It defines the infrastructure that Ansible controls. Key concepts: Static Inventory, Dynamic Inventory, Host Groups, Host Variables, Group Variables, AWS Cloud Inventory, Inventory Organization, and Jenkins Integration. A well-designed inventory enables scalable automation across hundreds or thousands of servers in a DevOps environment.

Ansible Ad-Hoc Commands?

What are Ansible Ad-Hoc Commands?

Ad-Hoc commands are quick, one-time tasks executed via the CLI without creating a playbook. Ideal for checking status, restarting services, or managing packages on the fly.

Syntax & Architecture

Command: ansible <host-pattern> -m <module> -a "<arguments>"

Administrator -> Ansible Command -> Control Node -> SSH -> [Server-01, Server-02, Server-03]

Connectivity & Host Info

Execute Linux Commands

Use the shell module for deep system checks:

Package Management

Service Management

Manage services using the service module:

# Restart Service
ansible webservers -m service -a "name=nginx state=restarted" -b

File & User Management

System Information

The setup module gathers all facts about a host:

ansible web01 -m setup | grep hostname

Real-World DevOps Usage

Used heavily in Jenkins pipelines for quick health checks or restarts:

ansible production -m shell -a "systemctl restart application"

Ad-Hoc Commands vs Playbooks

FeatureAd-HocPlaybooks
ExecutionQuick TaskComplex Automation
StorageNone (CLI)Git (YAML)
UsageOne-timeRepeatable

Best Practices

Summary

Ad-Hoc commands are the fastest way to manage infrastructure. Master the ping, shell, apt/yum, service, and setup modules to become efficient in Ansible.

Ansible Playbooks

What is an Ansible Playbook?

An Ansible Playbook is a YAML-based automation file that defines a series of tasks to configure, deploy, and manage servers automatically.

Playbooks are used for: Software installation, Server configuration, Application deployment, User management, Security hardening, and Cloud infrastructure automation.

Unlike Ad-Hoc Commands, Playbooks are repeatable, reusable, and suitable for production automation.

Ansible Playbook Architecture

    Developer / Admin
           |
           ↓
    Ansible Playbook (YAML File)
           |
           ↓
    Ansible Controller
           |
          SSH
    --------------------------------
    |              |               |
    Web Server     Database        Application
                   Server          Server

Playbook Basic Structure

A Playbook contains: Play, Hosts, Variables, Tasks, Handlers, and Roles.

Simple Playbook Example (install-nginx.yml)

---
- name: Install Nginx Server
  hosts: webservers
  become: yes
  tasks:
    - name: Install nginx package
      apt:
        name: nginx
        state: present
    

Run: ansible-playbook install-nginx.yml

Playbook Components

  1. Name: Defines the purpose of the playbook.
  2. Hosts: Defines target servers (e.g., [webservers] in inventory).
  3. Become: Used for privilege escalation (sudo).
  4. Tasks: Define the actions Ansible performs.
  5. Modules: apt (packages), yum (RPMs), service (manage services), copy (files), file (manage files), user (management), template (configs), git (ops), docker (containers).

Practical Examples

Variables & Logic

Variables: Store reusable values (e.g., package_name: nginx). Use {{ variable_name }} to call them.

Register Variables: Store command output (e.g., df -h result) and use debug to print it.

Conditional Execution: Use when (e.g., ansible_os_family == "Debian").

Loops: Run same task multiple times for different items (nginx, git, docker).

Handlers, Templates & Tags

Handlers: Run only when changes happen (e.g., 'Restart nginx').

Templates: Use Jinja2 variables (e.g., listen {{ port }};) in .j2 files.

Tags: Allow running specific tasks (e.g., --tags web).

Ansible Roles & Vault

Roles: Organize projects into tasks, handlers, templates, files, and vars folders. Initialize with: ansible-galaxy role init nginx.

Ansible Vault: Encrypt sensitive data (Passwords, API keys). Use ansible-vault create and --ask-vault-pass.

CI/CD & Deployment

Jenkins CI/CD Architecture: Developer → GitHub → Jenkins Pipeline → Ansible Playbook → Production Servers.

Real-World Project Structure: Separate inventory/, playbooks/, roles/, group_vars/, and ansible.cfg.

Best Practices

Summary

Ansible Playbooks enable Infrastructure as Code (IaC). Key concepts: YAML, Tasks, Modules, Variables, Conditions, Loops, Handlers, Templates, Roles, Vault, and Jenkins integration. They are the backbone of scalable, reliable, and repeatable DevOps automation.

Ansible Variables & Templates

Introduction:

In Ansible automation, Variables and Templates are used to make playbooks flexible, reusable, and dynamic. Variables store changing values such as IP addresses, package names, ports, and usernames, while Templates create dynamic configuration files using Jinja2 expressions.

Ansible Variables

Variables are values that change based on environment, configuration, or user requirements. Example: username: admin, app_port: 8080.

Variable Syntax

Ansible variables use standard YAML format. Example usage in tasks:

    - name: Install Application
      apt:
        name: "{{ app_name }}"
        state: present

Types of Ansible Variables

Variable Priority: Command line > Playbook > Inventory > Group > Role variables.

Ansible Facts as Variables

Ansible automatically collects system information (OS, IP, Memory, Hostname). Access them via ansible_hostname or ansible_os_family.

Variables Logic

Ansible Templates

Templates process dynamic configuration files using the Jinja2 engine. They are essential for dynamic server configurations (Nginx, Database configs, Application properties).

Template Architecture

    Template File (nginx.conf.j2)
              |
      Ansible Template Module
              |
    Dynamic Configuration File
              |
        Target Server

Jinja2 Syntax & Usage

Syntax: Use {{ variable_name }} for values.

Control Flow: Use {% if %} for conditions and {% for %} for loops within templates.

Template Module Example:

    - name: Deploy nginx config
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Restart nginx

CI/CD & Best Practices

In CI/CD, pass environment variables via -e. Maintain variables in group_vars and host_vars for better organization.

Best Practices:

Summary

Ansible Variables provide flexibility by storing reusable values, and Templates generate dynamic configuration files. Key concepts include Playbook/Inventory/Group/Host variables, Facts, Jinja2 syntax, and Template modules. Together, they are essential for building scalable DevOps automation.

Ansible Roles

What are Ansible Roles?

Ansible Roles are a way to organize Ansible automation into reusable, modular components. Roles allow DevOps engineers to divide large playbooks into smaller, manageable sections containing Tasks, Variables, Handlers, Templates, Files, Modules, and Default settings. Roles make Ansible projects easier to maintain, reuse, and scale.

Why Use Ansible Roles?

Without roles: A large-playbook.yml becomes difficult to maintain, hard to reuse, and difficult to debug.

With roles: An Ansible Project contains separate folders for nginx, mysql, docker, and application roles. Benefits include code reuse, better organization, easier testing, team collaboration, and enterprise automation.

Ansible Role Architecture

    Ansible Playbook
           |
           ↓
     Ansible Roles
    ---------------------------------
    |       |        |        |
    Nginx  MySQL  Docker    App
    |
    ↓
    Tasks + Templates + Variables + Handlers

Ansible Role Directory Structure

A standard role structure includes folders like defaults/, vars/, tasks/, handlers/, templates/, files/, meta/, and a README.md file.

Role Directory Explanation

Creating an Ansible Role

Use the command: ansible-galaxy role init nginx. This creates the folder structure automatically.

Example: Creating Nginx Role

Step 1: Init role. Step 2: Configure tasks/main.yml. Step 3: Create handlers in handlers/main.yml. Step 4: Create templates in templates/nginx.conf.j2.

Using Role in Playbook

Include roles in your playbook like this:

    roles:
      - nginx
      - mysql
      - docker

You can also define role dependencies in meta/main.yml.

Ansible Galaxy Roles

Ansible Galaxy is a repository where users share reusable roles. You can search with ansible-galaxy search nginx and install with ansible-galaxy install geerlingguy.nginx.

Role with Jenkins CI/CD

The architecture flows from Developer → GitHub → Jenkins Pipeline → Ansible Playbook → Ansible Roles → Production Servers.

Best Practices for Roles

Roles vs Playbooks

RolesPlaybooks
Reusable componentsAutomation workflow
Modular structureExecutes roles/tasks
Stored in roles directoryYAML automation file
Used by multiple projectsDefines deployment process

Summary

Ansible Roles provide a structured approach to building enterprise-level automation. Key concepts: Role structure, Tasks, Handlers, Templates, Variables, Files, Dependencies, Ansible Galaxy, and Jenkins CI/CD Integration. Roles are essential for creating scalable and maintainable DevOps automation frameworks.

Ansible Vault

What is Ansible Vault?

Ansible Vault is a built-in security feature of Ansible used to encrypt sensitive information such as passwords, API keys, SSH private keys, certificates, and cloud credentials.

Instead of storing secrets in plain text, Ansible Vault encrypts them using AES-256 encryption, ensuring only authorized users can access the data.

Why Use Ansible Vault?

Without Ansible Vault:

db_username: admin
db_password: MySecretPassword123
aws_access_key: AKIA...

Problems:

With Ansible Vault:

$ANSIBLE_VAULT;1.1;AES256
633635346236383238396336...

Benefits:

Ansible Vault Architecture

               Administrator
                     |
                     ↓
           ansible-vault encrypt
                     |
                     ↓
             Encrypted File
                     |
                     ↓
           Git Repository (Safe)
                     |
                     ↓
         ansible-playbook --ask-vault-pass
                     |
                     ↓
             Managed Servers

Common Ansible Vault Commands

Command Purpose
ansible-vault create file.yml Create a new encrypted file
ansible-vault encrypt file.yml Encrypt an existing file
ansible-vault decrypt file.yml Decrypt a file
ansible-vault edit file.yml Edit an encrypted file
ansible-vault view file.yml View encrypted file contents
ansible-vault rekey file.yml Change the vault password

Creating an Encrypted File

Create a new encrypted file:

ansible-vault create secrets.yml

You will be prompted to enter a vault password twice.

Example content:

db_username: admin
db_password: StrongPassword123

After saving, the file is encrypted automatically.

Encrypt an Existing File

Suppose you have:

aws_access_key: AKIAxxxxxxxx
aws_secret_key: xxxxxxxxxxxxxx

Encrypt it:

ansible-vault encrypt aws-secrets.yml

View an Encrypted File

ansible-vault view secrets.yml

You must enter the vault password to see the contents.

Edit an Encrypted File

ansible-vault edit secrets.yml

Ansible decrypts the file temporarily, opens it in your editor, and encrypts it again when you save.

Decrypt a File

ansible-vault decrypt secrets.yml

Note: This permanently removes encryption from the file. Use this command carefully.

Change the Vault Password

ansible-vault rekey secrets.yml

You'll enter the old password and then specify a new one.

Using Vault in a Playbook

Step 1: Create an Encrypted Variables File

db_username: admin
db_password: StrongPassword123

Encrypt it:

ansible-vault encrypt secrets.yml

Step 2: Reference the File

---
- name: Configure Database
  hosts: database
  vars_files:
    - secrets.yml
  tasks:
    - name: Display Username
      debug:
        msg: "{{ db_username }}"

Step 3: Run the Playbook

Prompt for the vault password:

ansible-playbook database.yml --ask-vault-pass

Using a Vault Password File

Instead of entering the password each time:

Create a password file: vault-password.txt

Contents:

MyVaultPassword

Run:

ansible-playbook site.yml \
 --vault-password-file vault-password.txt

Important: Protect this password file with strict file permissions and avoid committing it to source control.

Encrypt Individual Variables

You can encrypt only specific values.

Generate an encrypted string:

ansible-vault encrypt_string 'StrongPassword123' --name 'db_password'

Example output:

db_password: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          616263643435...

Use it directly in your playbook or variable file.

Example Project Structure

ansible-project/
├── inventory/
│  └── production.ini
│
├── playbooks/
│  └── deploy.yml
│
├── group_vars/
│  └── all.yml
│
├── secrets.yml   (Encrypted)
│
└── ansible.cfg

Vault with Jenkins CI/CD

Developer
    |
    ↓
GitHub
    |
    ↓
Jenkins Pipeline
    |
    ↓
Ansible Playbook
    |
    ↓
Encrypted Vault Secrets
    |
    ↓
Production Servers

Example Jenkins stage:

stage('Deploy') {
   steps {
       sh '''
       ansible-playbook deploy.yml \
       --vault-password-file vault-password.txt
       '''
   }
}

In production, store the vault password securely using your CI/CD platform's secret management (for example, Jenkins Credentials) rather than committing a password file to your repository.

Best Practices

Ansible Vault vs Plain Text

Plain Text Ansible Vault
Secrets visible Secrets encrypted
Unsafe in Git Safe to store in Git
No encryption AES-256 encryption
High security risk Strong protection for sensitive data

Summary

Ansible Vault is Ansible's built-in secret management solution that helps protect confidential information in automation projects.

Key Concepts

Using Ansible Vault is a security best practice for any production-grade DevOps automation workflow.

Automated Configuration Management with Ansible

Introduction

Automated Configuration Management is the process of automatically installing, configuring, updating, and maintaining servers, applications, and infrastructure using code. With Ansible, configuration management is performed using Playbooks, Roles, and Inventory, ensuring consistent desired state.

What is Configuration Management?

The practice of defining and maintaining the desired state of IT infrastructure, including OS configuration, software installation, user/group management, package updates, service management, security/network configuration, and application deployment.

3. Traditional vs Automated

Traditional (Manual)Automated (Ansible)
Manual server configurationConfiguration as Code
Time-consumingFast and repeatable
Prone to human errorConsistent results
Difficult to scaleEasily manages hundreds of servers
Hard to auditVersion controlled in Git

Ansible Architecture

Architecture Flow: Developer/Admin → Git Repository → Jenkins Pipeline → Ansible Control Node → SSH (Agentless) → Web/App/DB/Cache Servers.

Workflow: Read Inventory → Connect via SSH → Execute Playbook → Apply Modules → Verify State → Report Status.

Key Components

Core Management Tasks

Configuration Logic

Advanced Integration

Best Practices

Store in Git, use Roles, avoid hardcoding, use Ansible Vault for secrets, use Dynamic Inventory, test in Staging, write idempotent tasks, and use Tags for selective runs.

Summary

Automated Configuration Management with Ansible enables reliable, scalable infrastructure management. Key concepts: Agentless automation, Inventory, Playbooks, Roles, Variables, Templates, Idempotency, Vault, Cloud/CI/CD Integration. By treating infrastructure as code, you eliminate drift and improve deployment reliability.

Ansible Interview Questions & Answers

Part 1: Fundamentals, Architecture, Installation & Configuration

Q1. What is Ansible?

Ansible is an open-source automation tool used for Configuration management, Application deployment, Infrastructure provisioning, Continuous deployment, and Orchestration. It automates IT operations using YAML-based playbooks.

Q2. Who developed Ansible?

Ansible was created by Michael DeHaan in 2012. Later, it was acquired by Red Hat in 2015.

Q3. What are the main uses of Ansible?

Major uses include Configuration Management, Application Deployment, Server Provisioning, Cloud Automation, Security Automation, Network Automation, and CI/CD Integration.

Q4. Is Ansible agent-based or agentless?

Ansible is an agentless tool. It does not require any agent on managed servers. It uses SSH for Linux and WinRM for Windows.

Q5. Explain Ansible Architecture.

It consists of the Control Node (where Ansible is installed) and Managed Nodes (remote servers). Communication happens via SSH.

Q6. What are the main components of Ansible?

Main components: Control Node, Managed Nodes, Inventory, Playbooks, Modules, Plugins, Roles, and Collections.

Q7. What is an Ansible Control Node?

The Control Node is the server where Ansible is installed and from where it manages remote machines (running Ansible, Python, and SSH).

Q8. What are Managed Nodes?

Managed Nodes are remote servers controlled by Ansible, such as AWS EC2 instances, Linux servers, Database servers, or Kubernetes nodes.

Q9. What protocol does Ansible use for communication?

For Linux, it uses the SSH Protocol. For Windows, it uses the WinRM Protocol.

Q10. What programming language is Ansible written in?

Ansible is mainly written in Python, while Playbooks are written using YAML.

Q11. How do you install Ansible on Ubuntu?

Commands: sudo apt update, sudo apt install ansible -y

Q12. How do you install Ansible on RedHat/CentOS?

Commands: sudo dnf install epel-release -y, sudo dnf install ansible -y

Q13. What are the Ansible configuration files?

Important files: ansible.cfg (Main config), hosts (Inventory), and playbooks.yml (Automation). Default location: /etc/ansible/

Q14. What is ansible.cfg?

It is the main configuration file that defines inventory location, SSH settings, privilege escalation, and logging. Example: host_key_checking=False

Q15. What is Ansible Inventory?

Inventory is a file containing information about managed servers. Example: [webservers], web01 ansible_host=192.168.1.10

Q16. What are the types of Inventory?

Static Inventory (manually maintained) and Dynamic Inventory (automatically retrieved from cloud providers).

Q17. Where is the default inventory file located?

The default location is: /etc/ansible/hosts

Q18. How do you check the Ansible version?

Command: ansible --version

Q19. How do you test Ansible connectivity?

Command: ansible all -m ping

Q20. How do you check inventory hosts?

Command: ansible all --list-hosts

Q21. How do you generate SSH keys for Ansible?

Command: ssh-keygen

Q22. How do you copy SSH keys to managed servers?

Command: ssh-copy-id user@server-ip

Q23. Why does Ansible use SSH keys?

For passwordless authentication, better security, automation support, and faster deployments.

Q24. What is Ansible Galaxy?

A central repository for sharing reusable Roles, Collections, and automation content.

Q25. What are Ansible Collections?

Distribution packages that contain Modules, Plugins, Roles, and Documentation.