Ansible

Ansible


What is Ansible?

Ansible is an agentless automation tool used for:

  • Server configuration
  • Application deployment
  • Orchestration
  • Infrastructure automation

Uses YAML Playbooks + works over SSH.


๐Ÿงพ Check Installation

ansible --version

๐ŸŒ Inventory (Hosts File)

Default inventory file:

/etc/ansible/hosts

Example:

[webservers]
192.168.1.10
192.168.1.11

[db]
192.168.1.20

Custom inventory usage:

ansible -i inventory.ini all -m ping

Generate key:

ssh-keygen

Copy key:

ssh-copy-id user@server

๐Ÿงช Test Connection

ansible all -m ping

Specific group:

ansible webservers -m ping

๐Ÿงญ Ad-hoc Commands

Run command on remote:

ansible all -m command -a "uptime"

Install package:

ansible all -m apt -a "name=nginx state=present" --become

Copy file:

ansible all -m copy -a "src=file.txt dest=/home/user/"

Create directory:

ansible all -m file -a "path=/opt/test state=directory"

๐Ÿ“œ Playbook Structure

A playbook is YAML:

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

Run playbook:

ansible-playbook site.yml

๐Ÿงฉ Common Modules

Module Purpose
ping test connectivity
apt / yum package management
service manage services
copy copy files
file manage files/dirs
command run commands
shell run shell commands
user user management

โš™๏ธ Service Management

- name: Start nginx
  service:
    name: nginx
    state: started

Enable service:

- name: Enable nginx
  service:
    name: nginx
    enabled: yes

๐Ÿ“‚ Copy & Templates

Copy file:

- name: Copy config
  copy:
    src: config.conf
    dest: /etc/app/config.conf

Template (Jinja2):

- name: Deploy template
  template:
    src: config.j2
    dest: /etc/app/config.conf

๐Ÿ”‘ Become (Root Privilege)

In playbook:

become: yes

In command:

ansible-playbook play.yml --become

๐Ÿง  Variables

vars:
  package: nginx

tasks:
  - name: Install package
    apt:
      name: "{{ package }}"
      state: present

๐ŸŽฏ Handlers (Run Only When Changed)

tasks:
  - name: Install nginx
    apt:
      name: nginx
      state: present
    notify: restart nginx

handlers:
  - name: restart nginx
    service:
      name: nginx
      state: restarted

๐Ÿงช Dry Run (Check Mode)

ansible-playbook site.yml --check

๐ŸŽ๏ธ Speed Tips

Disable SSH host checking:

[defaults]
host_key_checking = False

Run in parallel:

ansible-playbook site.yml -f 10

๐Ÿงพ Facts (System Info)

Show facts:

ansible all -m setup

Use in play:

ansible_facts['ansible_hostname']

[!Summary]
Ansible is awesome because it is:

  • Agentless
  • Simple YAML-based
  • Secure (SSH)
  • Scalable
  • DevOps standard