Skip to content

Instantly share code, notes, and snippets.

@AlexAtkinson
Last active January 5, 2026 05:16
Show Gist options
  • Select an option

  • Save AlexAtkinson/fa4ee968b5ed422eb35435a82ca37b8e to your computer and use it in GitHub Desktop.

Select an option

Save AlexAtkinson/fa4ee968b5ed422eb35435a82ca37b8e to your computer and use it in GitHub Desktop.
Ansible Cheat

Ansible Cheat Sheet

Stuff I forgot...

TODO: Remember the stuff that drove me nuts as a noob...

Personal Use Tactics

These tactics shouldn't be employed in production.

Source ~/.bashrc

- name: Shell with .bashrc
  shell: |
    source ~/.bashrc
    custom_cmds...

General Good Practice

Common Assets Directory

Maintain a common download assets directory which can be used across multiple runs. This ensures that modules, such as 'get_url', are able to skip their action if an asset is already present. This conserves disk space, reduces bandwidth OPEX, reduces runtime, and mitigates unecessary internet traffic.

- name: "Create temp assets directory which will be utilized across multiple builds"
  ansible.builtin.file:
    path: /tmp/ansible_assets_dir
    state: directory
    mode: '0755'
  register: temp_assets_dir

Note:

  • This directory IS NOT to be cleaned up at the end of each run.
  • This direcotry may be persisted outside of /tmp as needed.
  • Some distributions only clear /tmp on boot. Configure as needed.

Per-Build Temp Directories

Maintain a discrete temporary directory for each run. The following prefixes the directory with both 'ansible' as well as a timestamp, ensuring ease of identification as needed.

- name: "Create temp directory for this build"
  ansible.builtin.tempfile:
    state: directory
    prefix: "ansible_{{ now(utc=true,fmt='%Y-%m-%dT%H-%M-%SZ') }}_"
  register: temp_dir

This directory may be cleaned up at the end of each run.

Facts

Know the facts.

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Get Ansible Facts for a given host.
# Arguments:
#   <host>         The host to get facts for (optional, defaults to localhost)
# Outputs:
#   JSON formatted Ansible facts
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# shellcheck disable=2120,2034
_ansible_facts() {
  local HOSTS
  [[ $1 == '-h' ]] && loggerx ERROR "Usage: _ansible_facts [<host>]" && return 1
  [[ -z $1 ]] && HOSTS='localhost' || HOSTS="$1"
  ansible "$HOSTS" -m ansible.builtin.setup | sed '1c {' | jq .
}

IE: _ansible_facts | jq -r .ansible_facts.ansible_all_ipv4_addresses

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment