Ansible – IT Automation and Configuration Management

4.8 Stars
Version 2.17
25 MB
Ansible – IT Automation and Configuration Management

Comprehensive Guide to Ansible: Infrastructure Automation Made Simple

Ansible has emerged as the leading choice for IT automation, enabling organizations to manage complex infrastructure through simple, human-readable YAML files. Unlike other configuration management tools requiring agents, Ansible operates agentlessly over SSH, dramatically simplifying deployment. This push-based model, combined with intuitive playbook syntax, makes Ansible accessible to both seasoned DevOps engineers and automation newcomers.

The tool excels at configuration management, application deployment, task automation, and infrastructure orchestration. From provisioning cloud resources to deploying containerized applications, Ansible provides a unified platform for managing the entire infrastructure lifecycle.

Installing Ansible

# Ubuntu/Debian
sudo apt update
sudo apt install ansible

# Using pip (latest version)
pip install ansible
pip install ansible-core

# Fedora
sudo dnf install ansible

# macOS
brew install ansible

# Verify installation
ansible --version

# Install collections
ansible-galaxy collection install community.general
ansible-galaxy collection install ansible.posix

Inventory Configuration

# /etc/ansible/hosts or custom inventory

[webservers]
web1.example.com
web2.example.com

[dbservers]
db1.example.com ansible_host=192.168.1.100

[all:vars]
ansible_user=admin
ansible_ssh_private_key_file=~/.ssh/id_rsa

# YAML inventory
all:
  children:
    webservers:
      hosts:
        web1.example.com:
        web2.example.com:
    dbservers:
      hosts:
        db1.example.com:
      vars:
        db_port: 5432

Ad-Hoc Commands

# Ping all hosts
ansible all -m ping

# Run command
ansible webservers -m command -a "uptime"
ansible webservers -a "uptime"

# Shell commands
ansible all -m shell -a "df -h | head -5"

# Copy file
ansible webservers -m copy -a "src=/local/file dest=/remote/file"

# Install package
ansible webservers -m apt -a "name=nginx state=present" --become

# Start service
ansible webservers -m service -a "name=nginx state=started" --become

# Gather facts
ansible webservers -m setup
ansible webservers -m setup -a "filter=ansible_distribution*"

Playbook Basics

# playbook.yml
---
- name: Configure webservers
  hosts: webservers
  become: yes
  
  vars:
    http_port: 80
  
  tasks:
    - name: Install nginx
      apt:
        name: nginx
        state: present
        update_cache: yes
    
    - name: Copy configuration
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Restart nginx
    
    - name: Ensure nginx running
      service:
        name: nginx
        state: started
        enabled: yes
  
  handlers:
    - name: Restart nginx
      service:
        name: nginx
        state: restarted

# Run playbook
ansible-playbook playbook.yml
ansible-playbook -i inventory.yml playbook.yml
ansible-playbook playbook.yml --check  # Dry run
ansible-playbook playbook.yml -v       # Verbose

Variables and Facts

# Variable definition
vars:
  http_port: 80
  app_name: myapp

# From file
vars_files:
  - vars/main.yml
  - vars/secrets.yml

# At runtime
ansible-playbook playbook.yml -e "http_port=8080"

# Host variables (host_vars/hostname.yml)
http_port: 8080

# Group variables (group_vars/groupname.yml)
http_port: 80
document_root: /var/www/html

# Using facts
- name: Print OS info
  debug:
    msg: "OS: {{ ansible_distribution }} {{ ansible_distribution_version }}"

- name: Conditional on OS
  apt:
    name: nginx
  when: ansible_os_family == "Debian"

# Register results
- name: Check service
  command: systemctl status nginx
  register: nginx_status
  ignore_errors: yes

- name: Print status
  debug:
    var: nginx_status.stdout

Conditionals and Loops

# Conditionals
- name: Install on Debian
  apt:
    name: nginx
  when: ansible_os_family == "Debian"

# Multiple conditions
- name: Complex condition
  command: /bin/something
  when:
    - ansible_distribution == "Ubuntu"
    - ansible_distribution_major_version | int >= 20

# Loops
- name: Install packages
  apt:
    name: "{{ item }}"
    state: present
  loop:
    - nginx
    - postgresql
    - redis

# Loop with dict
- name: Create users
  user:
    name: "{{ item.name }}"
    groups: "{{ item.groups }}"
  loop:
    - { name: 'user1', groups: 'admin' }
    - { name: 'user2', groups: 'developers' }

# Until loop
- name: Wait for service
  uri:
    url: http://localhost:8080/health
  register: result
  until: result.status == 200
  retries: 10
  delay: 5

Roles

# Role structure
roles/
  webserver/
    tasks/main.yml
    handlers/main.yml
    templates/
    files/
    vars/main.yml
    defaults/main.yml
    meta/main.yml

# Create role
ansible-galaxy init roles/webserver

# roles/webserver/tasks/main.yml
---
- name: Install nginx
  apt:
    name: nginx
    state: present

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

# Using roles
---
- hosts: webservers
  become: yes
  roles:
    - webserver
    - role: database
      vars:
        db_port: 5432

Ansible Vault

# Create encrypted file
ansible-vault create secrets.yml

# Edit encrypted file
ansible-vault edit secrets.yml

# Encrypt existing file
ansible-vault encrypt vars.yml

# Decrypt file
ansible-vault decrypt vars.yml

# View encrypted file
ansible-vault view secrets.yml

# Run playbook with vault
ansible-playbook playbook.yml --ask-vault-pass
ansible-playbook playbook.yml --vault-password-file ~/.vault_pass

# Encrypt string
ansible-vault encrypt_string 'secret' --name 'password'

Templates (Jinja2)

# templates/nginx.conf.j2
server {
    listen {{ http_port }};
    server_name {{ inventory_hostname }};
    
    location / {
        root {{ document_root }};
    }
    
{% if enable_ssl %}
    listen 443 ssl;
    ssl_certificate {{ ssl_cert }};
{% endif %}
}

# Template with loops
{% for vhost in virtual_hosts %}
server {
    listen {{ vhost.port }};
    server_name {{ vhost.name }};
}
{% endfor %}

Error Handling

# Ignore errors
- name: Try something
  command: /bin/risky
  ignore_errors: yes

# Block with rescue
- name: Handle errors
  block:
    - name: Try task
      command: /bin/something
  rescue:
    - name: Handle failure
      debug:
        msg: "Something failed"
  always:
    - name: Always run
      debug:
        msg: "Cleanup"

Ansible Galaxy

# Install role
ansible-galaxy install geerlingguy.nginx
ansible-galaxy install geerlingguy.docker

# requirements.yml
---
roles:
  - name: geerlingguy.nginx
  - name: geerlingguy.docker
    version: "6.1.0"

collections:
  - name: community.general

ansible-galaxy install -r requirements.yml

# Initialize new role
ansible-galaxy init my_role

Common Modules

# Package management
- apt: name=nginx state=present
- yum: name=nginx state=present
- pip: name=flask state=present

# File operations
- file: path=/etc/app state=directory mode='0755'
- copy: src=file.txt dest=/etc/app/file.txt
- template: src=config.j2 dest=/etc/app/config.conf
- lineinfile: path=/etc/hosts line="192.168.1.1 myhost"

# Services
- service: name=nginx state=started enabled=yes
- systemd: name=nginx state=restarted daemon_reload=yes

# Users and groups
- user: name=deploy groups=admin shell=/bin/bash
- group: name=developers state=present

# Commands
- command: /bin/something
- shell: echo "hello" > /tmp/hello.txt
- script: /local/script.sh

Conclusion

Ansible provides a powerful yet approachable platform for infrastructure automation. Its agentless architecture, readable YAML syntax, and extensive module library enable teams to codify infrastructure and achieve consistent deployments. Whether managing a handful of servers or orchestrating complex multi-cloud environments, Ansible’s flexibility makes it essential for modern DevOps practices.

Developer: Red Hat

Download Options

Download Ansible – IT Automation and Configuration Management

Version 2.17

File Size: 25 MB

Download Now
Safe & Secure

Verified and scanned for viruses

Regular Updates

Always get the latest version

24/7 Support

Help available when you need it