๐ฆ 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#
- Use roles for reusable logic
- Group hosts logically in inventory
- Keep secrets in Ansible Vault
- Use
become: true instead of hardcoded sudo
- Write idempotent tasks
- Use handlers only when needed
- Use variables for environment-specific settings
- Prefer
template over copy for configs