Outils pour utilisateurs

Outils du site


blog

Notes apache

Version
apachectl -v
 
Server MPM Mode
apachectl -V
 
Loaded Modules
apachectl -M
 
Compiled in modules
apachectl -l
 
Test Syntax
apachectl -t
 
Liste des vhosts
apache2ctl -S

Contexte variable environnent Apache.

grep -Pa -o 'TNS_ADMIN=[^\x00]*\x00' /proc/$(pgrep -o apache)/environ | sed -e 's/[^[:print:]]//g'

Rewrite

Exemple de conf

RewriteCond %{HTTP_HOST} =plop.acme.fr [NC,OR]
RewriteCond %{HTTP_HOST} =www.plop.acme.fr [NC]
RewriteRule .* https://acme.fr/plop [L,R=301]
 
 
### GARBAGE COLLECTOR ###
RewriteRule .* https://r.acme.fr/error_unavailable [L]

Perf

Voir :

Mem par process

ps -ylC httpd --sort:rss 

check allow and deny rules

2.2 configuration:

Order allow,deny
Allow from all

2.4 configuration:

Require all granted
# Require all denied

Hardening Apache

Ignorer dans les logs File does not exist: /var/www/favicon.ico

/etc/apache2/conf.d/nofavicon.conf

Redirect 404 /favicon.ico
<Location /favicon.ico>
ErrorDocument 404 "No favicon"
</Location>

Source : https://www.alouit-multimedia.com/02-assistance-informatique/tutoriaux/apache-en-finir-avec-les-erreurs-error-file-does-not-exist-favicon-ico/

Pb

Erreur FastCGI: comm with server - FastCGI: incomplete headers
2017-06-16T10:58:25.485 PCWEB1 err apache2[3253]: [fastcgi:error] [pid 3253:tid 140133122676480] [client 192.168.115.153:62059] FastCGI: comm with server "/PhpFpmVirtuel" aborted: idle timeout (30 sec)
2017-06-16T10:58:25.485 PCWEB1 err apache2[3253]: [fastcgi:error] [pid 3253:tid 140133122676480] [client 192.168.115.153:62059] FastCGI: incomplete headers (0 bytes) received from server "/PhpFpmVirtuel"

Si on n'y regarde de plus prêt, on voit dans le access.log, avant l'erreur :

2017-06-16T10:58:25.485 PCWEB1 debug access[3234]: 192.168.115.153 10:57:55.456 duration=30028931 (us) rec=893 (bytes) "POST /site/plop.php HTTP/1.1" 500 sent=763 (bytes)

Le pb vient que le script PHP /site/plop.php tombe en timeout : On constate que si la durée est inférieur à 30 secondes, c'est OK ⇒ ( 200 ). Si plus de 30s ⇒ erreur ( 500 )

grep plop.php /var/log/apache/access.log | sed -e 's/^.*duration=//' | sort -n | tail
 14777626 (us) rec=895 (bytes) "POST /site/plop.php HTTP/1.1" 200 sent=240 (bytes)
 15397927 (us) rec=892 (bytes) "POST /site/plop.php HTTP/1.1" 200 sent=240 (bytes)
 15993455 (us) rec=895 (bytes) "POST /site/plop.php HTTP/1.1" 200 sent=240 (bytes)
 17382090 (us) rec=892 (bytes) "POST /site/plop.php HTTP/1.1" 200 sent=240 (bytes)
 17850899 (us) rec=893 (bytes) "POST /site/plop.php HTTP/1.1" 200 sent=240 (bytes)
 30026574 (us) rec=898 (bytes) "POST /site/plop.php HTTP/1.1" 500 sent=763 (bytes)
 30027079 (us) rec=892 (bytes) "POST /site/plop.php HTTP/1.1" 500 sent=763 (bytes)
 30028931 (us) rec=893 (bytes) "POST /site/plop.php HTTP/1.1" 500 sent=763 (bytes)
 30029299 (us) rec=895 (bytes) "POST /site/plop.php HTTP/1.1" 500 sent=763 (bytes)
 30029900 (us) rec=898 (bytes) "POST /site/plop.php HTTP/1.1" 500 sent=763 (bytes)
[warn] //default// VirtualHost overlap on port 443, the first has precedence
# apachectl -t
[Mon Sep 14 14:31:10 2020] [warn] _default_ VirtualHost overlap on port 443, the first has precedence
Solution

Ajouter NameVirtualHost *:443

/etc/apache2/ports.conf

<IfModule mod_ssl.c>
    NameVirtualHost *:443
    # If you add NameVirtualHost *:443 here, you will also have to change
    # the VirtualHost statement in /etc/apache2/sites-available/default-ssl
    # to <VirtualHost *:443>
    # Server Name Indication for SSL named virtual hosts is currently not
    # supported by MSIE on Windows XP.
    Listen 443
</IfModule>
2025/03/24 15:06

Notes Ansible

Install et config

Install avec PIP

https://raw.githubusercontent.com/mrlesmithjr/ansible-samba/master/provision.sh

#!/bin/bash
sudo apt-get update
sudo apt-get install -y git python-pip python-dev
sudo pip install jinja2
sudo pip install ansible
sudo ansible-galaxy install -r /vagrant/requirements.yml -f
ansible-playbook -i "localhost," -c local /vagrant/playbook.yml
Doc

Voir ansible-doc. Exemple :

ansible-doc -t keyword -l
Inventaire

config

cp /etc/ansible/ansible.cfg ~/.ansible.cfg
mkdir ~/.ansible
cp /etc/ansible/hosts ~/.ansible/hosts.ini
 
sed -i -e 's%/etc/ansible/hosts%$HOME/.ansible/hosts.ini%' ~/.ansible.cfg
sed -i -e 's%#\(.*$HOME/\.ansible/hosts.ini\)%\1%' ~/.ansible.cfg
 
sed -i -e 's/^remote_port/#remote_port/' ~/.ansible.cfg
 
echo "localhost ansible_connection=local" >>  ~/.ansible/hosts.ini

Ou

/etc/ansible/ansible.cfg

[defaults]
host_key_checking = False
timeout = 60
vault_password_file = /var/lib/plop/ansible/vault/vault_pass.txt
ansible_managed = Ansible managed file, do not edit directly
filter_plugins = /var/lib/plop/ansible/filter_plugins/
lookup_plugins = /var/lib/plop/ansible/lookup_plugins/
library = /var/lib/plop/ansible/library/
remote_tmp = /tmp/.ansible
local_tmp = /tmp/.ansible
#allow_world_readable_tmpfiles = true
 
[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=30m -o UserKnownHostsFile=/dev/null
export ANSIBLE_CONFIG=$HOME/.ansible.cfg
ansible -i ~/.ansible/hosts.ini test -m ping

La connexion via SSH doit être configurée via ~/.ssh/config et via ssh-agent. Si besion :

ssh-agent -k
eval $(ssh-agent -s)
ssh-add 

Exemple de conf par variables

export ANSIBLE_ALLOW_EMBEDDED_TEMPLATES=false
export ANSIBLE_NOCOWS=true
export BECOME_ALLOW_SAME_USER=false
export ANSIBLE_PRIVATE_ROLE_VARS=true
export ANSIBLE_DISPLAY_ARGS_TO_STDOUT=true
export ANSIBLE_DISPLAY_TRACEBACK=always
export ANSIBLE_DUPLICATE_YAML_DICT_KEY=error
# export ANSIBLE_ENABLE_TASK_DEBUGGER=true
export ANSIBLE_HOST_PATTERN_MISMATCH=error
export ANSIBLE_INVENTORY_ANY_UNPARSED_IS_FAILED=true
export ANSIBLE_INVENTORY_UNPARSED_FAILED=true

Usage

Sudo / become

ansible-playbook -u user -kKb playbook.yml

Sur les serveurs distants

apt-get install python-minimal libpython-stdlib sudo

Traitements parallèles

Voir :

Exemple 1

ansible.cfg

[defaults]
strategy = free

Exemple 2

ansible -e serial_number=50 

Connexions

[arista]
eos ansible_host=192.168.2.10 ansible_connection=network_cli ansible_network_os=eos
 
[juniper]
junos ansible_host=192.168.2.20 ansible_connection=netconf ansible_network_os=junos

Autres

Lancer une commande

ansible all -a "free -m"

Lancer une commande bash (utilisation Pipe vars etc…)

ansible all -m shell -a "ifconfig | grep inet"

Connaître toutes les variables et les valeurs associées (Nom machine, mémoire, Version noyaux …)

ansible all -m setup

Lancer une commande simultanément sur plusieurs serveurs par lots de 2 machines -s pour sudo

ansible webservers -m service -a "name=nginx state=restarted" --forks=2 -s

Mode “noop” / “dry-run”

--check
ou --check--diff --limit foo.example.com

always_run: True sinon --check n’exécute pas les instructions du module shell,

lineinfile

A la place de lineinfile il existe aussi replace

Dépendance de rôles

Quand un rôle dépend d'un autre. \ Ici foo dépend de bar

roles/foo/meta/main.yml

---
allow_duplicates: no
dependencies:
  - role: bar

Exemple

Exemple

  • Découpage “role” un plusieurs morceaux (split role)
  • “when when”
  • Include dans un role
  • Action si fichier n'existe pas Si /etc/systemd/system/multi-user.target.wants/rpcbind.service n'existe pas faire : * systemctl add-wants multi-user.target rpcbind.service

/roles/nis_client/tasks/main.yml

---
- name: Include tasks
  ansible.builtin.include_tasks: "{{ ansible_os_family | lower }}.yml"

/roles/nis_client/tasks/debian.yml

---
  - name: Ubuntu lancer rpcbind avant NIS
    stat: path='/etc/systemd/system/multi-user.target.wants/rpcbind.service'
    register: systemdwants

  - name: DEBUG
    debug: msg="systemdwants = {{ systemdwants }}"

  - name: Ubuntu lancer rpcbind avant NIS 2
    command: systemctl add-wants multi-user.target rpcbind.service
    # when: systemdwants.stat.exists == False
    when: not systemdwants.stat.exists
    notify:
      - restart nis
Vérifier si un paquet deb est déjà installé

Source : http://chaosmail.github.io/programming/2015/03/04/install-deb-packages-in-ansible/

---

- name: Check if my_package is installed
  command: dpkg-query -W my_package
  register: my_package_check_deb
  failed_when: my_package_check_deb.rc > 1
  changed_when: my_package_check_deb.rc == 1
  check_mode: false

- name: copie du paquet my_package
  copy: src=my_package_linux.ubuntu14.04_x86-64.deb dest=/root/my_package_linux.ubuntu14.04_x86-64.deb
  changed_when: my_package_check_deb.rc == 1

- name: installation des dépendances
  apt: name=libacl1 state=present
  changed_when: my_package_check_deb.rc == 1

- name: install du paquet
  apt: deb=/root/my_package_linux.ubuntu14.04_x86-64.deb
  changed_when: my_package_check_deb.rc == 1
Exemple de find shell
- name: /var/log/* readable by user process - find
  shell: 'find /var/log/ -not \( -perm /o=r -o -user process \)  -a -not \( -wholename "/var/log/btmp*" \)'
  changed_when: False
  always_run: True
  register: list_files_var_log_notreadable

- name: /var/log/* readable by user process - set
  file: mode="o+rX" dest={{ item }}
  #file: mode="0755" dest={{ item }}
  with_items:
    - "{{ list_files_var_log_notreadable.stdout.split('\n') }}"
  when: list_files_var_log_notreadable.stdout != ""
Exemples include role conditionnel

Exemple 1

- hosts: webservers
  roles:
     - { role: debian_stock_config, when: ansible_os_family == 'Debian' }

Exemple 2

- name: Enable local cache DNS
  include_role:
    name: acme.dns.enable_local_cache_dns
  vars:
    EVAR_BACKUP_NAME: postinstall
    host_func_excluded:
      - FOO
    # trigramme_appli: "{{ inventory_hostname[5:8] }}"
    trigramme_appli: "{{ ansible_hostname[5:8] }}"
  when: not trigramme_appli | lower in host_func_excluded | lower

Notes Ansible

Lancer l'action même si Check Mode (Dry Run) ''%%--check%%''

always_run is deprecated. Use check_mode = no instead

#always_run: true
check_mode: false

Parfois il est préférable de trouver une solution plus élégante. Par exemple :

- name: mkdir /san/label
  file: dest='/san/{{ item }}' state=directory
  with_items:
    #- '{{ list_label_ext4devs.stdout_lines }}'
    #- '{{ list_label_xfsdevs.stdout_lines }}'
    - '{{ list_label_ext4devs.stdout_lines | default() }}'
    - '{{ list_label_xfsdevs.stdout_lines  | default() }}'

Ici nous utilisons default() pour éviter une erreur à cause d'un champ vide

fatal: [plop1]: FAILED! => {"failed": true, "msg": "'dict object' has no attribute 'stdout_lines'"}
Ignorer si mode check (ne pas tester)

when: not ansible_check_mode

- name: activation service sysstat 1
  lineinfile: dest=/etc/default/sysstat line='ENABLED="false"' state=absent
  when: not ansible_check_mode
Exemple module command ne lancer qu'une seule fois une commande.
- name: newer autolock screen - do conf
  command: dbus-launch gsettings set org.gnome.desktop.lockdown disable-lock-screen true
  become: '{{ autologin_user }}'
  args:
    creates: /root/.ansible-jalon-disable-lock-screen

- name: newer autolock screen - jalon exist ?
  stat: path=/root/.ansible-jalon-disable-lock-screen
  register: p

- name: newer autolock screen - jalon touch
  file: path=/root/.ansible-jalon-disable-lock-screen state=touch
  # when: p.stat.exists == False
  when: not p.stat.exists

Gather_fact partiel

Grâce à gather_subset

play.yml

- name: Test
  hosts: all
  gather_subset: os_family

Copie de fichiers

Une alternative à M(copy)

- name: Download file from a file path
  # ansible.builtin.copy:
  ansible.builtin.get_url:
    url: file:///tmp/a_file.txt
    dest: /tmp/afilecopy.txt

Pb

becoming-an-unprivileged-user Err Failed to set permissions on the temporary...Not owner\nchown

Lors de l’exécution d’un playbook Ansible avec un sudo (become) faisant appel à un utilisateur non privilégié (ici « oracle »)

ansible -m ping -u user01 -i srv1,  all --become-user=oracle -b

Nous avons l’erreur suivante :

srv1 | FAILED! => {
    "msg": "Failed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user (rc: 1, err: chown: /var/tmp/ansible-tmp-1685976784.0795348-3077033-272077328342364/: Not owner\nchown: /var/tmp/ansible-tmp-1685976784.0795348-3077033-272077328342364/AnsiballZ_ping.py: Not owner\n}). For information on working around this, see https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user"
}

Apparemment cela concernerait que AIX.

Solution

La solution de contournement la plus simple à mettre en place est de définir à True la variable ansible_shell_allow_world_readable_temp

play1.yml

#!/usr/bin/ansible-playbook
 
#
#  ./play1.yml -u user01 -i srv1,
 
---

- name: test sudo oracle
  hosts: all
  gather_facts: false
  become: true
  become_user: oracle
  vars:
    ansible_shell_allow_world_readable_temp: true

  tasks:
    - name: command id
      command: id
      changed_when: false
      register: cmd_id

    - name: echo id
      debug:
        var: cmd_id
Remote copy does not support recursive copy of directory

Le module copy ne supporte pas les copies de répertoire (mode récursif). \ Le module synchronize est plus approprié. Dans notre exemple nous voulons copier srv1:/mnt/plop/ sur srv1:/tmp/

Note : peut-être que cela marche avec 'directory_mode'

- name: push omniplanar installer
  copy:
    src: /mnt/plop/
    dest: /tmp
    remote_src: True
    #directory_mode: True

Solution

- name: push plop
  synchronize:
    src: /mnt/plop/plop.run
    dest: /usr/local/bin/
    rsync_opts:
      - "--chmod=F755"
      - "--chown=root:staff"
  #delegate_to: "{{ inventory_hostname }}"
  use_ssh_args: true
Failed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user

Erreur

fatal: [aws-zbx1]: FAILED! => {"msg": "Failed to set permissions on the temporary files Ansible needs to create when becoming an unprivileged user (rc: 1, err: chown: changing ownership of '/var/tmp/ansible-tmp-1559124598.47-172527571991348/': Operation not permitted\nchown: changing ownership of '/var/tmp/ansible-tmp-1559124598.47-172527571991348/AnsiballZ_postgresql_db.py': Operation not permitted\n}). For information on working around this, see https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user"

Solution

~/.ansible.cfg

[defaults]
allow_world_readable_tmpfiles = true

ou

  vars:
    ansible_shell_allow_world_readable_temp: true

Voir https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user

sudo: no tty present and no askpass program specified

Solution de contournement (workaround) Source: https://github.com/ansible/ansible/issues/15297

  lineinfile:
    path: /etc/sudoers
    state: present
    insertafter: EOF
    line: '{{ ansible_user }} ALL=NOPASSWD:/usr/bin/rsync'

Solution 2 Source : https://github.com/ansible/ansible/issues/20769

Applique la perte de l'élévation de privilèges

Ajouter rsync_path: /usr/bin/rsync

  tasks:
    - name: Synchronization of src on the control machine to dest on the remote hosts
      synchronize: 
        src: /etc/hostname
        dest: /home/user
        rsync_path: /usr/bin/rsync
Pb No module named 'ansible'
$ ansible --version
Traceback (most recent call last):
  File "/usr/bin/ansible", line 34, in <module>
    from ansible import context
ModuleNotFoundError: No module named 'ansible'
Solution

Test

env PYTHONPATH=/usr/lib/python3/dist-packages ansible --version

Solution si test OK

~/.bashrc

# Fix bug Ansible : No module named 'ansible'
export PYTHONPATH=$PYTHONPATH:/usr/lib/python3/dist-packages
Err template error while templating string: Could not load "search": 'search'.
TASK [dns_update_resolv_conf : Remove immutable attribute] **************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The conditional check 'stat_resolv_conf.stat.attr_flags | search(\"i\")' failed. The error was: template error while templating string: Could not load \"search\": 'search'. String: {% if stat_resolv_conf.stat.attr_flags | search(\"i\") %} True {% else %} False {% endif %}. Could not load \"search\": 'search'\n\nThe error appears to be in '/home/jean/code/dns_update_resolv_conf/roles/dns_update_resolv_conf/tasks/main.yml': line 147, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Remove immutable attribute\n  ^ here\n"}
Solution

Change

when:
    - result | failed

By

when:
    - result is failed

Example :

- name: Remove immutable attribute
  become: true
  ansible.builtin.file:
    path: "{{ resolv_filepath }}"
    attributes: "-i"
  # when: stat_resolv_conf.stat.attr_flags | search("i")
  when: stat_resolv_conf.stat.attr_flags is search("i")
Pb passer un boolean ou des listes en extravars à Ansible
Solution

Passer par du JSON

--extra-vars '{"abc": false}'

--extra-vars '{"abc": ["elm",] }'

Test

Voir :

ansible-test sanity --list-tests
ansible-test sanity --docker
Molecule

Debug

env ANSIBLE_NOCOLOR=1 ansible-playbook -vvvvv

Voir le module debug

env ANSIBLE_DEBUG=1 ansible-playbook
Ansible-lint

Voir :

.ansible-lint

---

profile: null
exclude_paths:
  - test/playbook.yml
---
# Offline mode disables installation of requirements.yml and schema refreshing
offline: true

profile: production
exclude_paths:
  - .git/
  - .github/
  - .gitlab/
  - .cache/
warn_list:
  - var_naming
  - idiom
skip_list:
  - var-naming[no-role-prefix]
  # - yaml[trailing-spaces]
  - yaml[empty-lines]

.ansible-lint-ignore

roles/agent/defaults/main.yml var-naming[no-role-prefix]

Exeption :

Utiliser skip_ansible_lint

Exemple :

- name: Kustomize get image
  become: true
  become_user: "{{ user_k8s }}"
  ansible.builtin.shell:
    chdir: "{{ myhome }}/awx-operator"
    cmd: "{{ myhome }}/awx-operator/bin/kustomize build config/default"
  changed_when: false
  register: reg_image
  tags: skip_ansible_lint
Syntax

Voir :

  • ansible-playbook --syntax-check
  • Ansible-lint
Callback plugin

Boucle

with_items is replaced by loop and the flatten filter.

- name: with_items
  ansible.builtin.debug:
    msg: "{{ item }}"
  with_items: "{{ items }}"

- name: with_items -> loop
  ansible.builtin.debug:
    msg: "{{ item }}"
  loop: "{{ items | flatten(levels=1) }}"

Autres

ansible_python_interpreter=/home/user/network-automation/venv/bin/python
2025/03/24 15:06

Notes ansible-vault

Voir aussi :

  • SOPS

Ansible-vault pour crypto chiffrement

Définir la clef

Adding the vault password file option to the Ansible configuration

cat /dev/urandom  | tr -dc A-Za-z0-9 | head -c32 > ~/.ansible/.vault_pass
chmod 600 ~/.ansible/.vault_pass

~/.ansible.cfg

[defaults]
 
vault_password_file = $HOME/.ansible/.vault_pass

Changer le secret

mv ~/.ansible/.vault_pass ~/.ansible/.vault_pass.old
cat /dev/urandom  | tr -dc A-Za-z0-9 | head -c32 > ~/.ansible/.vault_pass
chmod 600 ~/.ansible/.vault_pass*
ansible-vault rekey --vault-password-file=~/.ansible/.vault_pass.old --new-vault-password-file=~/.ansible/.vault_pass $(find . -type f -name "*.mdp.yml")
 
# shred -u ~/.ansible/.vault_pass

Fichiers entièrement chiffrés - Full encrypted file

play-config-unvault.yml

    - name: Deploy decrypted configuration
      ansible.builtin.copy:
        content: "{{ lookup('ansible.builtin.unvault', '/tmp/plop.vault') }}"
        dest: /tmp/plop
        no_log: true
env ANSIBLE_VAULT_PASSWORD_FILE=key ./play-config-unvault.yml

Exemples

ansible-vault encrypt_string 'P@ssw0rd' --name 'mysql_pass_root'
mysql_pass_root: !vault |
          $ANSIBLE_VAULT;1.1;AES256
          31313332623736393962306239386565356536663533343665653565336265373265373166326565
          6166646561303163376336363834636633373538346632310a356166393237333865623863336133
          64343962336462356336303239663633316364393137633263366334376533303766393262653561
          6638303531626238630a613161663932376333633539656334336465383238623330393832666136
          6666

Pb

secret must be unicode or bytes, not ansible.parsing.yaml.objects.AnsibleVaultEncryptedUnicode

Dans notre exemple mysecret est une chaine chiffrée par ansible-vault

fatal: [remote]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{ mysecret | password_hash('sha512') }}): secret must be unicode or bytes, not ansible.parsing.yaml.objects.AnsibleVaultEncryptedUnicode"}
Solution

Source : https://gist.github.com/douglasmiranda/f21a4481d372ae54fcf4a6ff32249949

- name: "Create main user"
  user:
    name: "myuser"
    password: "{{ '%s' | format(mysecret) | password_hash('sha512') }}"
    # ...
2025/03/24 15:06

Notes ansible-pull

Voir :

# pull mode (suitable for automation)
$ ansible-pull -U https://git.example.com/ansible.git -i "$(hostname --short),"

# push mode (development)
$ ansible-playbook -i inventory ./playbook.yml --limit foo.example.com
2025/03/24 15:06

Notes Ansible Inventory

Voir :

Script pour gérer un inventaire - openstack-ansible :

Linter un fichier inventaire

ansible-lint inventory1.yml

yamllint inventory1.yml

ansible-inventory -i inventory1.yml -y --list > inventory2.yml

Print all variables for all hosts from the command line

ansible -i inventory/local -m debug -a "var=hostvars" all

Afficher les variables pour tous les hosts

ansible-inventory -i inventory.yml --graph --vars

Afficher les variables pour un host particulier

# En YAML
ansible-inventory -i inventory.yml -y --host server1
 
# En JSON
ansible-inventory -i inventory.yml --host server1

Plugin

$ ansible-doc -t inventory -l
advanced_host_list                  Parses a 'host list' with ranges
auto                                Loads and executes an inventory plugin specified in a YAML config
awx.awx.controller                  Ansible dynamic inventory plugin for the Automation Platform Controller
community.general.cobbler           Cobbler inventory source
community.general.gitlab_runners    Ansible dynamic inventory plugin for GitLab runners
community.general.icinga2           Icinga2 inventory source
community.general.linode            Ansible dynamic inventory plugin for Linode
community.general.lxd               Returns Ansible inventory from lxd host
community.general.nmap              Uses nmap to find hosts to target
community.general.online            Scaleway (previously Online SAS or Online.net) inventory source
community.general.opennebula        OpenNebula inventory source
community.general.proxmox           Proxmox inventory source
community.general.scaleway          Scaleway inventory source
community.general.stackpath_compute StackPath Edge Computing inventory source
community.general.virtualbox        virtualbox inventory source
community.general.xen_orchestra     Xen Orchestra inventory source
constructed                         Uses Jinja2 to construct vars and groups based on existing inventory
generator                           Uses Jinja2 to construct hosts and groups from patterns
host_list                           Parses a 'host list' string
ini                                 Uses an Ansible INI file as inventory source
script                              Executes an inventory script that returns JSON
toml                                Uses a specific TOML file as an inventory source
yaml                                Uses a specific YAML file as an inventory source

Playbook

Limiter l'inventaire en faisant une intersection

 hosts: "type_host:&{{ PLOP_LIMIT | default('all') }}"
Inventaire dynamique passé en extra-vars

play_roles_temp_inventory.yaml

#! /usr/bin/ansible-playbook
 
---

- hosts: localhost
  connection: local
  gather_facts: false

  tasks:
    - name: add hosts from extra-vars
      add_host:
        name: '{{ item }}'
        groups: building
      loop: "{{ hosts_list.split('\n') }}"
      changed_when: false

- hosts: building
  gather_facts: "{{ play_roles_gather_facts | default(false) | bool }}"
  tasks:
    - debug: msg="hosts_list={{ hosts_list | replace('\n',',') }}"
      run_once: true
      when: play_roles_debug | default(false) | bool

    - name: Include Ansible roles
      include_role:
        name: "{{ role_name }}"
      loop: "{{ play_roles }}"
      loop_control:
        loop_var: role_name
      when: play_roles is defined

Tower

Voir https://docs.ansible.com/ansible-tower/latest/html/administration/tipsandtricks.html#using-the-tower-cli-tool

awx-manage inventory_import --source=inventory/ \
  --inventory-name="My Tower Inventory"
 
awx-manage inventory_import --source=inventory/ \
  --inventory-name="My Tower Inventory" \
  --overwrite --overwrite-vars
 
mkdir -p inventory-directory/group_vars

Voir awx import

Autres

inventory_hostname et ansible_hostname

2025/03/24 15:06
blog.txt · Dernière modification : de 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki