Internução
Esta Dica Surgiu A Partir de Uma Dúvida no Telegram da Linuxtips E é éttima para quem precisa trabalhar com inventários dinâmicos ou realiza modificaçes em seu arquivo de venventário.
Представьте себе Seguinte Cenário: Você Vosui UM Playbook Que Realiza Modificaeses no Seu Inventário como adicionar um novo хост , e durante a mesma execução do Playbook Precisa Que Este хост Реем-Адиционадо Седжа Левадо Эм Рассмотрим, пара UMA PROXAXIA задача OU роль Анкет
Para Melhor Ilustrar, Criei abaixo um arquivo de inventário e Um Playbook que simplesmente irá immprimir todos os Хозяева Do Inventário, Adicionar UM novo хост Чамадо Хост-03
E Depois Imprimir Novamente OS хозяева :
# hosts [all] host-01 host-02
# playbook.yml --- - hosts: localhost become: true connection: local tasks: - name: Print list of hosts in inventory ansible.builtin.debug: msg: "{{ item }}" loop: "{{ groups['all'] }}" - name: Add host to inventory ansible.builtin.lineinfile: line: host-03 path: ./hosts regexp: "^host-03" state: present - name: Print list of hosts in inventory ansible.builtin.debug: msg: "{{ item }}" loop: "{{ groups['all'] }}"
Vamos Exemare O Nosso Playbook com Ansible -Playbook -i Hosts Playbook.yml
, Copendo o seguinte resultado:
PLAY [localhost] ************************************************************************************************************************************************************ TASK [Gathering Facts] ****************************************************************************************************************************************************** ok: [localhost] TASK [Print list of hosts in inventory] ************************************************************************************************************************************* ok: [localhost] => (item=host-01) => { "msg": "host-01" } ok: [localhost] => (item=host-02) => { "msg": "host-02" } TASK [Add host to inventory] ************************************************************************************************************************************************ changed: [localhost] TASK [Print list of hosts in inventory] ************************************************************************************************************************************* ok: [localhost] => (item=host-01) => { "msg": "host-01" } ok: [localhost] => (item=host-02) => { "msg": "host-02" } PLAY RECAP ****************************************************************************************************************************************************************** localhost : ok=4 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Percebe que foi adicionado um novo хост Хост-03
(включительно, Você perceberá a nova ontrada no arquivo хозяева
), Porém na segunda Impressão, Ele Continua não Sendo Impresso? O Motivo Disso é Devido ao fato de que o ansible apenas carrega na memória o venpentário durante o início da execução do Playbook , Игнорандо Eventuais alterações no mesmo (включительно Para Inventários dinâmicos).
Mas a pergunta que fica é: ok, e se eu precisar que alterações no meu vencerio sejam à Quente, para continuidade na execução? Bom, Aí Temos Principalmente duas opções:
Opção A: Использовать O Módulo add_host
O módulo add_host
Подавать Para adicionarmos Хозяева Dinamicamente à execução do ansible, porém não persistidas no arquivo de vencentário. Podemos utilizá-lo, adicionando uma Задача Дополнительная ao nosso Playbook , Carregerando o хозяин Хост-03
Também NA Memória:
--- - hosts: localhost become: true connection: local tasks: - name: Print list of hosts in inventory ansible.builtin.debug: msg: "{{ item }}" loop: "{{ groups['all'] }}" - name: Add host to inventory file ansible.builtin.lineinfile: line: host-03 path: ./hosts regexp: "^host-03" state: present - name: Add host to inventory (memory) ansible.builtin.add_host: name: host-03 - name: Print list of hosts in inventory ansible.builtin.debug: msg: "{{ item }}" loop: "{{ groups['all'] }}"
O resultado da execução é o seguinte:
PLAY [localhost] ************************************************************************************************************************************************************ TASK [Gathering Facts] ****************************************************************************************************************************************************** ok: [localhost] TASK [Print list of hosts in inventory] ************************************************************************************************************************************* ok: [localhost] => (item=host-01) => { "msg": "host-01" } ok: [localhost] => (item=host-02) => { "msg": "host-02" } TASK [Add host to inventory file] ******************************************************************************************************************************************* changed: [localhost] TASK [Add host to inventory (memory)] *************************************************************************************************************************************** changed: [localhost] TASK [Print list of hosts in inventory] ************************************************************************************************************************************* ok: [localhost] => (item=host-01) => { "msg": "host-01" } ok: [localhost] => (item=host-02) => { "msg": "host-02" } ok: [localhost] => (item=host-03) => { "msg": "host-03" } PLAY RECAP ****************************************************************************************************************************************************************** localhost : ok=5 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Opção B: Используйте Metatask reware_inventory
Метатаски Сан -базовая атмосфера задачи Que Alteram o Comportamento Do Ansible Durante Sua execução. Вамос Адиционар Ума Делас Нет Носсо Playbook Após A Adição do nosso хост ao arquivo de inventário para que o mesmo seja Recarregado antes da nova impressão:
-------- - hosts: localhost become: true connection: local tasks: - name: Print list of hosts in inventory ansible.builtin.debug: msg: "{{ item }}" loop: "{{ groups['all'] }}" - name: Add host to inventory file ansible.builtin.lineinfile: line: host-03 path: ./hosts regexp: "^host-03" state: present - meta: refresh_inventory - name: Print list of hosts in inventory ansible.builtin.debug: msg: "{{ item }}" loop: "{{ groups['all'] }}"
PLAY [localhost] ************************************************************************************************************************************************************ TASK [Gathering Facts] ****************************************************************************************************************************************************** ok: [localhost] TASK [Print list of hosts in inventory] ************************************************************************************************************************************* ok: [localhost] => (item=host-01) => { "msg": "host-01" } ok: [localhost] => (item=host-02) => { "msg": "host-02" } TASK [Add host to inventory file] ******************************************************************************************************************************************* changed: [localhost] TASK [Print list of hosts in inventory] ************************************************************************************************************************************* ok: [localhost] => (item=host-01) => { "msg": "host-01" } ok: [localhost] => (item=host-02) => { "msg": "host-02" } ok: [localhost] => (item=host-03) => { "msg": "host-03" } PLAY RECAP ****************************************************************************************************************************************************************** localhost : ok=4 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Заключение
Neste Breve Artigo Nós Vimos Como O Ansible Lê Seu Inventário, E Como Podemos adicionar novos Хозяева Durante Sua execuucão para novas Задачи E Роли , Este Conhecimento Sendo Aplicável Tanto Para Inventários Dinâmicos Quanto Estáticos (ou quando nós Queremos manipular o nosso arquivo хозяев
).
Espero Que Tenham Curtido!
Оригинал: «https://dev.to/stefanomartins/recarregando-o-inventario-do-ansible-durante-a-execucao-5ghm»