๐Ÿ“ฆ Inventory (hosts file)

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

[dbservers]
db1.example.com ansible_user=ubuntu ansible_port=22

โ–ถ๏ธ Basic Playbook Structure

- name: Example playbook
  hosts: webservers
  become: true
  vars:
    apache_port: 8080
  tasks:
    - name: Install Apache
      apt:
        name: apache2
        state: present
        update_cache: yes

    - name: Ensure Apache is running
      service:
        name: apache2
        state: started
        enabled: true

๐Ÿ”ง Common Task Modules

- name: Install packages
  apt:
    name:
      - git
      - curl
    state: present

- name: Copy a file
  copy:
    src: ./file.txt
    dest: /tmp/file.txt

- name: Use a template
  template:
    src: ./file.j2
    dest: /etc/config.cfg

- name: Execute shell command
  shell: "uptime"

- name: Ensure user exists
  user:
    name: deploy
    state: present

- name: Clone git repo
  git:
    repo: https://github.com/example/repo.git
    dest: /var/www/html

๐Ÿ” Loops and Conditionals

- name: Install list of packages
  apt:
    name: "{{ item }}"
    state: present
  with_items:
    - htop
    - tree
    - unzip

- name: Run only on Debian
  apt:
    name: apache2
    state: present
  when: ansible_facts['os_family'] == 'Debian'

๐Ÿ“ข Handlers and Notify

tasks:
  - name: Copy apache config
    copy:
      src: apache.conf
      dest: /etc/apache2/apache2.conf
    notify: restart apache

handlers:
  - name: restart apache
    service:
      name: apache2
      state: restarted

๐Ÿ“ฆ Roles (best practice structure)

roles/
โ”œโ”€โ”€ apache/
โ”‚   โ”œโ”€โ”€ tasks/
โ”‚   โ”‚   โ””โ”€โ”€ main.yml
โ”‚   โ”œโ”€โ”€ handlers/
โ”‚   โ”‚   โ””โ”€โ”€ main.yml
โ”‚   โ”œโ”€โ”€ templates/
โ”‚   โ”‚   โ””โ”€โ”€ apache.conf.j2
โ”‚   โ”œโ”€โ”€ vars/
โ”‚   โ”‚   โ””โ”€โ”€ main.yml

๐Ÿ”ง Example Role Usage in Playbook

- name: Apply roles
  hosts: webservers
  become: true
  roles:
    - apache
    - mysql

๐Ÿ” Useful Commands

ansible all -i inventory -m ping              # Test connectivity
ansible-playbook -i inventory playbook.yml    # Run playbook
ansible-playbook playbook.yml --check         # Dry-run
ansible-playbook playbook.yml -v              # Verbose output
ansible-doc apt                               # Show module docs

๐Ÿ›ก๏ธ Best Practices