Ad-Hoc Commands
- ansible all -m pingPing hosts
- -m shell -a "cmd"Run command
- -m copy -a "..."Copy files
- -m apt -a "..."Package mgmt
- -m service -a "..."Manage service
Common Modules
- copyCopy files
- templateJinja2 templates
- fileFile attributes
- lineinfileEdit line in file
- commandExecute command
- shellShell command
Playbook Commands
- ansible-playbookRun playbook
- -i inventorySpecify hosts
- --checkDry run
- --diffShow changes
- -v/-vvvVerbosity
Inventory Options
- [group]Host group
- [group:vars]Group variables
- [group:children]Nested groups
- ansible_hostTarget IP
- ansible_userSSH user
Playbook Structure
---
- name: Configure web servers
hosts: webservers
become: true
vars:
http_port: 80
tasks:
- name: Install nginx
apt:
name: nginx
state: present
update_cache: yes
- name: Start nginx
service:
name: nginx
state: started
enabled: yes
Variables & Conditionals
# Variable definition
vars:
packages:
- nginx
- git
# Using variables
- name: Install packages
apt:
name: "{{ item }}"
state: present
loop: "{{ packages }}"
# Conditional execution
- name: Only on Ubuntu
apt: name=nginx
when: ansible_os_family == "Debian"
Role Structure
roles/
└── webserver/
├── tasks/
│ └── main.yml
├── handlers/
│ └── main.yml
├── templates/
├── files/
├── vars/
│ └── main.yml
├── defaults/
│ └── main.yml
└── meta/
└── main.yml
Vault Commands
- ansible-vault createCreate encrypted
- ansible-vault editEdit encrypted
- ansible-vault viewView contents
- ansible-vault encryptEncrypt file
- ansible-vault decryptDecrypt file
Handlers & Notify
tasks:
- name: Update nginx config
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: Restart nginx
handlers:
- name: Restart nginx
service:
name: nginx
state: restarted
Dynamic Inventory
- aws_ec2AWS EC2
- azure_rmAzure
- gcp_computeGCP
- docker_containersDocker
- kubernetesK8s
Variable Precedence
- extra vars (-e)Highest
- task varsTask level
- play varsPlaybook
- host_varsPer host
- group_varsPer group
- defaultsLowest