diff --git a/roles/kubernetes/preinstall/defaults/main.yml b/roles/kubernetes/preinstall/defaults/main.yml index e215875179ae5331460a6c686c70cf50db1c467d..30ad182b39918c9847147d09c52214699370b37a 100644 --- a/roles/kubernetes/preinstall/defaults/main.yml +++ b/roles/kubernetes/preinstall/defaults/main.yml @@ -33,3 +33,16 @@ populate_inventory_to_hosts_file: true preinstall_selinux_state: permissive sysctl_file_path: "/etc/sysctl.d/99-sysctl.conf" + +etc_hosts_localhost_entries: + 127.0.0.1: + expected: + - localhost + - localhost.localdomain + ::1: + expected: + - localhost6 + - localhost6.localdomain + unexpected: + - localhost + - localhost.localdomain diff --git a/roles/kubernetes/preinstall/tasks/etchosts.yml b/roles/kubernetes/preinstall/tasks/etchosts.yml index 80456f3547e0cd1a5f149c7a160b7d56450fdcbb..57d82c71c0e20d20a7f25982dbabf03bcea4a1f9 100644 --- a/roles/kubernetes/preinstall/tasks/etchosts.yml +++ b/roles/kubernetes/preinstall/tasks/etchosts.yml @@ -22,18 +22,33 @@ - loadbalancer_apiserver is defined - loadbalancer_apiserver.address is defined -- name: Hosts | localhost ipv4 in hosts file - lineinfile: - dest: /etc/hosts - line: "127.0.0.1 localhost localhost.localdomain" - regexp: '^127.0.0.1.*$' - state: present - backup: yes +- name: Hosts | Retrieve hosts file content + slurp: + src: /etc/hosts + register: etc_hosts_content + +- name: Hosts | Extract existing entries for localhost from hosts file + set_fact: + etc_hosts_localhosts_dict: >- + {%- set splitted = (item | regex_replace('[ ]+', ' ')|regex_replace('#.+$')|trim).split( ' ') -%} + {{ etc_hosts_localhosts_dict|default({}) | combine({splitted[0]: splitted[1::] }) }} + with_items: "{{ (etc_hosts_content['content'] | b64decode).split('\n') }}" + when: + - etc_hosts_content.content is defined + - etc_hosts_localhost_entries.keys()|map('regex_replace', '(.*)', '^\\1 .*') | map('match', item) | list | length > 0 + +- name: Hosts | Update target hosts file entries dict with required entries + set_fact: + etc_hosts_localhosts_dict_target: >- + {%- set target_entries = etc_hosts_localhosts_dict.get(item.key, []) | difference(item.value.get('unexpected' ,[])) -%} + {{ etc_hosts_localhosts_dict_target|default({}) | combine({item.key: (target_entries + item.value.expected)|unique}) }} + with_dict: "{{ etc_hosts_localhost_entries }}" -- name: Hosts | localhost ipv6 in hosts file +- name: Hosts | Update (if necessary) hosts file lineinfile: dest: /etc/hosts - line: "::1 localhost6 localhost6.localdomain" - regexp: '^::1.*$' + line: "{{ item.key }} {{ item.value|join(' ') }}" + regexp: "^{{ item.key }}.*$" state: present backup: yes + with_dict: "{{ etc_hosts_localhosts_dict_target }}"