postgresqlansiblepg-hba.conf

How to duplicate and modify lines in files


I need to update postgresql pg_hba.conf, I need to duplicate some lines, and modify these new lines.

As an example, I have these entries :

# On server 1
host    db1,db2     userA           10.10.10.10/32                  scram-sha-256
host    db1         user1           actual-dev-001.domain.local     scram-sha-256
host    db1,db2     user1,user2     actual-rec-004.domain.local     md5
host    db2         userB           another-001.domain.local        scram-sha-256
host    db4         user4           another-002.domain.local        scram-sha-256
# On server 2 
host    dbA         user1           actual-dev-001.domain.local     scram-sha-256
host    db1,db2     user1,user2     actual-rec-004.domain.local     md5
host    db1,db2     userA           10.10.10.10/32                  scram-sha-256
host    db3,db4     userC           10.10.10.11/32                  scram-sha-256
host    dbB         userB           another-003.domain.local        scram-sha-256
host    db4         userD           another-004.domain.local        scram-sha-256

for which I need to duplicate all the actual lines to future to obtain :

# On server 1
host    db1,db2     userA           10.10.10.10/32                  scram-sha-256
host    db1         user1           actual-dev-001.domain.local     scram-sha-256
host    db1         user1           future-dev-001.domain.local     scram-sha-256
host    db1,db2     user1,user2     actual-rec-004.domain.local     md5
host    db1,db2     user1,user2     future-rec-004.domain.local     md5
host    db2         userB           another-001.domain.local        scram-sha-256
host    db4         user4           another-002.domain.local        scram-sha-256
# On server 2 
host    dbA         user1           actual-dev-001.domain.local     scram-sha-256
host    dbA         user1           future-dev-001.domain.local     scram-sha-256
host    db1,db2     user1,user2     actual-rec-004.domain.local     md5
host    db1,db2     user1,user2     future-rec-004.domain.local     md5
host    db1,db2     userA           10.10.10.10/32                  scram-sha-256
host    db3,db4     userC           10.10.10.11/32                  scram-sha-256
host    dbB         userB           another-003.domain.local        scram-sha-256
host    db4         userD           another-004.domain.local        scram-sha-256

I've tested many combinations of ansible replace and lineinfile modules but failed to combine theses. I've also looked at the postgres_pg_hba module without success. Any hints or recommendations?


Solution

  • You can do this with sed:
    sed '/actual/{p;s/actual/future/g;}' pg_hba.conf

    Once you have checked that the output is good, just add -i to write to file:
    sed -i '/actual/{p;s/actual/future/g;}' pg_hba.conf