I am not sure if it's exactly what you want, but you could write the contents into a file using the lineinfile than replace everything except the nameservers from there, using the replace module. Like this:
- name: Check if resolv exists
stat:
path: /etc/resolv.conf
register: resolv_conf
- set_fact:
content: "{{ lookup('file', '/etc/resolv.conf') }}"
when: resolv_conf.stat.exists
- name: Write them into a file
lineinfile:
line: "{{ content }}"
create: yes
state: present
path: /tmp/resolv_conf_nameservers
- name: Remove everything but nameservers
replace:
path: /tmp/resolv_conf_nameservers
regexp: "^(?!nameserver).*$"
replace: ""
~
Please note that you should use set_fact to load contents into a variable.
If you want the file containing the nameservers to be placed in your own machine/localhost, use delegate_to in the last two tasks:
- name: Check if resolv exists
stat:
path: /etc/resolv.conf
register: resolv_conf
- set_fact:
content: "{{ lookup('file', '/etc/resolv.conf') }}"
when: resolv_conf.stat.exists
- name: Write them into a file
lineinfile:
line: "{{ content }}"
create: yes
state: present
path: /tmp/resolv_conf_nameservers
delegate_to: localhost
- name: Remove everything but nameservers
replace:
path: /tmp/resolv_conf_nameservers
regexp: "^(?!nameserver).*$"
replace: ""
delegate_to: localhost