From f6b72fa830259f883a47d0b76b3bdc7074e055c9 Mon Sep 17 00:00:00 2001
From: Matthew Mosesohn <mmosesohn@mirantis.com>
Date: Tue, 14 Mar 2017 21:02:00 +0300
Subject: [PATCH] Make resolvconf preinstall idempotent

---
 .../preinstall/tasks/resolvconf.yml           | 50 ++++++++++---------
 1 file changed, 26 insertions(+), 24 deletions(-)

diff --git a/roles/kubernetes/preinstall/tasks/resolvconf.yml b/roles/kubernetes/preinstall/tasks/resolvconf.yml
index 55edd0ca7..6369dfd9c 100644
--- a/roles/kubernetes/preinstall/tasks/resolvconf.yml
+++ b/roles/kubernetes/preinstall/tasks/resolvconf.yml
@@ -3,25 +3,16 @@
   command: cp -f /etc/resolv.conf "{{ resolvconffile }}"
   when: ansible_os_family in ["CoreOS", "Container Linux by CoreOS"]
 
-- name: Remove search/domain/nameserver options
-  lineinfile:
-    dest: "{{item[0]}}"
-    state: absent
-    regexp: "^{{ item[1] }}.*$"
-    backup: yes
-    follow: yes
-  with_nested:
-    - "{{ [resolvconffile] + [base|default('')] + [head|default('')] }}"
-    - [ 'search ', 'nameserver ', 'domain ', 'options ' ]
-  notify: Preinstall | restart network
-
-- name: Add domain/search/nameservers to resolv.conf
+- name: Add domain/search/nameservers/options to resolv.conf
   blockinfile:
     dest: "{{resolvconffile}}"
     block: |-
       {% for item in [domainentry] + [searchentries] + nameserverentries.split(',') -%}
       {{ item }}
       {% endfor %}
+      options ndots:{{ ndots }}
+      options timeout:2
+      options attempts:2
     state: present
     insertbefore: BOF
     create: yes
@@ -30,21 +21,32 @@
     marker: "# Ansible entries {mark}"
   notify: Preinstall | restart network
 
-- name: Add options to resolv.conf
-  lineinfile:
-    line: options {{ item }}
-    dest: "{{resolvconffile}}"
-    state: present
-    regexp: "^options.*{{ item }}$"
-    insertafter: EOF
+- name: Remove search/domain/nameserver options before block
+  replace:
+    dest: "{{item[0]}}"
+    regexp: '^{{ item[1] }}[^#]*(?=# Ansible entries BEGIN)'
     backup: yes
     follow: yes
-  with_items:
-    - ndots:{{ ndots }}
-    - timeout:2
-    - attempts:2
+  with_nested:
+    - "{{ [resolvconffile] + [base|default('')] + [head|default('')] }}"
+    - [ 'search ', 'nameserver ', 'domain ', 'options ' ]
+  when: item[0] != ""
   notify: Preinstall | restart network
 
+- name: Remove search/domain/nameserver options after block
+  replace:
+    dest: "{{item[0]}}"
+    regexp: '(# Ansible entries END\n(?:(?!^{{ item[1] }}).*\n)*)(?:^{{ item[1] }}.*\n?)+'
+    replace: '\1'
+    backup: yes
+    follow: yes
+  with_nested:
+    - "{{ [resolvconffile] + [base|default('')] + [head|default('')] }}"
+    - [ 'search ', 'nameserver ', 'domain ', 'options ' ]
+  when: item[0] != ""
+  notify: Preinstall | restart network
+
+
 - name: get temporary resolveconf cloud init file content
   command: cat {{ resolvconffile }}
   register: cloud_config
-- 
GitLab