Loop Ansible através de número variável de Hostvars

Loop Ansible através de número variável de Hostvars

Estou tentando obter nomes de host e endereços IP de uma lista de hosts inserida pelo usuário e enviar essas informações para um servidor central. O principal problema que estou enfrentando é que o número de hosts pode variar consideravelmente. Por exemplo, na primeira execução, um usuário pode inserir 1 nome de host, na segunda execução, inserir 30 e na próxima, inserir 5. Quero poder usar um único manual, independentemente de o usuário inserir 1 ou 100 hosts.

Os nomes de host são coletados por meio de um prompt de "variável extra" quando um modelo do Ansible Tower é executado:

client_hosts: 'host1,host2'

que são referenciados no playbook:

- name: Gather client information
  hosts: 
  - "{{ client_hosts | default(omit) }}"  
  tasks:    
    - name: Grab client hostname
      shell: cat /etc/hostname
      register: client_hostname

    - name: Grab client IP address
      shell: hostname -i | sed -n '1 p'
      register: client_ip

e mais abaixo no manual, quero adicionar esses IPs + nomes de host a um arquivo em um servidor central específico (o nome de host do servidor não muda):

- name: Update server
  hosts: central.server  
  tasks:  
    - name: Update client host list
      lineinfile:
        path: /path/to/file
        line: "{{ hostvars['client_hosts']['client_ip'] }} - {{ hostvars['client_hosts']['client_hostname'] }}"

O procedimento acima funciona bem para um único host, mas como eu faria um loop através do registro de variáveis ​​quando mais de um host for especificado (por exemplo, client_hostname[1,2,*]?) e atualizaria o servidor com esses valores quando não sei como muitos hosts serão inscritos com antecedência?

Responder1

Existem três partes neste caso de uso: 1) Gerenciar o inventário, 2) Coletarnome_host_clienteecliente_ipe 3) Reportar ao servidor central.

1. Gerencie o estoque

Existem muitas opções sobre como gerenciar o estoque e coletarnome_host_clienteecliente_ip. Por exemplo, useAdicionando intervalos de hostsse você planeja criar centenas de hosts com nomes simples como host001, hosts002, ..., host999. Por exemplo, no inventário abaixo adicioneservidor_central, localhost para simplificar e cem hosts no grupoteste

shell> cat inventory/01-hosts 
central_server ansible_host=localhost

[test]
host[001:100]

[test:vars]
ansible_connection=ssh
ansible_user=admin
ansible_become=yes
ansible_become_user=root
ansible_become_method=sudo
ansible_python_interpreter=/usr/local/bin/python3.8

Teste brevemente o inventário

- hosts: all
  gather_facts: false
  tasks:
    - debug:
        var: ansible_play_hosts|length
      run_once: true

dar resumido

  ansible_play_hosts|length: '101'

Execute o comando abaixo se quiser exibir o inventário completo

shell> ansible-inventory -i inventory --list --yaml

Depois, há muitas opções de como selecionar os hosts. VerPadrões: segmentação de hosts e grupos. Por exemplo,limiteo inventário para hosts ou grupos específicos. Teste-o com o manual simples abaixo

shell> cat pb1.yml
- hosts: all
  gather_facts: false
  tasks:
    - debug:
        var: inventory_hostname

dar

shell> ansible-playbook -i inventory pb1.yml -l host001,host002

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

TASK [debug] *********************************************************************************
ok: [host001] => 
  inventory_hostname: host001
ok: [host002] => 
  inventory_hostname: host002

PLAY RECAP ***********************************************************************************
host001: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host002: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Use o plugin de inventárioconstruídose você quiser limitar o inventário a um grupo maior de hosts. Ver

shell> ansible-doc -t inventory constructed

Por exemplo, a variável extracontagem_hostsé usado no exemplo abaixo para criar o grupomeu grupocompreendendo hosts limitados pelo valor desta variável

shell> cat inventory/02-constructed.yml
plugin: constructed
strict: true
use_extra_vars: true
compose:
  my_group_count: count_hosts|default(0)
groups:
  my_group: inventory_hostname[-2:]|int < my_group_count|int

Teste-o

shell> ansible-playbook -i inventory pb.yml -e count_hosts=10 -l my_group

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

TASK [debug] *********************************************************************************
ok: [host001] => 
  ansible_play_hosts|length: '11'

PLAY RECAP ***********************************************************************************
host001: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Execute o comando abaixo se quiser exibir o inventário completo

shell> ansible-inventory -i inventory -e count_hosts=10 --list --yaml

Com a ajuda doconstruídoplugin, você pode criar condições complexas. Por exemplo, limite os hosts a um intervalo específico e crie o grupomeu_grupo2

shell> cat inventory/02-constructed.yml
plugin: constructed
strict: true
use_extra_vars: true
compose:
  my_group_count: count_hosts|default(0)
  my_group_start: start_hosts|default(0)
  my_group_stop: stop_hosts|default(0)
groups:
  my_group1: inventory_hostname[-2:]|int < my_group_count|int
  my_group2: inventory_hostname[-2:]|int >= my_group_start|int and
             inventory_hostname[-2:]|int < my_group_stop|int

Teste-o

shell> ansible-playbook -i inventory pb1.yml -e start_hosts=10 -e stop_hosts=15 -l my_group2

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

TASK [debug] *********************************************************************************
ok: [host010] => 
  inventory_hostname: host010
ok: [host011] => 
  inventory_hostname: host011
ok: [host012] => 
  inventory_hostname: host012
ok: [host013] => 
  inventory_hostname: host013
ok: [host014] => 
  inventory_hostname: host014

...

2. Coletenome_host_clienteecliente_ip

Você pode usar o móduloconfigurarou colete os fatos por conta própria. Por causa da portabilidadeconfigurardeveria ser preferido.

Veja o móduloconfigurarsobre como coletar fatos sobre hosts remotos. Por exemplo, o manual abaixo reúne fatos sobre omáquinaeredee cria as variáveisnome_host_clienteecliente_ip

shell> cat pb2.yml
- hosts: all
  gather_facts: false
    
  tasks:

    - setup:
        gather_subset:
          - machine
          - network

    - set_fact:
        client_hostname: "{{ ansible_hostname }}"
    - debug:
        var: client_hostname

    - debug:
        var: ansible_default_ipv4
    - debug:
        var: ansible_all_ipv4_addresses

    - set_fact:
        client_ip: "{{ ansible_all_ipv4_addresses|last }}"
    - debug:
        var: client_ip

dar

shell> ansible-playbook -i inventory -l host011 pb2.yml

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

TASK [setup] *********************************************************************************
ok: [host011]

TASK [set_fact] ******************************************************************************
ok: [host011]

TASK [debug] *********************************************************************************
ok: [host011] => 
  client_hostname: test_11

TASK [debug] *********************************************************************************
ok: [host011] => 
  ansible_default_ipv4: {}

TASK [debug] *********************************************************************************
ok: [host011] => 
  ansible_all_ipv4_addresses:
  - 10.1.0.61

TASK [set_fact] ******************************************************************************
ok: [host011]

TASK [debug] *********************************************************************************
ok: [host011] => 
  client_ip: 10.1.0.61

PLAY RECAP ***********************************************************************************
host011: ok=7    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

A estrutura e o formato dos fatos podem diferir entre os sistemas operacionais.


Você pode coletar os fatos por conta própria. Por exemplo, o manual abaixo

shell> cat pb3.yml
- hosts: all
  gather_facts: false
    
  tasks:

    - name: Grab client hostname
      command: cat /etc/hostname
      register: out
    - set_fact:
        client_hostname: "{{ out.stdout }}"
    - debug:
        var: client_hostname

    - name: Grab client IP address
      shell: hostname -i | sed -n '1 p'
      register: out
    - set_fact:
        client_ip: "{{ out.stdout|split|last }}"
    - debug:
        var: client_ip

dê rodando no Linux

shell> ansible-playbook -i inventory -l central_server pb3.yml

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

TASK [Grab client hostname] ******************************************************************
changed: [central_server]

TASK [set_fact] ******************************************************************************
ok: [central_server]

TASK [debug] *********************************************************************************
ok: [central_server] => 
  client_hostname: central_server

TASK [Grab client IP address] ****************************************************************
changed: [central_server]

TASK [set_fact] ******************************************************************************
ok: [central_server]

TASK [debug] *********************************************************************************
ok: [central_server] => 
  client_ip: 10.1.0.22

PLAY RECAP ***********************************************************************************
central_server: ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

A saída dos utilitários pode diferir entre os sistemas operacionais.


3) Reporte ao servidor central

Use Jinja para criar a estrutura. Execute a tarefa uma vez e delegue-a aoservidor_central

shell> cat pb4.yml
- hosts: all
  gather_facts: false
    
  tasks:

    - setup:
        gather_subset:
          - machine
          - network
    - set_fact:
        client_hostname: "{{ ansible_hostname }}"
        client_ip: "{{ ansible_all_ipv4_addresses|last }}"

    - copy:
        dest: /tmp/test_host_ip.txt
        content: |
          {% for host in ansible_play_hosts %}
          {{ hostvars[host]['client_hostname'] }} - {{ hostvars[host]['client_ip'] }}
          {% endfor %}
      run_once: true
      delegate_to: central_server

dar

shell> ansible-playbook -i inventory -l host011,host013 pb4.yml

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

TASK [setup] *********************************************************************************
ok: [host013]
ok: [host011]

TASK [set_fact] ******************************************************************************
ok: [host011]
ok: [host013]

TASK [copy] **********************************************************************************
changed: [host011 -> central_server(localhost)]

PLAY RECAP ***********************************************************************************
host011: ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host013: ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

O playbook criou o arquivo emservidor_central

shell> cat /tmp/test_host_ip.txt 
test_11 - 10.1.0.61
test_13 - 10.1.0.63

Utilize o móduloarquivo de linhase você deseja adicionar linhas ao arquivo. O manual abaixo é idempotente

shell> cat pb5.yml
- hosts: all
  gather_facts: false
    
  tasks:

    - setup:
        gather_subset:
          - machine
          - network
    - set_fact:
        client_hostname: "{{ ansible_hostname }}"
        client_ip: "{{ ansible_all_ipv4_addresses|last }}"

    - lineinfile:
        path: /tmp/test_host_ip.txt
        line: |-
          {{ hostvars[item]['client_hostname'] }} - {{ hostvars[item]['client_ip'] }}
      loop: "{{ ansible_play_hosts }}"
      run_once: true
      delegate_to: central_server

Não haverá alterações quando você executá-lo repetidamente nos mesmos hosts

shell> ansible-playbook -i inventory -l host011,host013 pb5.yml

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

TASK [setup] *********************************************************************************
ok: [host011]
ok: [host013]

TASK [set_fact] ******************************************************************************
ok: [host011]
ok: [host013]

TASK [lineinfile] ****************************************************************************
ok: [host011 -> central_server(localhost)] => (item=host011)
ok: [host011 -> central_server(localhost)] => (item=host013)

PLAY RECAP ***********************************************************************************
host011: ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host013: ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Novas linhas serão adicionadas ao arquivo se o playbook for executado em novos hosts


shell> ansible-playbook -i inventory -l central_server pb5.yml

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

TASK [setup] *********************************************************************************
ok: [central_server]

TASK [set_fact] ******************************************************************************
ok: [central_server]

TASK [lineinfile] ****************************************************************************
changed: [central_server] => (item=central_server)

PLAY RECAP ***********************************************************************************
central_server: ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

A nova linha foi anexada ao arquivo

shell> cat /tmp/test_host_ip.txt 
test_11 - 10.1.0.61
test_13 - 10.1.0.63
central_server - 10.1.0.184

Responder2

Você pode percorrer a variável client_hosts usando a diretiva with_items em seu manual. Você pode então fazer referência a cada host individual usando a variável item no loop.

Aqui está um exemplo de como você pode modificar seu manual para lidar com vários hosts:

- name: Gather client information
  hosts: "{{ client_hosts | default(omit) }}"  
  tasks:
    - name: Grab client hostname and IP address
      shell: |
        hostname -i | sed -n '1 p' > /tmp/client_ip
        cat /etc/hostname > /tmp/client_hostname
      register: gather_client_info
      become: true

    - name: Set client hostname and IP address as variables
      set_fact:
        client_hostname: "{{ hostvars[item]['gather_client_info'].stdout_lines[1] }}"
        client_ip: "{{ hostvars[item]['gather_client_info'].stdout_lines[0] }}"
      with_items: "{{ client_hosts | default(omit) }}"

- name: Update server
  hosts: central.server  
  tasks:
    - name: Update client host list
      lineinfile:
        path: /path/to/file
        line: "{{ client_ip }} - {{ client_hostname }}"
      with_items: "{{ client_hosts | default(omit) }}"

Este manual percorrerá cada host na variável client_hosts e reunirá o nome do host e o endereço IP usando o módulo shell. Em seguida, ele definirá esses valores como variáveis ​​usando o módulo set_fact. Finalmente, ele percorrerá a variável client_hosts novamente e usará o módulo lineinfile para atualizar o arquivo no servidor central com o nome do host e o endereço IP de cada host.

Espero que isto ajude.

informação relacionada