Ceci est une ancienne révision du document !


Version : 2021.01.

Dernière mise-à-jour : 2021/03/24 10:47

DOF501 - Installation d'Ansible

Contenu du Module

  • DOF501 - Installation d'Ansible
    • Contenu du Module
    • Qu'est-ce Ansible ?
    • LAB #1 - Installation d'Ansible
    • LAB #2 - Configuration de ssh et de sudo
      • 2.1 - ssh
      • 2.2 - sudo

Qu'est-ce Ansible ?

Ansible est un outil d'automatisation qui permet d'automatiser les installations et les configurations répétitives de logiciels de manière fiable en utilisant une bibliothèque ré-utilisable d'instructions.

Ansible :

  • est installé sur un contrôleur qui communique avec les machines cibles en utilisant le protocole SSH,
  • ne nécessite ni l'utilisation d'un agent ni l'utilisation d'un service sur les cibles,
  • utilise le langage YAML (Yet Aother Markup Language), plus simple que JSON, le code Ruby utilisé par Chef et le langage propriétaire de Puppet.

LAB #1 - Installation d'Ansible

Connectez-vous à la VM Ansible à partir de votre poste dans notre cloud :

trainee@traineeXX:~$ ssh -l trainee ansible

Pour obtenir la dernière version d'Ansible, il convient d'utiliser pip. Installez pip avec la commande suivante :

trainee@ansible:~$ su -
Mot de passe : fenestros
root@ansible:~# apt-get update
...
root@ansible:~# apt-get install python3-pip
...
root@ansible:~# pip3 -V
pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.5)
root@ansible:~# pip3 list
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
Brlapi (0.6.5)
chardet (2.3.0)
cryptography (1.7.1)
cupshelpers (1.0)
httplib2 (0.9.2)
idna (2.2)
keyring (10.1)
keyrings.alt (1.3)
louis (3.0.0)
pip (9.0.1)
pyasn1 (0.1.9)
pycrypto (2.6.1)
pycups (1.9.73)
pycurl (7.43.0)
pygobject (3.22.0)
pysmbc (1.0.15.6)
python-apt (1.4.0b3)
python-debian (0.1.30)
python-debianbts (2.6.1)
pyxdg (0.25)
reportbug (7.1.7)
requests (2.12.4)
SecretStorage (2.3.1)
setuptools (33.1.1)
six (1.10.0)
urllib3 (1.19.1)
wheel (0.29.0)
</Code>

<WRAP center round important 60%>
**Important** : Pip3 est le gestionnaire des paquets pour Python 3.5. La commande est disponible en tant que pip3 ou pip sous Linux, Mac et Windows(r).
</WRAP>

<WRAP center round important 60%>
**Important** : Notez que le mot de passe **fenestros** ne sera pas en clair.
</WRAP>

Utilisez ensuite pip pour installer Ansible :

<code>
trainee@ansible:~$ pip3 install ansible
Collecting ansible
  Downloading https://files.pythonhosted.org/packages/19/0c/03233fb2896c6e04c403c7950eec4e2e41bafc059320d95926a95cce2c69/ansible-3.1.0.tar.gz (31.1MB)
    100% |████████████████████████████████| 31.2MB 42kB/s 
Collecting ansible-base<2.11,>=2.10.5 (from ansible)
  Downloading https://files.pythonhosted.org/packages/ba/58/009ab5eccdac9f44c52cc50391d5c8b986bc6559e0d56f3cc558a779ca48/ansible-base-2.10.7.tar.gz (5.7MB)
    100% |████████████████████████████████| 5.7MB 224kB/s 
Collecting PyYAML (from ansible-base<2.11,>=2.10.5->ansible)
  Downloading https://files.pythonhosted.org/packages/64/c2/b80047c7ac2478f9501676c988a5411ed5572f35d1beff9cae07d321512c/PyYAML-5.3.1.tar.gz (269kB)
    100% |████████████████████████████████| 276kB 4.1MB/s 
Collecting cryptography (from ansible-base<2.11,>=2.10.5->ansible)
  Downloading https://files.pythonhosted.org/packages/08/31/c43f1e45b4a5ebac13ff038a3f167ba3c7432f6dc8683ea504f5af9265eb/cryptography-3.2.1-cp35-abi3-manylinux1_x86_64.whl (2.6MB)
    100% |████████████████████████████████| 2.7MB 496kB/s 
Collecting jinja2 (from ansible-base<2.11,>=2.10.5->ansible)
  Downloading https://files.pythonhosted.org/packages/7e/c2/1eece8c95ddbc9b1aeb64f5783a9e07a286de42191b7204d67b7496ddf35/Jinja2-2.11.3-py2.py3-none-any.whl (125kB)
    100% |████████████████████████████████| 133kB 7.4MB/s 
Collecting packaging (from ansible-base<2.11,>=2.10.5->ansible)
  Downloading https://files.pythonhosted.org/packages/3e/89/7ea760b4daa42653ece2380531c90f64788d979110a2ab51049d92f408af/packaging-20.9-py2.py3-none-any.whl (40kB)
    100% |████████████████████████████████| 40kB 7.4MB/s 
Collecting six>=1.4.1 (from cryptography->ansible-base<2.11,>=2.10.5->ansible)
  Downloading https://files.pythonhosted.org/packages/ee/ff/48bde5c0f013094d729fe4b0316ba2a24774b3ff1c52d924a8a4cb04078a/six-1.15.0-py2.py3-none-any.whl
Collecting cffi!=1.11.3,>=1.8 (from cryptography->ansible-base<2.11,>=2.10.5->ansible)
  Downloading https://files.pythonhosted.org/packages/6c/a6/1662485aee65761f09707220d9e847baac4a912d419ee0139a9de22f34c4/cffi-1.14.5-cp35-cp35m-manylinux1_x86_64.whl (401kB)
    100% |████████████████████████████████| 409kB 3.1MB/s 
Collecting MarkupSafe>=0.23 (from jinja2->ansible-base<2.11,>=2.10.5->ansible)
  Downloading https://files.pythonhosted.org/packages/6e/57/d40124076756c19ff2269678de7ae25a14ebbb3f6314eb5ce9477f191350/MarkupSafe-1.1.1-cp35-cp35m-manylinux1_x86_64.whl
Collecting pyparsing>=2.0.2 (from packaging->ansible-base<2.11,>=2.10.5->ansible)
  Downloading https://files.pythonhosted.org/packages/8a/bb/488841f56197b13700afd5658fc279a2025a39e22449b7cf29864669b15d/pyparsing-2.4.7-py2.py3-none-any.whl (67kB)
    100% |████████████████████████████████| 71kB 6.9MB/s 
Collecting pycparser (from cffi!=1.11.3,>=1.8->cryptography->ansible-base<2.11,>=2.10.5->ansible)
  Downloading https://files.pythonhosted.org/packages/ae/e7/d9c3a176ca4b02024debf82342dab36efadfc5776f9c8db077e8f6e71821/pycparser-2.20-py2.py3-none-any.whl (112kB)
    100% |████████████████████████████████| 112kB 7.6MB/s 
Building wheels for collected packages: ansible, ansible-base, PyYAML
  Running setup.py bdist_wheel for ansible ... /
done
  Stored in directory: /home/trainee/.cache/pip/wheels/08/3d/48/89f1f39b7102a8e4856b822a6d082e4466e3a690e77cbfd0dc
  Running setup.py bdist_wheel for ansible-base ... done
  Stored in directory: /home/trainee/.cache/pip/wheels/b8/d8/c6/d68cfd370b56798b9cc24d33e002dc73f3982bfdc4fd66541d
  Running setup.py bdist_wheel for PyYAML ... done
  Stored in directory: /home/trainee/.cache/pip/wheels/a7/c1/ea/cf5bd31012e735dc1dfea3131a2d5eae7978b251083d6247bd
Successfully built ansible ansible-base PyYAML
Installing collected packages: PyYAML, six, pycparser, cffi, cryptography, MarkupSafe, jinja2, pyparsing, packaging, ansible-base, ansible
Successfully installed MarkupSafe-1.1.1 PyYAML-5.3.1 ansible-3.1.0 ansible-base-2.10.7 cffi-1.14.5 cryptography-3.2.1 jinja2-2.11.3 packaging-20.9 pycparser-2.20 pyparsing-2.4.7 six-1.15.0

Consultez la version d'Ansible que vous avez installé :

trainee@ansible:~$ ansible --version
/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
ansible 2.10.7
  config file = None
  configured module search path = ['/home/trainee/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/trainee/.local/lib/python3.5/site-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 3.5.3 (default, Nov 18 2020, 21:09:16) [GCC 6.3.0 20170516]

Il existe un bug dans la version 3.5.3 de Python sous Debian 9. Ceci peut être corrigé en modifiant les lignes 109 et 117 dans le fichier /usr/lib/python3.5/weakref.py de la machine Ansible :

root@ansible:~# vi /usr/lib/python3.5/weakref.py
root@ansible:~# cat /usr/lib/python3.5/weakref.py
        ...
        #def remove(wr, selfref=ref(self)):
        def remove(wr, selfref=ref(self), _atomic_removal=_remove_dead_weakref):
        ...
                    #_remove_dead_weakref(d, wr.key)
                    _atomic_removal(d, wr.key)
        ...

Important : N'utilisez pas de tabulations. Pour aligner les lignes, utilisez des espaces.

LAB #2 - Configuration de ssh et de sudo

2.1 - ssh

Ansible a besoin d'une configuration par clef asymétrique avec la machine TargetA afin de fonctionner correctement. Dans cette configuration :

  • La machine Ansible envoie à la machine TargetA une requête d'authentification par clé asymétrique qui contient le module de la clé à utiliser,
  • La machine TargetA recherche une correspondance pour ce module dans le fichier des clés autorisés ~/.ssh/authorized_keys,
    • Dans le cas où une correspondance n'est pas trouvée, la machine TargetA met fin à la communication,
    • Dans le cas contraire la machine TargetA génère une chaîne aléatoire de 256 bits appelée un challenge et la chiffre avec la clé publique de la machine Ansible,
  • La machine Ansible reçoit le challenge et le décrypte avec la partie privée de sa clé. Il combine le challenge avec l'identifiant de session et chiffre le résultat. Ensuite il envoie le résultat chiffré à la machine TargetA.
  • La machine TargetA génère le même haché et le compare avec celui reçu de la machine Ansible. Si les deux hachés sont identiques, l'authentification est réussie.

Saisissez maintenant les commandes suivantes en tant que trainee dans la machine Ansible :

Important - Lors de la génération des clefs, la passphrase doit être vide.

root@ansible:~# exit
déconnexion
trainee@ansible:~$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/trainee/.ssh/id_rsa): 
Created directory '/home/trainee/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/trainee/.ssh/id_rsa.
Your public key has been saved in /home/trainee/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:JQNe6n1PZphil37Akn1uO5A8e/4MhhIAb99T70ffo8Y trainee@ansible.i2tch.loc
The key's randomart image is:
+---[RSA 2048]----+
|    . . .        |
|     + +         |
|      * o . .    |
|     o + O = .   |
|      . S.%.= . .|
|       . B=@ . .o|
|        . o+O ..+|
|         ..+oE...|
|           o++o  |
+----[SHA256]-----+
trainee@ansible:~$ ssh-keygen -t ecdsa
Generating public/private ecdsa key pair.
Enter file in which to save the key (/home/trainee/.ssh/id_ecdsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/trainee/.ssh/id_ecdsa.
Your public key has been saved in /home/trainee/.ssh/id_ecdsa.pub.
The key fingerprint is:
SHA256:Ir3cEmFZND2AyFqQ2n65dXOPlSAB1BzzkzR3ViI+OYc trainee@ansible.i2tch.loc
The key's randomart image is:
+---[ECDSA 256]---+
|  .+ oo*B+o o +..|
|  . + .o+=o= * . |
| o o  +  .+.E .  |
|. o  o .. .. +   |
| .  ..+ S. . .   |
|  . oo.=o . o    |
|   . o+..o +     |
|    .  .  . .    |
|                 |
+----[SHA256]-----+
trainee@ansible:~$ ssh-keygen -t ed25519
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/trainee/.ssh/id_ed25519): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/trainee/.ssh/id_ed25519.
Your public key has been saved in /home/trainee/.ssh/id_ed25519.pub.
The key fingerprint is:
SHA256:HGNyqw1PwiaV9LOHg2oYFNasG8T67jTKdv+Hw/bnprQ trainee@ansible.i2tch.loc
The key's randomart image is:
+--[ED25519 256]--+
| .oo  .          |
| .o.o. o         |
| o..  + B        |
|..o  o * B       |
| ..o. * S .      |
|  oo + B o       |
| .+ o o +.       |
|.+.+   =...o     |
|ooo ..o.+E=.     |
+----[SHA256]-----+

Important - Les clés générées seront placées dans le répertoire ~/.ssh/.

Créez ensuite le fichier ~/.ssh/authorized_keys :

trainee@ansible:~$ cat .ssh/id_rsa.pub >> .ssh/authorized_keys
trainee@ansible:~$ cat .ssh/id_ecdsa.pub >> .ssh/authorized_keys
trainee@ansible:~$ cat .ssh/id_ed25519.pub >> .ssh/authorized_keys
trainee@ansible:~$ cat .ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC9VrGLpJsdvewBkI8caRwQq55N5CSTYaz7THUauaWTZYmSZmod3IBsUzJM/+FOzhkD5jgIJknoOnw0zwg6IINl6H8TbCg10gR0tdVvZF1IaOEG1gv6a5AkG4UWWgEh68+lPan5wNTCIyTyNtbK0oFzhtubibYKPtEbDTWbhQbH2vN4ZfW/0I+qGBbEgWXTLVvpwYu84ZjM0+EDiK/BbeDLYLtKEwunifEr9Ze3LF7CIZXyWYVkwhbkMyEsMUGinbtOTC3hX3Vlj234Cz4hbBRM5aXgjwy2EFLU/hwGeD3eaaqdhXyC35Ie6Nl36q/bAK63m3WAyDF/H2hT5600y6G9 trainee@ansible.i2tch.loc
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBL6zYXgOcA/uOlUawI25deR/y4jGxHyehSvHGnfbGDkNloS1TLfPbwde1lVrOjRPdWyKZHQr5viluwGaGzfmzPs= trainee@ansible.i2tch.loc
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIP2fCTH0bwFFG0DVWwZm7jGBdIVRSP+SjQzrgX/1Zcb9 trainee@ansible.i2tch.loc

Il convient maintenant de se connecter sur la machine TargetA en utilisant ssh et de vérifier la présence du répertoire ~/.ssh :

En saisissant cette commande, vous obtiendrez une fenêtre similaire à celle-ci :

trainee@ansible:~$ ssh -l trainee targeta.i2tch.loc
The authenticity of host 'targeta.i2tch.loc (10.0.2.52)' can't be established.
ECDSA key fingerprint is SHA256:sEfHBv9azmK60cjqF/aJgUc9jg56slNaZQdAUcvBOvE.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'targeta.i2tch.loc,10.0.2.52' (ECDSA) to the list of known hosts.
Debian GNU/Linux 9
trainee@targeta.i2tch.loc's password: 
Linux targeta.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: Sun Mar 21 13:34:13 2021 from 10.0.2.17

trainee@targeta:~$ ls -la | grep ssh
drwx------  2 trainee trainee  4096 janv. 28  2019 .ssh

trainee@targeta:~$ exit
déconnexion
Connection to targeta.i2tch.loc closed.

Important - Si le dossier distant .ssh n'existe pas dans le répertoire personnel de l'utilisateur connecté, il faut le créer avec des permissions de 700.

Important : Notez que le mot de passe trainee ne sera pas en clair.

Ensuite, il convient de transférer le fichier .ssh/authorized_keys de la machine Ansible vers la machine TargetA :

trainee@ansible:~$ scp .ssh/authorized_keys trainee@targeta.i2tch.loc:/home/trainee/.ssh/authorized_keys
Debian GNU/Linux 9
trainee@targeta.i2tch.loc's password: trainee
authorized_keys                                                                                                                        100%  701   994.8KB/s   00:00 

Important : Notez que le mot de passe trainee ne sera pas en clair.

Connectez-vous via ssh de la machine Ansible à la machine TargetA :

trainee@ansible:~$ ssh -l trainee targeta.i2tch.loc
Debian GNU/Linux 9
Linux targeta.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 11:41:12 2021 from 10.0.2.50

Important : Notez que l'authentification a utilisé le couple de clefs asymétrique et aucun mot de passe n'a été requis.

2.2 - sudo

La commande sudo permet à un utilisateur autorisé d'exécuter une commande en tant que root ou en tant qu'un autre utilisateur. Lors de l'exécution de la commande, l'UID et le GID effectifs et réels sont ceux de l'identité de l'utilisateur cible. L'utilisation de la commande sudo est une façon simple de déléguer des tâches administratives à d'autres utilisateurs sans communiquer le mot de passe de root et sans placer un SUID bit sur l'exécutable. La commande sudo est configurée grâce au fichier /etc/sudoers.

Consultez ensuite le fichier /etc/sudoers :

root@targeta:~# cat /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults	env_reset
Defaults	mail_badpass
Defaults	secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root	ALL=(ALL:ALL) ALL

# Allow members of group sudo to execute any command
%sudo	ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

Important : Notez la présence de la ligne %sudo ALL=(ALL) ALL. Cette ligne possède le format Qui Où = (En tant que qui) Quoi. La ligne implique donc que les membres du groupe sudo peuvent exécuter à partir de n'importe quel hôte et en tant que n'importe quel utilisateur, toutes les commandes du système. Dans ce fichier donc, un groupe est référencé par un %. Un nom sans ce caractère est forcément un utilisateur. Pour éditer le fichier /etc/sudoers, il est nécessaire d'utiliser la commande visudo.

Créez le fichier /etc/sudoers.d/ansible_users dans la VM targeta qui permettra à trainee d'utiliser la commande sudo sans entrer son mot de passe :

root@targeta:~# vi ansible_users
root@targeta:~# cat ansible_users
trainee ALL=(ALL)   NOPASSWD:ALL
root@targeta:~# chmod 440 ansible_users
root@targeta:~# mv ansible_users /etc/sudoers.d/
root@targeta:~# exit

Testez la prise en compte de vore configuration :

trainee@targeta:~$ sudo su -
root@targeta:~# exit
déconnexion
trainee@targeta:~$  

Important : Notez que trainee a pu exécuter la commande su - via sudo sans saisir son mot de passe.


<html>

Copyright © 2021 Hugh NORRIS.

</html>

Menu