Ansible
Fichiers de configuration
plusieurs lieux possible, défini par ordre de priorité * exemple : inventory = /etc/ansible/hostsforks = 5sudo_user = rootask_sudo_pass = Trueask_pass = Truegathering = implicitgather_subset = allroles_path = /etc/ansible/roleslog_path = /var/log/ansible.logvault_password_file = /path/to/vault_password_filefact_caching_connection =/tmppipelining = False
dossier de base USER
~/.ansible/ansible.cfg
.ansible
ll -R $HOME/.ansible*-rw-r--r-- 1 samik staff 19K 3 mai 11:31 /Users/samik/.ansible.cfg/Users/samik/.ansible:total 0drwx------ 2 samik staff 64B 12 aoû 18:30 cpdrwx------ 2 samik staff 64B 12 aoû 18:29 tmp/Users/samik/.ansible/cp:/Users/samik/.ansible/tmp:
.ansible.cfg
egrep -v "#|^$" /Users/samik/.ansible.cfg [defaults] inventory = $HOME/hosts remote_tmp = .ansible/tmp local_tmp = ~/.ansible/tmp nocows = 1 [inventory] [privilege_escalation] [paramiko_connection] [ssh_connection] [persistent_connection] [sudo_become_plugin] [selinux] [colors] [diff] head -20 /Users/samik/.ansible.cfg # Example config file for ansible -- https://ansible.com/ # ======================================================= # Nearly all parameters can be overridden in ansible-playbook # or with command line flags. Ansible will read ANSIBLE_CONFIG, # ansible.cfg in the current working directory, .ansible.cfg in # the home directory, or /etc/ansible/ansible.cfg, whichever it # finds first # For a full list of available options, run ansible-config list or see the # documentation: https://docs.ansible.com/ansible/latest/reference_appendices/config.html. [defaults] inventory = $HOME/hosts #library = ~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules #module_utils = ~/.ansible/plugins/module_utils:/usr/share/ansible/plugins/module_utils remote_tmp = .ansible/tmp local_tmp = ~/.ansible/tmp #forks = 5 #poll_interval = 0.001
adefini par variable
ANSIBLE_CONFIG
/etc/ansible
lieu du playbook
ansible.cfg
Commande
ansible-config
ansible-config usage: ansible-config [-h] [--version] [-v] {list,dump,view} ... ansible-config: error: the following arguments are required: action usage: ansible-config [-h] [--version] [-v] {list,dump,view} ... View ansible configuration. positional arguments: {list,dump,view} list Print all config options dump Dump configuration view View configuration file optional arguments: --version show program's version number, config file location, configured module search path, module location, executable location and exit -h, --help show this help message and exit -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging)
list
ansible-config list|head -20 ACTION_WARNINGS: default: true description: - By default Ansible will issue a warning when received from a task action (module or action plugin) - These warnings can be silenced by adjusting this setting to False. env: - name: ANSIBLE_ACTION_WARNINGS ini: - key: action_warnings section: defaults name: Toggle action warnings type: boolean version_added: '2.5' AGNOSTIC_BECOME_PROMPT: default: true description: Display an agnostic become prompt instead of displaying a prompt containing the command line supplied become method env: - name: ANSIBLE_AGNOSTIC_BECOME_PROMPT
view
ansible-config view|head -20 # Example config file for ansible -- https://ansible.com/ # ======================================================= # Nearly all parameters can be overridden in ansible-playbook # or with command line flags. Ansible will read ANSIBLE_CONFIG, # ansible.cfg in the current working directory, .ansible.cfg in # the home directory, or /etc/ansible/ansible.cfg, whichever it # finds first # For a full list of available options, run ansible-config list or see the # documentation: https://docs.ansible.com/ansible/latest/reference_appendices/config.html. [defaults] inventory = $HOME/hosts #library = ~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules #module_utils = ~/.ansible/plugins/module_utils:/usr/share/ansible/plugins/module_utils remote_tmp = .ansible/tmp local_tmp = ~/.ansible/tmp #forks = 5 #poll_interval = 0.001
adepend de l'emplacement
astuce pour localiser le fichier config pris en compte: ansible -v imac -m ping Using /Users/samik/.ansible.cfg as config file ...
fonctionnement
CLI
Exemple
ping
ansible all -m ping(test simple de fonctionnement)imackris | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname imackris: nodename nor servname provided, or not known", "unreachable": true}[WARNING]: Platform linux on host abacus is using the discovered Python interpreter at /usr/bin/python,but future installation of another Python interpreter could change this. Seehttps://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for moreinformation.abacus | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong"}[WARNING]: Platform linux on host kaisenlinux is using the discovered Python interpreter at/usr/bin/python, but future installation of another Python interpreter could change this. Seehttps://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for moreinformation.kaisenlinux | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong"}[WARNING]: Platform darwin on host imacpat is using the discovered Python interpreter at/usr/bin/python, but future installation of another Python interpreter could change this. Seehttps://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for moreinformation.imacpat | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong"}mbp | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host mbp port 22: Operation timed out", "unreachable": true}nexus | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host nexus port 2222: Operation timed out", "unreachable": true}ipadkris | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host ipadkris port 22: Operation timed out", "unreachable": true}
acommand
shell
debug
raw
apt
service
copy
idem scp
fetch
récupérer un fichier
gather facts
Playbook
nombreuses options : -i : inventory -l : limit > spécifier un/des groupes ou serveurs ou patterns -u : user -b : become > sudo -k : password de ssh (à éviter) -K : password du sudo -C : check > dry run -D : diff > afficher les différences avant/après les tasks (actions) --ask-vault : prompt pour le password vault --syntax-check : vérfier la syntax --vault-password-file : passer le vault password par un fichier -e : surcharger n'importe quelle variable -f : nombre de parallélisation -t : filtrer sur les tags (--skip-tags) --flush-cache : éviter l'utilisation du cache --step : une tâche à la fois (confirmation via prompt) --start-at-task : commencer à une tâche spécifiquement --list-tags : lister tous les tags rencontrés --list-tasks : liste les tâches qui vont être exécutées
Exécution
ansible-playbook exemple_playbook.ymlPLAY [copie du fichier master.gitconfig] *************************************************************************************TASK [Gathering Facts] *******************************************************************************************************[WARNING]: Platform linux on host kaisenlinux is using the discovered Python interpreter at /usr/bin/python, but futureinstallation of another Python interpreter could change this. Seehttps://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.ok: [kaisenlinux]ok: [localhost]TASK [copy] ******************************************************************************************************************changed: [kaisenlinux]ok: [localhost]PLAY [mise à jour des packets désirés brew] **********************************************************************************TASK [Gathering Facts] *******************************************************************************************************[WARNING]: Platform linux on host abacus is using the discovered Python interpreter at /usr/bin/python, but futureinstallation of another Python interpreter could change this. Seehttps://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for more information.ok: [abacus]ok: [kaisenlinux]fatal: [nexus]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host nexus port 2222: Operation timed out", "unreachable": true}fatal: [ipadkris]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ssh: connect to host ipadkris port 22: Operation timed out", "unreachable": true}TASK [homebrew] **************************************************************************************************************fatal: [abacus]: FAILED! => {"changed": false, "msg": "Failed to find required executable brew in paths: /usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/games:/sbin:/usr/sbin:/usr/local/sbin"}fatal: [kaisenlinux]: FAILED! => {"changed": false, "msg": "Failed to find required executable brew in paths: /usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/games:/sbin:/usr/sbin:/usr/local/sbin"}PLAY RECAP *******************************************************************************************************************abacus : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0ipadkris : ok=0 changed=0 unreachable=1 failed=0 skipped=0 rescued=0 ignored=0kaisenlinux : ok=3 changed=1 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0nexus : ok=0 changed=0 unreachable=1 failed=0 skipped=0 rescued=0 ignored=0
astructure
l'indentation est importante (python oblige !)
modules
Variable d'environnement
Documentation :https://docs.ansible.com/ansible/latest/user_guide/playbooks_environment.htmlObjectifs : Définir des variables d'environnement et utiliser un prompt * différents endroits pour définir les variables d'environnement * playbook * tasks
environment
- name: utilisation du module shell et command hosts: all environment: PATHLIB: "/var/lib/" tasks: - name: echo shell: echo $PATHLIB register: __output - name: print debug: var: __output * variable d'environnement de la machine ansible - name: echo shell: "echo {{ lookup('env', 'ENV') | default('stage', True) }}" register: __output - name: print debug: var: __output
prompt
* var prompt : interrogation de l'utilisateur vars_prompt: - name: nom tasks: - name: echo shell: "echo Salut {{ nom }}" register: __output - name: print debug: var: __output * avec phrase et valeur par défaut vars_prompt: - name: env prompt: "Quel est votre environnement ? prod/stage/dev" default: dev environment: ENV: "{{ env }}" tasks: - name: echo shell: "echo Salut $ENV" register: __output - name: print debug: var: __output * exemples:- name: utilisation du module shell et command hosts: all environment: PATHLIB: "/var/lib/" ENV: "{{ env }}" vars_prompt: - name: nom - name: env prompt: "Quel est votre environnement ? prod/stage/dev" default: dev tasks: - name: echo shell: echo $PATHLIB register: __output changed_when: false - name: print debug: var: __output - name: echo shell: "echo Salut $ENV" register: __output - name: print debug: var: __output
roles
initialisation
creer: un dossier roles executer: ansible-galaxy init monrole résultat: tree -a . └── monrole ├── defaults │ └── main.yml ├── files ├── handlers │ └── main.yml ├── meta │ └── main.yml ├── README.md ├── tasks │ └── main.yml ├── templates ├── tests │ ├── inventory │ └── test.yml ├── .travis.yml └── vars └── main.yml
Exemple1
Exemple2
ANSIBLE : Ex - Monitoring > node exporterObjectif : série de vidéo de mise en pratique autour du monitoringprometheus / grafana / node-exporter...étapes :1- installation node exporter2- installation de prometheus3- installation de grafana* travail sur 4 noeuds1- un de monitoring (prometheus/grafana)2- tous monitoré par node exporter* structure = inventory + playbook + role node exporterInformations des conteneurs : => /samik-debian-4 - 172.17.0.5 => /samik-debian-3 - 172.17.0.4 => /samik-debian-2 - 172.17.0.3 => /samik-debian-1 - 172.17.0.2
Configuration
Precedence des variables
ANSIBLE : Precedence des variables* 23 types / localisation : command line values (eg “-u user”) role defaults [1] inventory file or script group vars [2] inventory group_vars/all [3] playbook group_vars/all [3] inventory group_vars/* [3] playbook group_vars/* [3] inventory file or script host vars [2] inventory host_vars/* [3] playbook host_vars/* [3] host facts / cached set_facts [4] play vars play vars_prompt play vars_files role vars (defined in role/vars/main.yml) block vars (only for tasks in block) task vars (only for the task) include_vars set_facts / registered vars role (and include_role) params include params extra vars (always win precedence)ANSIBLE : Precedence des variables* exemple > role* default variable* group vars* host vars* variables de playbook* variables de roles* facts de roles (set_fact)* variable de cli
ainventaire/inventory
Résumé: * inventory = inventaire des machines et de leurs variables * élément éssentiel car il décrit votre infra :* vos serveurs* vos types de serveurs * deux types d'instances :* hosts* groupes * plusieurs formats :* ini = plat* yaml = plus homogène* json = pour manipuler * possiblité d'utiliser des patterns * inventory = * fichier d'inventaire* répertoire group_vars* répertoire host_vars
Grande ligne
Usage
ORCHESTRATION ET AUTOMATISATION
DEPLOYEMENT
CONFIGURATION
Path multiple
Sujet secondaire
Langage
YAML
JSON