Skip to content

Instantly share code, notes, and snippets.

@ZappaBoy
Created September 10, 2022 19:41
Show Gist options
  • Save ZappaBoy/5ef6de12a28f06373206d0b116515b57 to your computer and use it in GitHub Desktop.
Save ZappaBoy/5ef6de12a28f06373206d0b116515b57 to your computer and use it in GitHub Desktop.
Ansible Getting Started Cheatsheet

Getting Started

Templating

You can copy-paste the code in this document and simply replace the UPPERCASE vairables with your configurations.

Create an inventory.yaml

all:
  hosts:
    # Add this block for each server
    SERVERNAME:
      ansible_become_pass: "{{ become_pass_SERVERNAME }}"
      ansible_ssh_host: "{{ ssh_host_SERVERNAME }}"
      ansible_ssh_user: "{{ ssh_user_SERVERNAME }}"
      ansible_ssh_port: "{{ ssh_port_SERVERNAME }}"
      ansible_ssh_pass: "{{ ssh_pass_SERVERNAME }}"
      ansible_ssh_private_key_file: "{{ ssh_private_key_file_SERVERNAME }}"
    # ...
    
  children:
    allservers:
      hosts:
        # Add the server to the hosts group
        SERVERNAME:

Create the following directories structure for each server

host_vars/
└── SERVERNAME
    ├── vars
    └── vault

host_vars/SERVERNAME/vars

---
# SERVERNAME Vars
become_pass_SERVERNAME: "{{ vault_become_pass_SERVERNAME }}"
ssh_host_SERVERNAME: "IP"
ssh_user_SERVERNAME: "USERNAME"
ssh_port_SERVERNAME: "PORT"
ssh_private_key_file_SERVERNAME:  "SSH_KEY_PATH"
ssh_pass_SERVERNAME: "{{ vault_ssh_pass_SERVERNAME }}"

host_vars/SERVERNAME/vault

Create the vault using the ansible-vault command:

ansible-vault create host_vars/server_name/vault
---
vault_become_pass_SERVERNAME: "BECOME_PASS"
vault_ssh_pass_SERVERNAME: "SSH_PASS"

Add the following to the inventory file

all:
  hosts:
    # ...
    SERVERNAME:
      ansible_become_pass: "{{ become_pass_SERVERNAME }}"
      ansible_ssh_host: "{{ ssh_host_SERVERNAME }}"
      ansible_ssh_user: "{{ ssh_user_SERVERNAME }}"
      ansible_ssh_port: "{{ ssh_port_SERVERNAME }}"
      ansible_ssh_pass: "{{ ssh_pass_SERVERNAME }}"
      ansible_ssh_private_key_file: "{{ ssh_private_key_file_SERVERNAME }}"
    # ...
  children:
    allservers:
      hosts:
        SERVERNAME:

Add the ssh key using ssh-agent

If you use a passhphrase encrypted private key you need to use ssh-agent due to the fact that ansible doesn’t support that.

eval "$(ssh-agent -s)"
ssh-add "SSH_KEY_PATH"

Run a command

ansible all -i inventory.yaml --ask-vault-pass --fork NUMBER_OF_SERVERS -m command -a COMMAND

Run a module

ansible all -i inventory.yaml --ask-vault-pass --fork NUMBER_OF_SERVERS -m module MODULE_NAME

Run a playbook

ansible-playbook -i inventory.yaml --ask-vault-pass --fork NUMBER_OF_SERVERS PLAYBOOK_PATH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment