Ansible: work with lines in file

hostname: gt
file /etc/resolv.conf
cat /etc/resolv.conf
options rotate
nameserver 192.168.1.21
nameserver 192.168.1.22
options timeout:1

Case 1

# remove line from file
ansible gt -m lineinfile -a 'dest=/etc/resolv.conf state=absent line="options timeout:1"'
gt | success >> {
«changed»: true,
«found»: 1,
«msg»: «1 line (s) removed»
}

cat /etc/resolv.conf
options rotate
nameserver 192.168.1.21
nameserver 192.168.1.22

Case 2

# add line to file
ansible gt -m lineinfile -a 'dest=/etc/resolv.conf state=present line="options timeout:10"'
gt | success >> {
«changed»: true,
«msg»: «line added»
}

cat /etc/resolv.conf
options rotate
nameserver 192.168.1.21
nameserver 192.168.1.22
options timeout:10

but if you run it again, you'll duplicate row:
options timeout:10
options timeout:10

See Case4 how to escape it.

Case 3

# replace line in file or add new line
ansible gt -m lineinfile -a 'dest=/etc/resolv.conf state=present regexp="timeout:10" line="options timeout:1"'
gt | success >> {
«changed»: true,
«msg»: «line replaced»
}

cat /etc/resolv.conf
options rotate
nameserver 192.168.1.21
nameserver 192.168.1.22
options timeout:1

Case 4

# replace line only if it exists
ansible gt -m lineinfile -a 'dest=/etc/resolv.conf state=present backrefs=yes regexp="timeout:1" line="options timeout:1"'
gt | success >> {
«changed»: false,
«msg»: ""
}

cat /etc/resolv.conf
options rotate
nameserver 192.168.1.21
nameserver 192.168.1.22
options timeout:1