Here’s a cheat sheet for Ansible:
Basic Commands
Running a Playbook:
ansible-playbook playbook.yml
Running Ad-Hoc Commands:
ansible all -m command -a "uname -a"
Inventory
Specifying Inventory File:
ansible-playbook -i inventory_file playbook.yml
Listing Hosts in Inventory:
ansible-inventory --list
Playbooks
Defining a Playbook:
---
- name: My Playbook
hosts: all
tasks:
- name: My Task
command: echo "Hello, World!"
Running a Specific Task in a Playbook:
ansible-playbook playbook.yml --tags=task_name
Variables
Defining Variables in Playbooks:
---
- name: Playbook with Variables
hosts: all
vars:
my_var: "Hello, Ansible!"
tasks:
- name: Display Variable
debug:
var: my_var
Overriding Variables at Runtime:
ansible-playbook playbook.yml -e "my_var=NewValue"
Roles
Creating a Role:
ansible-galaxy init role_name
Including a Role in a Playbook:
---
- name: Playbook with Role
hosts: all
roles:
- role: role_name
Handlers
Defining a Handler:
---
- name: Playbook with Handler
hosts: all
tasks:
- name: My Task
command: echo "Change Detected"
notify: Restart Service
handlers:
- name: Restart Service
service:
name: my_service
state: restarted
Conditionals
Using when
in a Task:
---
- name: Conditional Task
hosts: all
tasks:
- name: Conditional Command
command: echo "Condition Met"
when: my_condition == "true"
Modules
Common Modules:
command
: Execute a command on hosts.shell
: Execute shell commands.copy
: Copy files to remote hosts.file
: Manage files and directories.
Ansible Galaxy
Installing Roles from Galaxy:
ansible-galaxy install author.role_name
Listing Installed Roles:
ansible-galaxy list
SSH Key Authentication
Setting Up SSH Key Authentication:
ssh-copy-id user@host
Here is a dedicated SSH Cheat Sheet.
This cheat sheet covers some basic Ansible commands and concepts. For more details and advanced usage, refer to the official Ansible documentation.