Invalid license: Your evaluation license of RefinedTheme expired.

Ansible and CIDR


I've had a very frustrating time managing PostgreSQL's pg_hba.conf from Ansible.


PostgreSQL requires you to give a CIDR entry, so instead of

Ansible's internal variables have only the old notation available, and converting is not _that_ simple. At some time there was a network_to_cidr function, but it was never upstreamed.


The starting idea was to allow all clients on the local subnet to access the database.

It just turned out to not be straightforward at all, and the ansible ecosys has produced at least 3 approaches to this over the last years.

FYI: I'm using the ANXS PostgreSQL role (

I love when I find there's an ANXS module for something: They're a lot better than what you normally get in the ansible ecosys. Before finding it, I had tried a few others which didn't work well :-)

(Later I plan to migrate to ansible-pgpool which also doesn't look too shabby and solves a few special issues)


How to configure

Below you see how it will work. Basically, because the network_to_cidr filter wasn't merged upstream, you need a temporary variable that does the parsing.

In the next step you can access it and it'll be OK. If the prior step fails, it might render to "False" during the templating.

  - { type: host,  database: all, user: all, address: '::1/128',      method: '{{ postgresql_default_auth_method }}', comment: 'IPv6 local connections:' }
postgresql_pg_hba_passwd_hosts: []
postgresql_pg_hba_trust_hosts: []
# here's our magic
net_mask: "{{ }}/{{ ansible_default_ipv4.netmask }}"
net_cidr: "{{ net_mask | ipaddr('net') }}"
  - { type: host,  database: 'mydb', user: 'myuser', 
      address: "{{net_cidr}}",      method: 'md5', 
      comment: 'Access for Appservers' }


I've slapped the access control entries in the main vars section for now because this whole thing took so much time.