Ansible Cheat Sheet: Quick Reference Guide

blank
Ansible Cheatsheet

Ansible is a powerful automation tool used for configuration management, application deployment, and task automation. It simplifies complex tasks and ensures consistency across environments.

Whether you’re a beginner or an experienced user, this Ansible cheat sheet will help you streamline your automation workflows.


Essential Ansible Commands

1. Inventory Management

Ansible uses an inventory file to define the hosts and groups of hosts on which commands and playbooks will run.

Command/FileDescription
/etc/ansible/hostsDefault location for the inventory file.
ansible-inventory --listLists all hosts and groups in the inventory.
ansible-inventory --graphDisplays a visual representation of the inventory.
[group-name]Defines a group of hosts in the inventory file.
[group-name:vars]Defines variables for a specific group.
Example Inventory File:
[webservers]
web1.example.com
web2.example.com

[dbservers]
db1.example.com
db2.example.com

[webservers:vars]
ansible_user=admin
ansible_ssh_private_key_file=/path/to/key.pemCode language: JavaScript (javascript)

2. Ad-Hoc Commands

Ad-hoc commands are used to execute quick tasks on remote hosts without writing a playbook.

CommandDescription
ansible <group> -m <module> -a "<arguments>"Runs a module on a group of hosts.
ansible all -m pingPings all hosts in the inventory.
ansible webservers -m shell -a "uptime"Runs the uptime command on all webservers.
ansible dbservers -m yum -a "name=httpd state=present"Installs the httpd package on all dbservers.
ansible all -m copy -a "src=/file.txt dest=/tmp/file.txt"Copies a file to all hosts.

3. Playbook Execution

Playbooks are YAML files that define automation tasks.

CommandDescription
ansible-playbook <playbook.yml>Runs a playbook.
ansible-playbook <playbook.yml> --limit <group>Runs a playbook on a specific group of hosts.
ansible-playbook <playbook.yml> --start-at-task="task-name"Starts a playbook at a specific task.
ansible-playbook <playbook.yml> --checkPerforms a dry run without making changes.
ansible-playbook <playbook.yml> --tags <tag-name>Runs only tasks with a specific tag.
Example Playbook:
- name: Install and start Apache
  hosts: webservers
  become: yes
  tasks:
    - name: Install Apache
      yum:
        name: httpd
        state: present

    - name: Start Apache service
      service:
        name: httpd
        state: started

4. Modules

Modules are the building blocks of Ansible, used to perform specific tasks.

ModuleDescription
yumManages packages on Red Hat-based systems.
aptManages packages on Debian-based systems.
serviceManages services.
copyCopies files to remote hosts.
fileManages files and directories.
shellExecutes shell commands.
templateRenders a template file and copies it to the remote host.
userManages user accounts.
debugPrints debug messages during playbook execution.

5. Variables and Facts

Variables allow you to customize playbooks, and facts provide information about remote hosts.

CommandDescription
ansible <host> -m setupDisplays all facts about a host.
{{ variable_name }}Syntax to use variables in playbooks.
vars:Defines variables in a playbook.
hostvarsAccesses variables from other hosts.
Example:
- name: Use variables
  hosts: all
  vars:
    app_port: 8080
  tasks:
    - name: Print variable value
      debug:
        msg: "The app port is {{ app_port }}"Code language: JavaScript (javascript)

6. Conditionals and Loops

Conditionals and loops allow you to control task execution and repeat tasks.

SyntaxDescription
when: <condition>Executes a task only if the condition is true.
with_items: <list>Iterates over a list of items.
loop:Modern alternative to with_items.
Example:
- name: Install multiple packages
  hosts: all
  tasks:
    - name: Install packages
      yum:
        name: "{{ item }}"
        state: present
      loop:
        - httpd
        - mariadb
        - phpCode language: JavaScript (javascript)

7. Roles

Roles are reusable units of automation that organize playbooks and tasks.

CommandDescription
ansible-galaxy init <role-name>Creates a new role structure.
roles/Directory where roles are stored.
ansible-galaxy install <role-name>Installs a role from Ansible Galaxy.
Example Role Structure:
roles/
  common/
    tasks/
    handlers/
    templates/
    files/
    vars/
    defaults/
    meta/

8. Handlers

Handlers are tasks that run only when notified by other tasks.

SyntaxDescription
notify: <handler-name>Triggers a handler after a task.
handlers:Defines handlers in a playbook.
Example:
- name: Restart Apache
  hosts: webservers
  tasks:
    - name: Install Apache
      yum:
        name: httpd
        state: present
      notify: Restart Apache service

  handlers:
    - name: Restart Apache service
      service:
        name: httpd
        state: restarted

Common Ansible Challenges and Solutions

ChallengeSolution
Permission denied errorsUse become: yes to escalate privileges.
Slow playbook executionUse strategy: free in the playbook to speed up execution.
Undefined variablesEnsure variables are defined in the inventory, playbook, or role.
Idempotency issuesUse modules that ensure idempotency (e.g., yum, apt).
Debugging playbooksUse the debug module to print variable values and task outputs.

FAQs About Ansible

What is the difference between ansible-playbook and ansible?

ansible is used for ad-hoc commands.
ansible-playbook is used to execute playbooks.

How do I check the syntax of a playbook?

Use the command:
ansible-playbook <playbook.yml> --syntax-check

Can I use Ansible for Windows?

Yes, Ansible supports Windows using the win_* modules (e.g., win_package, win_service).

How do I manage secrets in Ansible?

Use Ansible Vault to encrypt sensitive data:
ansible-vault create <file.yml>
ansible-vault edit <file.yml>
ansible-playbook <playbook.yml> --ask-vault-pass


    Pro Tips for Using Ansible

    1. Use Roles for Reusability: Organize your playbooks into roles for better maintainability.
    2. Leverage Tags: Use tags to run specific tasks or groups of tasks.
    3. Test Playbooks: Use --check and --diff to test playbooks before execution.
    4. Use Ansible Galaxy: Explore and reuse roles from Ansible Galaxy to save time.
    5. Document Your Playbooks: Add comments and descriptions to make playbooks easier to understand.

    Total
    0
    Shares
    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Previous Post
    Git cheat sheet

    Git Cheat Sheet: Essential Commands and Tips

    Related Posts