clean up /etc/hosts file if populate_inventory_to_hosts_file is false (#10144)

* de-populate hosts file if populate_inventory_to_hosts_file is false

keep newline

* fix when condition
pull/10365/head
R. P. Taylor 2023-08-15 20:22:28 -07:00 committed by GitHub
parent 1955943d4a
commit cf3b3ca6fd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 23 additions and 26 deletions

View File

@ -1,32 +1,29 @@
---
- name: Hosts | update inventory in hosts file
when: populate_inventory_to_hosts_file
block:
- name: Hosts | create list from inventory
set_fact:
etc_hosts_inventory_block: |-
{% for item in (groups['k8s_cluster'] + groups['etcd'] | default([]) + groups['calico_rr'] | default([])) | unique -%}
{% if 'access_ip' in hostvars[item] or 'ip' in hostvars[item] or 'ansible_default_ipv4' in hostvars[item] -%}
{{ hostvars[item]['access_ip'] | default(hostvars[item]['ip'] | default(hostvars[item]['ansible_default_ipv4']['address'])) }}
{%- if ('ansible_hostname' in hostvars[item] and item != hostvars[item]['ansible_hostname']) %} {{ hostvars[item]['ansible_hostname'] }}.{{ dns_domain }} {{ hostvars[item]['ansible_hostname'] }} {% else %} {{ item }}.{{ dns_domain }} {{ item }} {% endif %}
- name: Hosts | create hosts list from inventory
set_fact:
etc_hosts_inventory_block: |-
{% for item in (groups['k8s_cluster'] + groups['etcd'] | default([]) + groups['calico_rr'] | default([])) | unique -%}
{% if 'access_ip' in hostvars[item] or 'ip' in hostvars[item] or 'ansible_default_ipv4' in hostvars[item] -%}
{{ hostvars[item]['access_ip'] | default(hostvars[item]['ip'] | default(hostvars[item]['ansible_default_ipv4']['address'])) }}
{%- if ('ansible_hostname' in hostvars[item] and item != hostvars[item]['ansible_hostname']) %} {{ hostvars[item]['ansible_hostname'] }}.{{ dns_domain }} {{ hostvars[item]['ansible_hostname'] }} {% else %} {{ item }}.{{ dns_domain }} {{ item }} {% endif %}
{% endif %}
{% endfor %}
delegate_to: localhost
connection: local
delegate_facts: yes
run_once: yes
{% endif %}
{% endfor %}
delegate_to: localhost
connection: local
delegate_facts: yes
run_once: yes
- name: Hosts | populate inventory into hosts file
blockinfile:
path: /etc/hosts
block: "{{ hostvars.localhost.etc_hosts_inventory_block }}"
state: present
create: yes
backup: yes
unsafe_writes: yes
marker: "# Ansible inventory hosts {mark}"
mode: 0644
- name: Hosts | populate inventory into hosts file
blockinfile:
path: /etc/hosts
block: "{{ hostvars.localhost.etc_hosts_inventory_block }}"
state: "{{ 'present' if populate_inventory_to_hosts_file else 'absent' }}"
create: yes
backup: yes
unsafe_writes: yes
marker: "# Ansible inventory hosts {mark}"
mode: 0644
- name: Hosts | populate kubernetes loadbalancer address into hosts file
lineinfile: