Ansible cheat sheet: installation, Kerberos, inventory and roles
Installing Ansible in a virtual environment, automation user, SSH, Kerberos/WinRM, inventories, updates and playbook examples.
Ansible cheat sheet: installing in a Python virtual environment, creating an automation user, deploying SSH keys, Kerberos authentication for Windows targets, updating the tooling, and sample roles and playbooks.
Installation (CentOS / RHEL)
sudo yum install python-virtualenv sshpass
sudo yum install gcc python3-devel krb5-devel krb5-libs krb5-workstation
sudo pip3 install --upgrade pip
# dedicated user
sudo adduser user-ansible
sudo su - user-ansible
echo "alias python='python3'" >> ~/.bashrc
# virtual environment
python3.8 -m venv ansible
source ansible/bin/activate
pip3 install ansible
pip3 install pywinrm
pip3 install pywinrm[kerberos]
ansible --version
Automation user on the nodes
Generate a SHA-512 password hash:
ansible localhost -m debug -a "msg={{'<PASSWORD>'|password_hash('sha512','secretsalt')}}"
Create the user on the Linux nodes (connecting with an existing admin account):
ansible -i env/dev/inventory.yml -m user \
-a 'name=user-ansible password=<HASH>' \
--user admin_user --become --ask-pass --ask-become-pass linux
To pin the user's uid and gid, add the uid= and group= parameters of the user module (create the group beforehand with the wanted gid).
Sudoers
File 10-user-ansible to deploy in /etc/sudoers.d/:
user-ansible ALL=(ALL) NOPASSWD:ALL
Defaults:update !requiretty
ansible -i env/dev/inventory.yml -m ansible.builtin.copy \
-a "src=/home/user-ansible/deploy/etc/sudoers.d/10-user-ansible dest=/etc/sudoers.d/10-user-ansible mode=644 owner=root group=root" \
--user admin_user --become --ask-pass --ask-become-pass linux
SSH key
ssh-keygen -t ecdsa
ansible -i env/dev/inventory.yml -m authorized_key \
-a 'user=user-ansible state=present key="{{lookup("file", "/home/user-ansible/.ssh/id_ecdsa.pub") }}"' \
--user user-ansible --become --ask-pass --ask-become-pass linux
To use this user by default, set it in group_vars/all:
ansible_connection: ssh
ansible_user: user-ansible
Or per host in the inventory:
hosts:
server01.example.com:
ansible_user: user-ansible
Kerberos for Windows targets (WinRM)
Install the packages (krb5-workstation, krb5-libs, krb5-devel) and pywinrm[kerberos] in the virtual environment, then configure /etc/krb5.conf:
includedir /etc/krb5.conf.d/
[logging]
default = FILE:/var/log/krb5libs.log
kdc = FILE:/var/log/krb5kdc.log
admin_server = FILE:/var/log/kadmind.log
[libdefaults]
dns_lookup_realm = false
ticket_lifetime = 24h
renew_lifetime = 7d
forwardable = true
rdns = false
pkinit_anchors = FILE:/etc/pki/tls/certs/ca-bundle.crt
default_ccache_name = KEYRING:persistent:%{uid}
default_realm = EXAMPLE.COM
File /etc/krb5.conf.d/10-example.conf:
[realms]
EXAMPLE.COM = {
kdc = kdc01.example.com:88
kdc = kdc02.example.com:88
admin_server = kdc01.example.com:749
default_domain = example.com
}
[domain_realm]
.example.com = EXAMPLE.COM
Test:
kinit user@example.com
klist
kdestroy
ansible -i env/dev/inventory.yml -m win_ping 'w2016:&mssql'
On the Windows side:
winrm enumerate winrm/config/listener
Inventory
ansible-inventory --graph -i hosts.yaml
ansible -i inventaire_all.yml 'prod:&mssql' --list-hosts
ansible -i inventaire.ini -m ping all
Example of a hierarchical inventory:
all:
children:
dev:
children:
db:
children:
linux:
children:
centos:
children:
oracle:
hosts:
dev_lnx_cent_orcl_server1:
mysql:
hosts:
dev_lnx_cent_mysql_server1:
windows:
children:
w2019:
children:
mssql:
hosts:
dev_win_19_mssql_server1:
Possible layout:
env/
├── dev
│ ├── group_vars
│ │ └── windows
│ ├── host_vars
│ └── inventory.yml
├── prod
│ └── inventory.yml
└── stage
Host patterns
| Pattern | Result |
|---|---|
all |
All hosts in the inventory |
host1 |
A single host |
host1:host2 |
Both host1 and host2 |
group1 |
A single group |
group1:group2 |
All servers in group1 and group2 |
group1:&group2 |
Servers that are in both group1 and group2 |
group1:!group2 |
Servers in group1 except those also in group2 |
Lookup order
Inventory file: ./hosts, ~/.ansible/hosts, /etc/ansible/hosts.
Configuration file: ANSIBLE_CONFIG environment variable, ansible.cfg in the current directory, ~/.ansible.cfg, /etc/ansible/ansible.cfg.
Updating
Python packages:
pip list --outdated --format=json | jq '.[].name' | xargs -n1 pip install -U
# or, without jq
pip --disable-pip-version-check list --outdated --format=json \
| python -c "import json, sys; print('\n'.join([x['name'] for x in json.load(sys.stdin)]))" \
| xargs -n1 pip install -U
Galaxy collections (with ansible-galaxy-outdated):
ansible-galaxy collection list
ansible-galaxy-outdated | awk 'NR>2 {print $1}' | xargs -n1 ansible-galaxy collection install -U
ansible-galaxy collection install -U ansible.windows
ansible-galaxy collection install -r requirements.yml
For an urllib3-related error: pip install -U urllib3 requests.
Roles and playbooks
Conditional reboot
roles/common/tasks/checkReboot.yml (the checkReboot.sh script must print reboot when a reboot is required):
- name: block reboot
block:
- name: check Reboot
script: checkReboot.sh
ignore_errors: false
register: reboot_hint
- name: is required reboot
debug:
msg: "return code : {{ reboot_hint.stdout }}"
- name: Reboot a slow machine that might have lots of updates to apply
ansible.builtin.reboot:
reboot_timeout: 3600
when: reboot_hint.stdout is search('reboot')
rescue:
- name: Print when errors
ansible.builtin.debug:
msg: 'I caught an error'
Update role that calls it:
- name: Run the equivalent of "yay -Syu" as a separate step
yay:
update_cache: yes
upgrade: yes
- name: Reboot check and reboot if needed
include_role:
name: common
tasks_from: checkReboot.yml
On Arch Linux, the pacman module comes from community.general (ansible-galaxy collection install community.general).
Playbook
---
- name: "update archlinux"
hosts: arch
serial: 1
become: yes
ignore_unreachable: yes
roles:
- role: "arch_update"
ansible-playbook -i inventaire.ini --user user-ansible --become update_arch.yml
Conditional become depending on the OS:
- hosts: all
become: "{{ 'no' if ansible_facts['os_family'] == 'Windows' else 'yes' }}"
Splitting role tasks
- include_tasks: run-this-first.yml
- include_tasks: run-this-second.yml
- include_tasks: run-this-last.yml
Run a task on a single node
- name: Create API resources directory
file:
path: "{{ output_dir.path }}/api-resources"
state: directory
when: inventory_hostname == groups['control-plane'][0]
Other examples
# count the hosts of a group
- set_fact: group_number="{{ groups['Groupe1']|count }}"
# print all facts
- name: Print all available facts
ansible.builtin.debug:
var: ansible_facts
# write an output to a local file
- name: shell command
shell: my_shell_command
register: myshell_output
- name: copy the output to a local file
copy:
content: "{{ myshell_output.stdout }}"
dest: "/tmp/hello.txt"
delegate_to: localhost
Ad hoc commands:
ansible <hostname> -m ansible.builtin.setup
ansible linux -m setup -i env/dev/ -a 'filter=ansible_distribution,ansible_distribution_version,ansible_memtotal_mb,ansible_kernel'
ansible localhost -m include_role -a name=<role_name>
ansible -i env/dev/ -m ping linux
ansible -i env/dev/ -m win_ping 'windows'
Windows examples
- hosts: win
tasks:
- name: Install MSI
win_package:
path: C:\ansible_examples\package.msi
state: present
arguments:
- /install
- /passive
- /norestart
- name: Stop a service
win_service:
name: Tomcat8
state: stopped
- name: Set an environment variable for all users
win_environment:
state: present
name: NewVariable
value: New Value
level: machine
- name: Create a registry key
win_regedit:
path: HKLM:\SOFTWARE\Example
name: Key
data: Value
- name: Run an executable
win_command: whoami.exe
Check for pending Windows updates (PowerShell):
$UpdateSession = New-Object -ComObject Microsoft.Update.Session
$UpdateSearcher = $UpdateSession.CreateupdateSearcher()
$searchresult = $updatesearcher.Search("IsInstalled=0") # 0 = NotInstalled | 1 = Installed
$searchresult.Updates.Count
Notes
- Ansible is agentless: SSH for Linux, WinRM for Windows.
- Never store clear-text passwords in inventories or playbooks; use
--ask-pass,--ask-become-passor Ansible Vault.