Hello, although this is an older thread, I came across it today while searching for a solution to also use lineinfile to edit multiple lines after a designated regex.
Apologies if this is not the right way to do it, (and if its a bad way, would love to see the "right" way to do it). But hey, I just needed to get it done and this one was a bit of a challenge.
Note the syntax to get around the YAML gotcha with the command below. Here's is what worked for me although disclaimer YMMV.
# idempotent using with multiline regex with register
- name: "Test for subjectAltName = IP in /etc/pki/tls/openssl.cnf"
command: 'grep "^subjectAltName = IP: {{ (ansible_eth0 | default(ansible_lo)).ipv4.address }}" /etc/pki/tls/openssl.cnf'
register: test_grep
failed_when: "'PLACEHOLDERHACK' in test_grep.stderr"
#ignore_errors: yes
- name: "modify SSL cert configuration add subjectAltName = IP to /etc/pki/tls/openssl.cnf"
lineinfile: 'dest=/etc/pki/tls/openssl.cnf regexp="^\[ v3_ca \]" state=present insertafter="^\[ v3_ca \]" line="[ v3_ca ]\nsubjectAltName = IP: {{ (ansible_eth0 | default(ansible_lo)).ipv4.address }}" backup=yes'
when: test_grep.stdout == ""
Idempotent result in edited file Where the nodes IP is '192.168.xx.xx':
Original target file was just the section:
[ v3_ca ]
Idempotent result (post multiple iterations) in edited target file then included section and the desired IP:
[ v3_ca ]
subjectAltName = IP: 192.168.xx.xx
Note that I actually had to modify the above code for our handling of virtual hosts running CentOS-7 as I was getting "ansible_eth0.ipv4.address is undefined" errors.
Were still running ansible 1.9.4, but I also tried upgrading to latest ansible version (as of 2016-02-35) version 2.x and still saw the problem.
Let me know if seeing the other workaround for handling dynamically named (and specific) network interfaces on CentOS-7 might be useful.