Skip to content

Instantly share code, notes, and snippets.

@AntoOnline
Last active April 29, 2023 19:38
Show Gist options
  • Save AntoOnline/c794fb24b3826716a941781177c64934 to your computer and use it in GitHub Desktop.
Save AntoOnline/c794fb24b3826716a941781177c64934 to your computer and use it in GitHub Desktop.

Ansible Cheat Sheet

Installation

pip install ansible

Inventory File (hosts)

[web]
web1.example.com
web2.example.com

[db]
db1.example.com

[all:vars]
ansible_user=myuser

Basic Commands

Ping hosts

ansible all -m ping

Run ad-hoc command

ansible all -a "df -h"

Check syntax of playbook

ansible-playbook playbook.yml --syntax-check

Run playbook

ansible-playbook -i hosts playbook.yml

Run playbook with tags

ansible-playbook -i hosts playbook.yml --tags "tag1,tag2"

Playbook Structure

Basic Playbook

---
- name: My first playbook
  hosts: all
  tasks:
    - name: Ensure nginx is installed
      ansible.builtin.package:
        name: nginx
        state: present

Variables

vars:
  user_name: "john"
  user_home: "/home/john"

Handlers

handlers:
  - name: restart nginx
    ansible.builtin.service:
      name: nginx
      state: restarted

Roles

ansible-galaxy init my-role

Directory Structure

my-role/
    ├── defaults/
    ├── files/
    ├── handlers/
    ├── meta/
    ├── tasks/
    ├── templates/
    └── vars/

Conditionals

when: "'web' in group_names"

Loops

with_items:
  - item1
  - item2

Debugging

Debug task output

- name: Debug variable
  ansible.builtin.debug:
    var: my_variable
This cheat sheet should provide a quick reference for someone new to Ansible. It covers installation, inventory files, basic commands, playbook structure, and some debugging tips.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment