Ceci est une ancienne révision du document !


Version - 2021.01

Dernière mise-à-jour : 2021/03/26 10:21

DOF503 - Rôles, Gabarits et Hiérarchie des Variables

Contenu du Module

  • DOF503 - Rôles, Gabarits et Hiérarchie des Variables
    • Contenu du Module
    • LAB #1 - Dépendances de Rôles
    • LAB #2 - Utilisation des Gabarits
      • 2.1 - Variables
      • 2.2 - Gabarits Conditionnels
      • 2.3 - Boucles
      • 2.4 - Macros
      • 2.5 - Filtres
        • 2.5.1 - Default
        • 2.5.2 - Join
        • 2.5.3 - Map
      • 2.6 - Gabarits Parent - Enfants
        • 2.6.1 - Le Gabarit Parent
        • 2.6.2 - Le Gabarit Enfant
    • LAB #3 - Gestion de la Hiérarchie des Variables

LAB #1 - Dépendances de Rôles

Afin de comprendre le fonctionnement des dépendances entre les Rôles vous allez étudier l'exemple de l'installation d'Apache Tomcat. Apache Tomcat est un serveur d'applications Java et par conséquent nécessite à ce que Java soit installé.

Commencez par créer le Rôle exemple01.java dans le répertoire /home/trainee/.ansible/roles/ :

trainee@ansible:~$ mkdir /home/trainee/.ansible/roles/exemple01.java/
trainee@ansible:~$ cd /home/trainee/.ansible/roles/exemple01.java/
trainee@ansible:~/.ansible/roles/exemple01.java$ mkdir defaults tasks templates
trainee@ansible:~/.ansible/roles/exemple01.java$ 

Important : Notez que dans ce Rôle nous n'avons besoin que des répertoires defaults, tasks et templates.

Créez le fichier main.yaml dans le sous-répertoire tasks afin d'installer Java :

trainee@ansible:~/.ansible/roles/exemple01.java$ vi /home/trainee/.ansible/roles/exemple01.java/tasks/main.yaml
trainee@ansible:~/.ansible/roles/exemple01.java$ cat /home/trainee/.ansible/roles/exemple01.java/tasks/main.yaml
---
- name: install jre
  package: name={{ java_package }} state=present

- name: configure java home 
  template:
    src: java.sh
    dest: /etc/profile.d/java.sh
    owner: root
    group: root
    mode: 0644

Important : Notez que le paquet à installer n'est pas explicitement déclaré. Le paquet est référencé par le contenu de la variable java_package, elle-même déclarée dans le fichier main.yaml du sous-répertoire defaults du Rôle. Notez aussi l'utilisation d'un gabarit, appelé template, qui fournit le fichier java.sh qui doit être copié à l'emplacement /etc/profile.d/ à partir du sous-répertoire templates du Rôle.

Créez donc le fichier main.yaml du sous-répertoire defaults :

trainee@ansible:~/.ansible/roles/exemple01.java$ vi /home/trainee/.ansible/roles/exemple01.java/defaults/main.yaml
trainee@ansible:~/.ansible/roles/exemple01.java$ cat /home/trainee/.ansible/roles/exemple01.java/defaults/main.yaml
---
java_home: /usr/lib/jvm/java-8-openjdk-amd64/jre
java_package: openjdk-8-jre

Important : Notez qu'ici sont déclarées deux variables : java_home et java_package.

Dernièrement, créez le fichier vide java.sh dans le sous-répertoire templates du Rôle exemple01.java :

trainee@ansible:~/.ansible/roles/exemple01.java$ touch /home/trainee/.ansible/roles/exemple01.java/templates/java.sh

Important : Ce fichier ne serait pas normalement vide. Par contre dans ce LAB, nous nous concentrons sur Ansible et seule la présence du fichier est nécessaire pour le bon fonctionnement du LAB.

Créez maintenant le Rôle tomcat dans le répertoire /home/trainee/.ansible/roles/ :

trainee@ansible:~$ mkdir /home/trainee/.ansible/roles/tomcat/
trainee@ansible:~$ cd /home/trainee/.ansible/roles/tomcat/
trainee@ansible:~/.ansible/roles/tomcat$ mkdir meta tasks

Important : Notez que dans ce Rôle nous n'avons besoin que des répertoires meta et tasks.

Créez le fichier main.yaml dans le sous-répertoire tasks afin d'installer Tomcat 8 :

trainee@ansible:~/.ansible/roles/tomcat$ vi /home/trainee/.ansible/roles/tomcat/tasks/main.yaml
trainee@ansible:~/.ansible/roles/tomcat$ cat /home/trainee/.ansible/roles/tomcat/tasks/main.yaml
---
- name: install tomcat
  package: name=tomcat8 state=present

Créez maintenant le fichier main.yaml du sous-répertoire meta du Rôle tomcat :

trainee@ansible:~/.ansible/roles/tomcat$ vi /home/trainee/.ansible/roles/tomcat/meta/main.yaml
trainee@ansible:~/.ansible/roles/tomcat$ cat /home/trainee/.ansible/roles/tomcat/meta/main.yaml
---
dependencies:
  - exemple01.java

Important : Ce fichier informe Ansible que le Rôle tomcat dépend du Rôle exemple01.java.

Ensuite créez le fichier playbook.yaml au dessus des deux Rôles précédemment crées :

trainee@ansible:~/.ansible/roles/tomcat$ vi /home/trainee/.ansible/roles/playbook.yaml
trainee@ansible:~/.ansible/roles/tomcat$ cat /home/trainee/.ansible/roles/playbook.yaml
---
- hosts: all
  become: true
  roles: 
    - tomcat

Important : Notez que dans le Play Book, nous appelons uniquement le Rôle tomcat.

Copiez le fichier /home/trainee/inventory dans le répertoire /home/trainee/.ansible/roles/ :

trainee@ansible:~/.ansible/roles/tomcat$ cd /home/trainee/.ansible/roles/
trainee@ansible:~/.ansible/roles$ cp ~/inventory .

A l'issu de cette configuration, vous devrez obtenir l'arborescence suivante :

trainee@ansible:~/.ansible/roles$ tree
.
├── exemple01.java
│   ├── defaults
│   │   └── main.yaml
│   ├── tasks
│   │   └── main.yaml
│   └── templates
│       └── java.sh
├── geerlingguy.java
│   ├── defaults
│   │   └── main.yml
│   ├── LICENSE
│   ├── meta
│   │   └── main.yml
│   ├── molecule
│   │   └── default
│   │       ├── converge.yml
│   │       └── molecule.yml
│   ├── README.md
│   ├── tasks
│   │   ├── main.yml
│   │   ├── setup-Debian.yml
│   │   ├── setup-FreeBSD.yml
│   │   └── setup-RedHat.yml
│   ├── templates
│   │   └── java_home.sh.j2
│   └── vars
│       ├── Debian-10.yml
│       ├── Debian-8.yml
│       ├── Debian-9.yml
│       ├── Fedora.yml
│       ├── FreeBSD.yml
│       ├── RedHat-6.yml
│       ├── RedHat-7.yml
│       ├── RedHat-8.yml
│       ├── Ubuntu-12.yml
│       ├── Ubuntu-14.yml
│       ├── Ubuntu-16.yml
│       ├── Ubuntu-18.yml
│       └── Ubuntu-20.yml
├── inventory
├── playbook.yaml
└── tomcat
    ├── meta
    │   └── main.yaml
    └── tasks
        └── main.yaml
15 directories, 31 files

Exécutez la commande ansible-playbook uniquement pour l'hôte web01 :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml -l web01
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web01]

TASK [exemple01.java : install jre] ********************************************************************************************************************
ok: [web01]

TASK [exemple01.java : configure java home] ************************************************************************************************************
changed: [web01]

TASK [tomcat : install tomcat] *************************************************************************************************************************
changed: [web01]

PLAY RECAP *********************************************************************************************************************************************
web01                      : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

Important : Notez que le Rôle exemple01.java est traité avant le Rôle tomcat.

Vérifiez l'installation de Java et de Tomcat8 dans la machine Web01 :

trainee@ansible:~/.ansible/roles$ ssh web01
Debian GNU/Linux 9
Linux web01.i2tch.loc 4.9.0-8-amd64 #1 SMP Debian 4.9.130-2 (2018-10-27) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Mar 24 14:32:15 2021 from 10.0.2.50

trainee@web01:~$ systemctl status tomcat8
● tomcat8.service - LSB: Start Tomcat.
   Loaded: loaded (/etc/init.d/tomcat8; generated; vendor preset: enabled)
   Active: active (running) since Wed 2021-03-24 14:32:59 CET; 2min 19s ago
     Docs: man:systemd-sysv-generator(8)
   CGroup: /system.slice/tomcat8.service
           └─9437 /usr/lib/jvm/default-java/bin/java -Djava.util.logging.config.file=/var/lib/tomcat8/conf/logging.properties -Djava.util.logging.manage
trainee@web01:~$ exit
déconnexion
Connection to web01 closed.
trainee@ansible:~/.ansible/roles$

Modifiez maintenant le fichier /home/trainee/.ansible/roles/tomcat/meta/main.yaml :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/tomcat/meta/main.yaml
trainee@ansible:~/.ansible/roles$ cat /home/trainee/.ansible/roles/tomcat/meta/main.yaml
---
dependencies:
  - { role: exemple01.java, java_package: tree } 

Important : Notez que cette fois-ci, la valeur de la variable java_package spécifiée dans le fichier /home/trainee/.ansible/roles/exemple01.java/defaults/main.yaml est sur-chargée par la valeur tree.

Testez votre configuration :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml -l web02
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web02]

TASK [exemple01.java : install jre] ********************************************************************************************************************
changed: [web02]

TASK [exemple01.java : configure java home] ************************************************************************************************************
changed: [web02]

TASK [tomcat : install tomcat] *************************************************************************************************************************
changed: [web02]

PLAY RECAP *********************************************************************************************************************************************
web02                      : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

LAB #2 - Utilisation des Gabarits

2.1 - Variables

Les Gabarits ou Templates d'Ansible utilisent une bibliothèque Python qui s'appelle Jinja2.

Important : La documentation des gabarits se trouvent à cette adresse: https://docs.ansible.com/ansible/latest/modules/template_module.html.

Afin de comprendre le fonctionnement des gabarits vous allez étudier l'exemple de l'installation d'HAProxy sur la machine Web04.

Commencez par créer le Rôle haproxy :

trainee@ansible:~/.ansible/roles$ mkdir /home/trainee/.ansible/roles/haproxy/
trainee@ansible:~$ cd /home/trainee/.ansible/roles/haproxy/
trainee@ansible:~/.ansible/roles/haproxy$ mkdir defaults handlers tasks templates

Important : Notez que dans ce Rôle nous n'avons besoin que des répertoires defaults, handlers, tasks et templates.

Créez maintenant le fichier /home/trainee/.ansible/roles/haproxy/tasks/main.yaml :

trainee@ansible:~/.ansible/roles/haproxy$ vi /home/trainee/.ansible/roles/haproxy/tasks/main.yaml
trainee@ansible:~/.ansible/roles/haproxy$ cat /home/trainee/.ansible/roles/haproxy/tasks/main.yaml
--- 
- name: install
  package: name=haproxy state=present

- name: configure
  template:
    src: haproxy.cfg
    dest: /etc/haproxy/haproxy.cfg
    owner: root
    group: root
    mode: 0644
  notify: reload haproxy

- name: service
  service: name=haproxy state=started enabled=yes 

Important : Notez que l'installation fait appel à un gabarit suivi par un Handler qui s'appelle reload haproxy.

Créez donc ce Handler dans le fichier /home/trainee/.ansible/roles/haproxy/handlers/main.yaml :

trainee@ansible:~/.ansible/roles/haproxy$ vi /home/trainee/.ansible/roles/haproxy/handlers/main.yaml
trainee@ansible:~/.ansible/roles/haproxy$ cat /home/trainee/.ansible/roles/haproxy/handlers/main.yaml
---
- name: reload haproxy
  service: name=haproxy state=reloaded

Créez maintenant le fichier haproxy.cfg dans le répertoire /home/trainee/.ansible/roles/haproxy/templates/ :

trainee@ansible:~/.ansible/roles/haproxy$ vi /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
trainee@ansible:~/.ansible/roles/haproxy$ cat /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
global
	log /dev/log	local0
	log /dev/log	local1 notice
	chroot /var/lib/haproxy
	stats socket /run/haproxy/admin.sock mode 660 level admin
	stats timeout 30s
	user haproxy
	group haproxy
	daemon

	# Default SSL material locations
	ca-base /etc/ssl/certs
	crt-base /etc/ssl/private

	# Default ciphers to use on SSL-enabled listening sockets.
	# For more information, see ciphers(1SSL). This list is from:
	#  https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
	# An alternative list with additional directives can be obtained from
	#  https://mozilla.github.io/server-side-tls/ssl-config-generator/?server=haproxy
	ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
	ssl-default-bind-options no-sslv3

defaults
	log	global
	mode	http
	option	httplog
	option	dontlognull
        timeout connect 5000
        timeout client  50000
        timeout server  50000
	errorfile 400 /etc/haproxy/errors/400.http
	errorfile 403 /etc/haproxy/errors/403.http
	errorfile 408 /etc/haproxy/errors/408.http
	errorfile 500 /etc/haproxy/errors/500.http
	errorfile 502 /etc/haproxy/errors/502.http
	errorfile 503 /etc/haproxy/errors/503.http
	errorfile 504 /etc/haproxy/errors/504.http

frontend haproxy
    bind {{ haproxy_listen_address }}:{{haproxy_listen_port}}
    mode http
    default_backend dotcms
    stats enable
    stats uri /haproxy?stats
    stats realm HAProxy Statistics
    stats auth admin:admin
    balance roundrobin
    option httpclose
    option forwardfor

backend dotcms
    server web02 10.0.2.54:8080 check
    server web03 10.0.2.55:8080 check

Important : Notez l'utilisation de deux variables Ansible dans ce fichier - {{ haproxy_listen_address }} et {{haproxy_listen_port}}.

Spécifiez la valeur de ces variables dans le fichier /home/trainee/.ansible/roles/haproxy/defaults/main.yaml :

trainee@ansible:~/.ansible/roles/haproxy$ vi /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
trainee@ansible:~/.ansible/roles/haproxy$ cat /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
---
haproxy_listen_address: 0.0.0.0
haproxy_listen_port: 80
haproxy_log: haproxy.log

Dernièrement, modifiez le fichier ~/.ansible/roles/playbook.yaml afin d'appeler le Rôle haproxy :

trainee@ansible:~/.ansible/roles/haproxy$ cd ..
trainee@ansible:~/.ansible/roles$ vi playbook.yaml 
trainee@ansible:~/.ansible/roles$ cat playbook.yaml 
---
- hosts: all
  become: true
  roles: 
    - haproxy

Exécutez la commande ansible-playbook sur le groupe equilibrage qui contient web04 :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml -l equilibrage
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web04]

TASK [haproxy : install] *******************************************************************************************************************************
ok: [web04]

TASK [haproxy : configure] *****************************************************************************************************************************
changed: [web04]

TASK [haproxy : service] *******************************************************************************************************************************
ok: [web04]

RUNNING HANDLER [haproxy : reload haproxy] *************************************************************************************************************
changed: [web04]

PLAY RECAP *********************************************************************************************************************************************
web04                      : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

Consultez l'état du service haproxy ainsi que le contenu du fichier /etc/haproxy/haproxy.cfg dans la machine Web04 :

trainee@ansible:~/.ansible/roles$ ssh web04
Debian GNU/Linux 9
Linux web04.i2tch.loc 4.9.0-8-amd64 #1 SMP Debian 4.9.130-2 (2018-10-27) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Mar 24 15:33:40 2021 from 10.0.2.50
trainee@web04:~$ systemctl status haproxy
● haproxy.service - HAProxy Load Balancer
   Loaded: loaded (/lib/systemd/system/haproxy.service; enabled; vendor preset: enabled)
   Active: active (running) since Wed 2021-03-24 12:24:08 CET; 3h 11min ago
     Docs: man:haproxy(1)
           file:/usr/share/doc/haproxy/configuration.txt.gz
  Process: 6930 ExecReload=/bin/kill -USR2 $MAINPID (code=exited, status=0/SUCCESS)
  Process: 6928 ExecReload=/usr/sbin/haproxy -f $CONFIG -c -q $EXTRAOPTS (code=exited, status=0/SUCCESS)
 Main PID: 3166 (haproxy-systemd)
    Tasks: 3 (limit: 4915)
   CGroup: /system.slice/haproxy.service
           ├─3166 /usr/sbin/haproxy-systemd-wrapper -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid
           ├─6931 /usr/sbin/haproxy-master
           └─6934 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -Ds -sf 3171
trainee@web04:~$ cat /etc/haproxy/haproxy.cfg
global
	log /dev/log	local0
	log /dev/log	local1 notice
	chroot /var/lib/haproxy
	stats socket /run/haproxy/admin.sock mode 660 level admin
	stats timeout 30s
	user haproxy
	group haproxy
	daemon

	# Default SSL material locations
	ca-base /etc/ssl/certs
	crt-base /etc/ssl/private

	# Default ciphers to use on SSL-enabled listening sockets.
	# For more information, see ciphers(1SSL). This list is from:
	#  https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
	# An alternative list with additional directives can be obtained from
	#  https://mozilla.github.io/server-side-tls/ssl-config-generator/?server=haproxy
	ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
	ssl-default-bind-options no-sslv3

defaults
	log	global
	mode	http
	option	httplog
	option	dontlognull
        timeout connect 5000
        timeout client  50000
        timeout server  50000
	errorfile 400 /etc/haproxy/errors/400.http
	errorfile 403 /etc/haproxy/errors/403.http
	errorfile 408 /etc/haproxy/errors/408.http
	errorfile 500 /etc/haproxy/errors/500.http
	errorfile 502 /etc/haproxy/errors/502.http
	errorfile 503 /etc/haproxy/errors/503.http
	errorfile 504 /etc/haproxy/errors/504.http

frontend haproxy
    bind 0.0.0.0:80
    mode http
    default_backend dotcms
    stats enable
    stats uri /haproxy?stats
    stats realm HAProxy Statistics
    stats auth admin:admin
    balance roundrobin
    option httpclose
    option forwardfor

backend dotcms
    server web02 10.0.2.54:8080 check
    server web03 10.0.2.55:8080 check

trainee@web04:~$ exit
déconnexion
Connection to web04 closed.

Important : Notez que les valeurs des variables spécifiées dans le fichier /home/trainee/.ansible/roles/haproxy/defaults/main.yaml ont été injectées à la place des variables {{ haproxy_listen_address }} et {{haproxy_listen_port}}.

2.2 - Gabarits Conditionnels

Les gabarits peuvent être configurés d'une manière conditionnelle afin de produire des résultats différents en fonction de la valeur d'une variable. Afin de comprendre le fonctionnement des gabarits conditionnels vous allez modifier l'exemple de l'installation d'HAProxy sur la machine Web04.

Editez le fichier /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg :

trainee@ansible:~/.ansible/roles$
trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
trainee@ansible:~/.ansible/roles$ tail -n 17 /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
frontend haproxy
    bind {{ haproxy_listen_address }}:{{haproxy_listen_port}}
    mode http
    default_backend dotcms
{% if haproxy_stats %}
    stats enable
    stats uri /haproxy?stats
    stats realm HAProxy Statistics
    stats auth admin:admin
{% endif %}
    balance roundrobin
    option httpclose
    option forwardfor

backend dotcms
    server web02 10.0.2.54:8080 check
    server web03 10.0.2.55:8080 check

Important : Notez la condition {% if haproxy_stats %} qui ne tiendra compte des quatre lignes jusqu'à la ligne {% endif %} que dans le cas où la valeur de la variable haproxy_stats est True.

Définissez la variable haproxy_stats dans le fichier /home/trainee/.ansible/roles/haproxy/defaults/main.yaml :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
trainee@ansible:~/.ansible/roles$ cat /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
---
haproxy_listen_address: 0.0.0.0
haproxy_listen_port: 80
haproxy_log: haproxy.log
haproxy_stats: True

Important : Notez qu'Ansible teste si la variable est définie. Par conséquent la variable peut contenir la valeur True, true voire toute autre chaîne telle que toto.

Exécutez maintenant la commande ansible-playbook :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml -l equilibrage
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web04]

TASK [haproxy : install] *******************************************************************************************************************************
ok: [web04]

TASK [haproxy : configure] *****************************************************************************************************************************
ok: [web04]

TASK [haproxy : service] *******************************************************************************************************************************
ok: [web04]

PLAY RECAP *********************************************************************************************************************************************
web04                      : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

Contrôlez le contenu du fichier /etc/haproxy/haproxy.cfg dans la machine Web04 :

trainee@ansible:~/.ansible/roles$ ssh web04
Debian GNU/Linux 9
Linux web04.i2tch.loc 4.9.0-8-amd64 #1 SMP Debian 4.9.130-2 (2018-10-27) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Mar 24 15:39:34 2021 from 10.0.2.50
trainee@web04:~$ tail -n 17 /etc/haproxy/haproxy.cfg
	errorfile 504 /etc/haproxy/errors/504.http

frontend haproxy
    bind 0.0.0.0:80
    mode http
    default_backend dotcms
    stats enable
    stats uri /haproxy?stats
    stats realm HAProxy Statistics
    stats auth admin:admin
    balance roundrobin
    option httpclose
    option forwardfor

backend dotcms
    server web02 10.0.2.54:8080 check
    server web03 10.0.2.55:8080 check

trainee@web04:~$ exit
déconnexion
Connection to web04 closed.

Important : Notez que les quatre lignes concernant les statistiques ont été incluses dans le fichier.

Éditez de nouveau le fichier /home/trainee/.ansible/roles/haproxy/defaults/main.yaml en modifiant la valeur de la variable haproxy_stats de True à False :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
trainee@ansible:~/.ansible/roles$ cat /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
---
haproxy_listen_address: 0.0.0.0
haproxy_listen_port: 80
haproxy_log: haproxy.log
haproxy_stats: False 

Important : Notez qu'Ansible teste si la variable n'est pas définie ou définie avec la valeur de False ou false. La valeur donc haproxy_stats: seule est considérée comme étant fausse.

Exécutez de nouveau la commande ansible-playbook :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml -l equilibrage
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web04]

TASK [haproxy : install] *******************************************************************************************************************************
ok: [web04]

TASK [haproxy : configure] *****************************************************************************************************************************
changed: [web04]

TASK [haproxy : service] *******************************************************************************************************************************
ok: [web04]

RUNNING HANDLER [haproxy : reload haproxy] *************************************************************************************************************
changed: [web04]

PLAY RECAP *********************************************************************************************************************************************
web04                      : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Contrôlez le contenu du fichier /etc/haproxy/haproxy.cfg dans la machine Web04 :

trainee@ansible:~/.ansible/roles$ ssh web04
Debian GNU/Linux 9
Linux web04.i2tch.loc 4.9.0-8-amd64 #1 SMP Debian 4.9.130-2 (2018-10-27) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Mar 24 15:42:29 2021 from 10.0.2.50
trainee@web04:~$ tail -n 17 /etc/haproxy/haproxy.cfg
	errorfile 408 /etc/haproxy/errors/408.http
	errorfile 500 /etc/haproxy/errors/500.http
	errorfile 502 /etc/haproxy/errors/502.http
	errorfile 503 /etc/haproxy/errors/503.http
	errorfile 504 /etc/haproxy/errors/504.http

frontend haproxy
    bind 0.0.0.0:80
    mode http
    default_backend dotcms
    balance roundrobin
    option httpclose
    option forwardfor

backend dotcms
    server web02 10.0.2.54:8080 check
    server web03 10.0.2.55:8080 check
trainee@web04:~$ exit
déconnexion
Connection to web04 closed.

Important : Notez que les quatre lignes concernant les statistiques n'ont pas été incluses dans le fichier.

L'inverse de la condition {% if haproxy_stats %} peut être obtenue en utilisant le mot not :

{% if not haproxy_stats %}

La condition suivante est remplie quelque soit la valeur de la variable {% if haproxy_stats %} :

{% if haproxy_stats is defined %}

La condition suivante est identique à la condition {% if haproxy_stats %} :

{% if haproxy_stats is defined and haproxy_stats %}

2.3 - Boucles

Créez la variable haproxy_backends dans le fichier /home/trainee/.ansible/roles/haproxy/defaults/main.yaml :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
trainee@ansible:~/.ansible/roles$ cat /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
---
haproxy_listen_address: 0.0.0.0
haproxy_listen_port: 80
haproxy_log: haproxy.log
haproxy_stats: True 
haproxy_backends:
  - 'server web02 10.0.2.54:8080 check'
  - 'server web03 10.0.2.55:8080 check'

Important : Notez que la variable haproxy_backends est une liste YAML.

Créez ensuite un boucle dans le fichier /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
trainee@ansible:~/.ansible/roles$ tail /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
    stats auth admin:admin
{% endif %}
    balance roundrobin
    option httpclose
    option forwardfor

backend dotcms
{% for backend in haproxy_backends %}
    {{ backend }}
{% endfor %}

Une autre façon de créer un boucle est d'utiliser un dictionnaire YAML :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
trainee@ansible:~/.ansible/roles$ cat /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
---
haproxy_listen_address: 0.0.0.0
haproxy_listen_port: 80
haproxy_log: haproxy.log
haproxy_stats: True 
haproxy_backends:
  web02:
    ip: 10.0.2.54
  web03:
    ip: 10.0.2.55

Pour accéder aux données dans le dictionnaire, il convient d'utiliser la fonction Python items :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
trainee@ansible:~/.ansible/roles$ tail /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
    stats auth admin:admin
{% endif %}
    balance roundrobin
    option httpclose
    option forwardfor

backend dotcms
{% for key, value in haproxy_backends.items() %}
    server {{ key }} {{ value.ip }}:8080 check
{% endfor %}

2.4 - Macros

Il est aussi possible d'utiliser un macro avec le dictionnaire :

trainee@ansible:~/.ansible/roles$ vi backend.j2
trainee@ansible:~/.ansible/roles$ cat backend.j2
{% macro backend(name, ip, port=8080) -%}
    server {{ name }} {{ ip }}:{{ port }} check
{%- endmacro %}

Il convient ensuite d'importer les valeurs dans le fichier /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg :

...
{% import 'backend.j2' as backend %}
backend dotcms
{% for key, value in haproxy_backends.items() %}
{{backend.backend(key, value.ip)}}
{% endfor %}

2.5 - Filtres

2.5.1 - Default

Le filtre default permet de fournir une valeur par défaut pour une variable. Éditez le fichier /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg et modifiez la variable haproxy_listen_port et la condition haproxy_stats :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
trainee@ansible:~/.ansible/roles$ tail -n 17 /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
    bind {{ haproxy_listen_address }}:{{haproxy_listen_port|default('80') }}
    mode http
    default_backend dotcms
{% if haproxy_stats|default(True) %}
    stats enable
    stats uri /haproxy?stats
    stats realm HAProxy Statistics
    stats auth admin:admin
{% endif %}
    balance roundrobin
    option httpclose
    option forwardfor

backend dotcms
{% for key, value in haproxy_backends.items() %}
    server {{ key }} {{ value.ip }}:8080 check
{% endfor %}

Supprimez ensuite les lignes haproxy_listen_port et haproxy_stats du fichier /home/trainee/.ansible/roles/haproxy/defaults/main.yaml :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
trainee@ansible:~/.ansible/roles$ cat /home/trainee/.ansible/roles/haproxy/defaults/main.yaml
---
haproxy_listen_address: 0.0.0.0
haproxy_log: haproxy.log
haproxy_backends:
  web02:
    ip: 10.0.2.54
  web03:
    ip: 10.0.2.55

Testez la configuration avec la commande ansible-playbook :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml -l equilibrage
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web04]

TASK [haproxy : install] *******************************************************************************************************************************
ok: [web04]

TASK [haproxy : configure] *****************************************************************************************************************************
changed: [web04]

TASK [haproxy : service] *******************************************************************************************************************************
ok: [web04]

RUNNING HANDLER [haproxy : reload haproxy] *************************************************************************************************************
changed: [web04]

PLAY RECAP *********************************************************************************************************************************************
web04                      : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

Vérifiez ensuite que les valeurs par défaut ont bien été utilisées :

trainee@ansible:~/.ansible/roles$ ssh web04
Debian GNU/Linux 9
Linux web04.i2tch.loc 4.9.0-8-amd64 #1 SMP Debian 4.9.130-2 (2018-10-27) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Mar 24 15:55:45 2021 from 10.0.2.50
trainee@web04:~$ tail -n 17 /etc/haproxy/haproxy.cfg
	errorfile 504 /etc/haproxy/errors/504.http

frontend haproxy
    bind 0.0.0.0:80
    mode http
    default_backend dotcms
    stats enable
    stats uri /haproxy?stats
    stats realm HAProxy Statistics
    stats auth admin:admin
    balance roundrobin
    option httpclose
    option forwardfor

backend dotcms
    server web03 10.0.2.55:8080 check
    server web02 10.0.2.54:8080 check
trainee@web04:~$ exit
déconnexion
Connection to web04 closed.

2.5.2 - Join

Le filtre Join :

{{ haproxy_backends|join(',') }}

permet de prendre une liste YAML :

haproxy_backends:
  - web02
  - web03

et de produire une liste séparée par des virgules :

web02,web03

2.5.3 - Map

Le filtre Map :

{{ haproxy_backends.values()|map(attribute='ip')|join(',') }}

permet de prendre un dictionnaire YAML :

haproxy_backends:
  web02:
    ip: 10.0.2.54
  web03:
    ip: 10.0.2.55

et de produire une liste séparée par des virgules :

10.0.2.54,10.0.2.55

2.6 - Gabarits Parent - Enfants

HAProxy ne gère pas uniquement le protocole http. Il peut également gérer d'autres connexions TCP. Pour cette raison, il est intéressant de créer un gabarit générique pour HAProxy et un gabarit enfants par protocole.

2.6.1 - Le Gabarit Parent

Modifiez donc le fichier /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg :

trainee@ansible:~$ vi /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
trainee@ansible:~$ cat /home/trainee/.ansible/roles/haproxy/templates/haproxy.cfg
global
	log /dev/log	local0
	log /dev/log	local1 notice
	chroot /var/lib/haproxy
	stats socket /run/haproxy/admin.sock mode 660 level admin
	stats timeout 30s
	user haproxy
	group haproxy
	daemon
{% block globals %}
{% endblock %}

defaults
	log	global
	option	dontlognull
        timeout connect 5000
        timeout client  50000
        timeout server  50000
{% block defaults %}
{% endblock %}

{% block server %}
{% endblock %}

Important : Ce gabarit ne contient que des directives générales. Les directives spécifiques au protocole http ont été remplacées par des blocs nommés globals, defaults et server.

2.6.2 - Le Gabarit Enfant

Créez maintenant le gabarit /home/trainee/.ansible/roles/haproxy/templates/haproxy.http.cfg, spécifique au protocole http :

trainee@ansible:~$ vi /home/trainee/.ansible/roles/haproxy/templates/haproxy.http.cfg
trainee@ansible:~$ cat /home/trainee/.ansible/roles/haproxy/templates/haproxy.http.cfg
{% extends 'haproxy.cfg' %}
{% block globals %}
	ca-base /etc/ssl/certs
	crt-base /etc/ssl/private
	ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
	ssl-default-bind-options no-sslv3
{% endblock %}
{% block defaults %}
	mode	http
	option	httplog
	errorfile 400 /etc/haproxy/errors/400.http
	errorfile 403 /etc/haproxy/errors/403.http
	errorfile 408 /etc/haproxy/errors/408.http
	errorfile 500 /etc/haproxy/errors/500.http
	errorfile 502 /etc/haproxy/errors/502.http
	errorfile 503 /etc/haproxy/errors/503.http
	errorfile 504 /etc/haproxy/errors/504.http
{% endblock %}
{% block server %}
frontend haproxy
    bind {{ haproxy_listen_address }}:{{haproxy_listen_port|default('80') }}
    mode http
    default_backend dotcms
{% if haproxy_stats|default(True) %}
    stats enable
    stats uri /haproxy?stats
    stats realm HAProxy Statistics
    stats auth admin:admin
{% endif %}
    balance roundrobin
    option httpclose
    option forwardfor

backend dotcms
{% for key, value in haproxy_backends.items() %}
    server {{ key }} {{ value.ip }}:8080 check
{% endfor %}
{% endblock %}

Important : Notez que les blocs nommés globals, defaults et server contiennent les directives qui seront injectées dans le fichier haproxy.cfg aux emplacements des trois blocs respectifs.

Modifiez ensuite le fichier /home/trainee/.ansible/roles/haproxy/tasks/main.yaml afin d'appeler le gabarit haproxy.http.cfg :

trainee@ansible:~$ vi /home/trainee/.ansible/roles/haproxy/tasks/main.yaml
trainee@ansible:~$ cat /home/trainee/.ansible/roles/haproxy/tasks/main.yaml
---
- name: install
  package: name=haproxy state=present

- name: configure
  template:
    src: haproxy.http.cfg
    dest: /etc/haproxy/haproxy.cfg
    owner: root
    group: root
    mode: 0644
  notify: reload haproxy

- name: service
  service: name=haproxy state=started enabled=yes

Exécutez la commande ansible-playbook :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml -l equilibrage
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web04]

TASK [haproxy : install] *******************************************************************************************************************************
ok: [web04]

TASK [haproxy : configure] *****************************************************************************************************************************
changed: [web04]

TASK [haproxy : service] *******************************************************************************************************************************
ok: [web04]

RUNNING HANDLER [haproxy : reload haproxy] *************************************************************************************************************
changed: [web04]

PLAY RECAP *********************************************************************************************************************************************
web04                      : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

Contrôlez maintenant le contenu du fichier /etc/haproxy/haproxy.cfg de la machine Web04 :

trainee@ansible:~/.ansible/roles$ ssh web04
Debian GNU/Linux 9
Linux web04.i2tch.loc 4.9.0-8-amd64 #1 SMP Debian 4.9.130-2 (2018-10-27) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Mar 24 16:00:24 2021 from 10.0.2.50
trainee@web04:~$ cat /etc/haproxy/haproxy.cfg
global
	log /dev/log	local0
	log /dev/log	local1 notice
	chroot /var/lib/haproxy
	stats socket /run/haproxy/admin.sock mode 660 level admin
	stats timeout 30s
	user haproxy
	group haproxy
	daemon
	ca-base /etc/ssl/certs
	crt-base /etc/ssl/private
	ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
	ssl-default-bind-options no-sslv3

defaults
	log	global
	option	dontlognull
        timeout connect 5000
        timeout client  50000
        timeout server  50000
	mode	http
	option	httplog
	errorfile 400 /etc/haproxy/errors/400.http
	errorfile 403 /etc/haproxy/errors/403.http
	errorfile 408 /etc/haproxy/errors/408.http
	errorfile 500 /etc/haproxy/errors/500.http
	errorfile 502 /etc/haproxy/errors/502.http
	errorfile 503 /etc/haproxy/errors/503.http
	errorfile 504 /etc/haproxy/errors/504.http

frontend haproxy
    bind 0.0.0.0:80
    mode http
    default_backend dotcms
    stats enable
    stats uri /haproxy?stats
    stats realm HAProxy Statistics
    stats auth admin:admin
    balance roundrobin
    option httpclose
    option forwardfor

backend dotcms
    server web02 10.0.2.54:8080 check
    server web03 10.0.2.55:8080 check

trainee@web04:~$ exit
déconnexion
Connection to web04 closed.

Important : Notez que les blocs nommés globals, defaults et server ont été renseignés.

LAB #3 - Gestion de la Hiérarchie des Variables

La hiérarchie de la prise en compte des variables par Ansible peut être illustrée par le diagremme suvant :

Créez le Rôle /home/trainee/.ansible/roles/debug contenant les sous-répertoires defaults et tasks :

trainee@ansible:~/.ansible/roles$ cd ../../
trainee@ansible:~$ mkdir /home/trainee/.ansible/roles/debug
trainee@ansible:~$ mkdir /home/trainee/.ansible/roles/debug/defaults
trainee@ansible:~$ mkdir /home/trainee/.ansible/roles/debug/tasks

Créez les fichiers main.yaml dans les sous-répertoires defaults et tasks du Rôle /home/trainee/.ansible/roles/debug :

trainee@ansible:~$ touch /home/trainee/.ansible/roles/debug/defaults/main.yaml
trainee@ansible:~$ touch  /home/trainee/.ansible/roles/debug/tasks/main.yaml

Vous obtiendrez :

trainee@ansible:~$ cd .ansible/roles/
trainee@ansible:~/.ansible/roles$ tree debug
debug
├── defaults
│   └── main.yaml
└── tasks
    └── main.yaml

2 directories, 2 files

Créez le répertoire /home/trainee/.ansible/roles/group_vars ainsi que le fichier /home/trainee/.ansible/roles/group_vars/all.yaml :

trainee@ansible:~/.ansible/roles$ mkdir /home/trainee/.ansible/roles/group_vars
trainee@ansible:~/.ansible/roles$ touch /home/trainee/.ansible/roles/group_vars/all.yaml

Vous obtiendrez :

trainee@ansible:~/.ansible/roles$ tree group_vars/
group_vars/
└── all.yaml

0 directories, 1 file

Éditez le fichier /home/trainee/.ansible/roles/debug/tasks/main.yaml en déclarant la valeur par défaut de la variable endroit :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/debug/tasks/main.yaml
trainee@ansible:~/.ansible/roles$ cat /home/trainee/.ansible/roles/debug/tasks/main.yaml
---
- debug:
    msg: "Ce message est issu de {{ endroit|default('roles/debug/tasks/main.yaml') }}"

Éditez le fichier /home/trainee/.ansible/roles/playbook.yaml :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/playbook.yaml 
trainee@ansible:~/.ansible/roles$ cat /home/trainee/.ansible/roles/playbook.yaml 
---
- hosts: all
  roles:
    - debug 

Exécutez la commande ansible-playbook pour voir la valeur par défaut de la variable endroit :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web04]
ok: [web01]
ok: [web03]
ok: [web02]

TASK [debug : debug] ***********************************************************************************************************************************
ok: [web01] => {
    "msg": "Ce message est issu de roles/debug/tasks/main.yaml"
}
ok: [web02] => {
    "msg": "Ce message est issu de roles/debug/tasks/main.yaml"
}
ok: [web03] => {
    "msg": "Ce message est issu de roles/debug/tasks/main.yaml"
}
ok: [web04] => {
    "msg": "Ce message est issu de roles/debug/tasks/main.yaml"
}

PLAY RECAP *********************************************************************************************************************************************
web01                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web02                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web03                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web04                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

Définissez maintenant la valeur de la variable endroit dans le fichier /home/trainee/.ansible/roles/debug/defaults/main.yaml :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/debug/defaults/main.yaml
trainee@ansible:~/.ansible/roles$ cat /home/trainee/.ansible/roles/debug/defaults/main.yaml
---
endroit: 'roles/debug/defaults/main.yaml'

Exécutez la commande ansible-playbook :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web01]
ok: [web03]
ok: [web02]
ok: [web04]

TASK [debug : debug] ***********************************************************************************************************************************
ok: [web01] => {
    "msg": "Ce message est issu de roles/debug/defaults/main.yaml"
}
ok: [web02] => {
    "msg": "Ce message est issu de roles/debug/defaults/main.yaml"
}
ok: [web03] => {
    "msg": "Ce message est issu de roles/debug/defaults/main.yaml"
}
ok: [web04] => {
    "msg": "Ce message est issu de roles/debug/defaults/main.yaml"
}

PLAY RECAP *********************************************************************************************************************************************
web01                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web02                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web03                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web04                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

Important : La variable fixée dans defaults/main.yaml surcharge la variable fixée dans tasks/main.yaml.

Définissez la valeur de la variable endroit dans le fichier /home/trainee/.ansible/roles/group_vars/all.yaml :

trainee@ansible:~/.ansible/roles$ vi /home/trainee/.ansible/roles/group_vars/all.yaml
trainee@ansible:~/.ansible/roles$ cat /home/trainee/.ansible/roles/group_vars/all.yaml
---
endroit: 'roles/group_vars/all.yaml'

Important : La déclaration de la variable peut être faite dans roles/group_vars/all ou dans roles/group_vars/all.yaml ou dans un fichier *.yaml dans le répertoire roles/group_vars/all/.

Exécutez la commande ansible-playbook :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web01]
ok: [web02]
ok: [web04]
ok: [web03]

TASK [debug : debug] ***********************************************************************************************************************************
ok: [web01] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web02] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web03] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web04] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}

PLAY RECAP *********************************************************************************************************************************************
web01                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web02                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web03                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web04                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

Important : La variable fixée dans group_vars/all.yaml surcharge la variable fixée dans defaults/main.yaml qui surcharge la variable fixée dans tasks/main.yaml.

Définissez la valeur de la variable endroit dans le fichier /home/trainee/.ansible/roles/playbook.yaml :

trainee@ansible:~/.ansible/roles$ vi playbook.yaml 
trainee@ansible:~/.ansible/roles$ cat playbook.yaml 
---
- hosts: all
  roles: 
    - { role: debug, endroit: 'playbook.yaml' }

Exécutez la commande ansible-playbook :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web02]
ok: [web01]
ok: [web03]
ok: [web04]

TASK [debug : debug] ***********************************************************************************************************************************
ok: [web01] => {
    "msg": "Ce message est issu de playbook.yaml"
}
ok: [web02] => {
    "msg": "Ce message est issu de playbook.yaml"
}
ok: [web03] => {
    "msg": "Ce message est issu de playbook.yaml"
}
ok: [web04] => {
    "msg": "Ce message est issu de playbook.yaml"
}

PLAY RECAP *********************************************************************************************************************************************
web01                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web02                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web03                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web04                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

Important : La variable fixée dans playbook.yaml surcharge la variable fixée dans group_vars/all.yaml qui surcharge la variable fixée dans defaults/main.yaml qui surcharge la variable fixée dans tasks/main.yaml.

Exécutez la commande ansible-playbook en définissant la valeur de la variable endroit sur la ligne de commande :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml -e 'endroit="la ligne de commande"'
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web03]
ok: [web02]
ok: [web04]
ok: [web01]

TASK [debug : debug] ***********************************************************************************************************************************
ok: [web01] => {
    "msg": "Ce message est issu de la ligne de commande"
}
ok: [web02] => {
    "msg": "Ce message est issu de la ligne de commande"
}
ok: [web03] => {
    "msg": "Ce message est issu de la ligne de commande"
}
ok: [web04] => {
    "msg": "Ce message est issu de la ligne de commande"
}

PLAY RECAP *********************************************************************************************************************************************
web01                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web02                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web03                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web04                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

Important : La variable fixée dans sur la ligne de commande surcharge la variable fixée dans playbook.yaml qui surcharge la variable fixée dans group_vars/all.yaml qui surcharge la variable fixée dans defaults/main.yaml qui surcharge la variable fixée dans tasks/main.yaml.

Créez maintenant le fichier /home/trainee/.ansible/roles/group_vars/group1.yaml :

trainee@ansible:~$ vi /home/trainee/.ansible/roles/group_vars/group1.yaml
trainee@ansible:~$ cat /home/trainee/.ansible/roles/group_vars/group1.yaml
---
endroit: 'group_vars/group1.yaml'

Créez ensuite le fichier /home/trainee/.ansible/roles/host_vars/localhost.yaml :

trainee@ansible:~$ mkdir /home/trainee/.ansible/roles/host_vars
trainee@ansible:~$ vi /home/trainee/.ansible/roles/host_vars/localhost.yaml
trainee@ansible:~$ cat /home/trainee/.ansible/roles/host_vars/localhost.yaml
---
# endroit: 'host_vars/localhost.yaml'

Modifiez le fichier /home/trainee/.ansible/roles/playbook.yaml :

trainee@ansible:~$ vi /home/trainee/.ansible/roles/playbook.yaml
trainee@ansible:~$ cat /home/trainee/.ansible/roles/playbook.yaml
---
- hosts: all
  roles: 
    - debug 

Modifiez ensuite le fichier inventory en ajoutant localhost :

trainee@ansible:~/.ansible/roles$ vi inventory
trainee@ansible:~/.ansible/roles$ cat inventory
localhost ansible_connection=local

[basededonnees]
web01

[dotcms]
web02
web03

[equilibrage]
web04

[debian:children]
basededonnees
dotcms
equilibrage

[debian:vars]
ansible_user=trainee

Vérifiez que les variables sont lues à partir du fichier all.yaml :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web01]
ok: [web02]
ok: [web03]
ok: [web04]
ok: [localhost]

TASK [debug : debug] ***********************************************************************************************************************************
ok: [localhost] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web01] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web02] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web03] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web04] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}

PLAY RECAP *********************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web01                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web02                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web03                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web04                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Important : Notez que la valeur de la variable endroit spécifiée dans le fichier group_vars/all.yaml s'applique à tous les groupes et à tous les hôtes.

Modifiez ensuite le fichier inventory en mettant localhost dans le group1 :

trainee@ansible:~/.ansible/roles$ vi inventory
trainee@ansible:~/.ansible/roles$ cat inventory
[group1]
localhost ansible_connection=local

[basededonnees]
web01

[dotcms]
web02
web03

[equilibrage]
web04

[debian:children]
basededonnees
dotcms
equilibrage

[debian:vars]
ansible_user=trainee

Exécutez de nouveau ansible-playbook :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [web03]
ok: [web01]
ok: [web02]
ok: [web04]
ok: [localhost]

TASK [debug : debug] ***********************************************************************************************************************************
ok: [localhost] => {
    "msg": "Ce message est issu de group_vars/group1.yaml"
}
ok: [web01] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web02] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web03] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web04] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}

PLAY RECAP *********************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web01                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web02                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web03                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web04                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

Important : La variable fixée dans group_vars/group1.yaml surcharge la variable fixée dans group_vars/all.yaml.

Modifiez le fichier /home/trainee/.ansible/roles/host_vars/localhost.yaml en décommentant la ligne 2 :

trainee@ansible:~$ vi /home/trainee/.ansible/roles/host_vars/localhost.yaml
trainee@ansible:~$ cat /home/trainee/.ansible/roles/host_vars/localhost.yaml
---
endroit: 'host_vars/localhost.yaml'

Exécutez la commande ansible-playbook :

trainee@ansible:~/.ansible/roles$ ansible-playbook -i inventory playbook.yaml
/home/trainee/.local/lib/python3.5/site-packages/ansible/parsing/vault/__init__.py:44: CryptographyDeprecationWarning: Python 3.5 support will be dropped in the next release of cryptography. Please upgrade your Python.
  from cryptography.exceptions import InvalidSignature

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [localhost]
ok: [web03]
ok: [web01]
ok: [web04]
ok: [web02]

TASK [debug : debug] ***********************************************************************************************************************************
ok: [localhost] => {
    "msg": "Ce message est issu de host_vars/localhost.yaml"
}
ok: [web01] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web02] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web03] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}
ok: [web04] => {
    "msg": "Ce message est issu de roles/group_vars/all.yaml"
}

PLAY RECAP *********************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web01                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web02                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web03                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
web04                      : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

Important : La variable fixée dans host_vars/localhost.yaml surcharge la variable fixée dans group_vars/group1.yaml qui surcharge la variable fixée dans group_vars/all.yaml.


<html>

Copyright © 2021 Hugh NORRIS

</html>

Menu