Aide-mémoire Ansible : installation, Kerberos, inventaire et rôles
Installation d'Ansible en environnement virtuel, utilisateur d'automatisation, SSH, Kerberos/WinRM, inventaires, mises à jour et exemples de playbooks.
Aide-mémoire Ansible : installation dans un environnement virtuel Python, création d'un utilisateur d'automatisation, déploiement des clés SSH, authentification Kerberos pour Windows, mise à jour des outils et exemples de rôles et de 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
# utilisateur dédié
sudo adduser user-ansible
sudo su - user-ansible
echo "alias python='python3'" >> ~/.bashrc
# environnement virtuel
python3.8 -m venv ansible
source ansible/bin/activate
pip3 install ansible
pip3 install pywinrm
pip3 install pywinrm[kerberos]
ansible --version
Utilisateur d'automatisation sur les nœuds
Générer un hash de mot de passe SHA-512 :
ansible localhost -m debug -a "msg={{'<PASSWORD>'|password_hash('sha512','secretsalt')}}"
Créer l'utilisateur sur les nœuds Linux (connexion avec un compte administrateur existant) :
ansible -i env/dev/inventory.yml -m user \
-a 'name=user-ansible password=<HASH>' \
--user admin_user --become --ask-pass --ask-become-pass linux
Pour fixer l'uid et le gid de l'utilisateur, ajouter les paramètres uid= et group= du module user (créer le groupe au préalable avec le gid voulu).
Sudoers
Fichier 10-user-ansible à déployer dans /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
Clé SSH
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
Pour utiliser cet utilisateur par défaut, le définir dans group_vars/all :
ansible_connection: ssh
ansible_user: user-ansible
Ou par hôte dans l'inventaire :
hosts:
server01.example.com:
ansible_user: user-ansible
Kerberos pour cibles Windows (WinRM)
Installer les paquets (krb5-workstation, krb5-libs, krb5-devel) et pywinrm[kerberos] dans l'environnement virtuel, puis configurer /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
Fichier /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'
Test côté Windows :
winrm enumerate winrm/config/listener
Inventaire
ansible-inventory --graph -i hosts.yaml
ansible -i inventaire_all.yml 'prod:&mssql' --list-hosts
ansible -i inventaire.ini -m ping all
Exemple d'inventaire hiérarchique :
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:
Arborescence possible :
env/
├── dev
│ ├── group_vars
│ │ └── windows
│ ├── host_vars
│ └── inventory.yml
├── prod
│ └── inventory.yml
└── stage
Motifs de sélection des hôtes
| Motif | Résultat |
|---|---|
all |
Tous les hôtes de l'inventaire |
host1 |
Un seul hôte |
host1:host2 |
host1 et host2 |
group1 |
Un seul groupe |
group1:group2 |
Tous les serveurs de group1 et group2 |
group1:&group2 |
Serveurs présents dans group1 et group2 |
group1:!group2 |
Serveurs de group1 sauf ceux de group2 |
Ordre de recherche
Fichier d'inventaire : ./hosts, ~/.ansible/hosts, /etc/ansible/hosts.
Fichier de configuration : variable ANSIBLE_CONFIG, ansible.cfg dans le répertoire courant, ~/.ansible.cfg, /etc/ansible/ansible.cfg.
Mise à jour
Paquets Python :
pip list --outdated --format=json | jq '.[].name' | xargs -n1 pip install -U
# ou, sans 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
Collections Galaxy (outil 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
En cas d'erreur liée à urllib3 : pip install -U urllib3 requests.
Rôles et playbooks
Redémarrage conditionnel
roles/common/tasks/checkReboot.yml (le script checkReboot.sh doit afficher reboot si un redémarrage est nécessaire) :
- 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'
Rôle de mise à jour qui l'appelle :
- 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
Pour Arch Linux, le module pacman est fourni par 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
become conditionnel selon l'OS :
- hosts: all
become: "{{ 'no' if ansible_facts['os_family'] == 'Windows' else 'yes' }}"
Découper les tâches d'un rôle
- include_tasks: run-this-first.yml
- include_tasks: run-this-second.yml
- include_tasks: run-this-last.yml
Exécuter une tâche sur un seul nœud
- name: Create API resources directory
file:
path: "{{ output_dir.path }}/api-resources"
state: directory
when: inventory_hostname == groups['control-plane'][0]
Autres exemples
# compter les hôtes d'un groupe
- set_fact: group_number="{{ groups['Groupe1']|count }}"
# afficher tous les facts
- name: Print all available facts
ansible.builtin.debug:
var: ansible_facts
# écrire une sortie dans un fichier local
- 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
Commandes ad hoc :
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'
Exemples Windows
- 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
Vérifier les mises à jour Windows en attente (PowerShell) :
$UpdateSession = New-Object -ComObject Microsoft.Update.Session
$UpdateSearcher = $UpdateSession.CreateupdateSearcher()
$searchresult = $updatesearcher.Search("IsInstalled=0") # 0 = NotInstalled | 1 = Installed
$searchresult.Updates.Count
Remarques
- Ansible est sans agent : SSH pour Linux, WinRM pour Windows.
- Ne jamais stocker de mot de passe en clair dans les inventaires ou les playbooks ; utiliser
--ask-pass,--ask-become-passou Ansible Vault.