How to wrap long line of re pattern in Ansible playbook?

Writing a code for validating ipaddress, since ipaddr depends on python-netaddr, we can't guarantee target ansible server got it installed. The re is from "regular-expressions-cookbook", long but working well.

- name: validate cluster -> topology_source_ip
  fail:
    msg: "topology_source ({{topology_source_ip}}) is not a valid IP address."
  when:
    - topology_source_ip is not regex('(?i)^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}?(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$')
    - topology_source_ip is not regex('(?i)^(?:(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}|(?=(?:[A-F0-9]{0,4}:){0,7}?[A-F0-9]{0,4}$)(([0-9A-F]{1,4}:){1,7}|:)((:[0-9A-F]{1,4}){1,7}|:)?|(?:[A-F0-9]{1,4}:){7}:|:(:[A-F0-9]{1,4}){7})$')

I want to split long lines to "standard" lines (<=80 chars). I googled, but can't find a solution for wrapping a long re pattern in ansible playbook. Any idea?

In Python, it could be:

r=re.compile(
    r'^(?:(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}|(?=(?:[A-F0-9]{0,4}:){0,7}?'
    r'[A-F0-9]{0,4}$)(([0-9A-F]{1,4}:){1,7}|:)((:[0-9A-F]{1,4}){1,7}|:)?'
    r'|(?:[A-F0-9]{1,4}:){7}:|:(:[A-F0-9]{1,4}){7})$'
    ,re.IGNORECASE
)
r.match("c10d:100::24")

1 answer

  • answered 2020-03-25 14:11 Vladimir Botka

    Q: "A solution for wrapping a long re pattern."

    A: Try to concatenate strings. For example

      vars:
        regex1: '{{ "(?i)^(?:(?:25[0-5]|" +
                    "2[0-4][0-9]|" +
                    "[01]?[0-9][0-9]?)\.){3}?(?:25[0-5]|"  +
                    "2[0-4][0-9]|" +
                    "[01]?[0-9][0-9]?)$" }}'
        regex2: '{{ "(?i)^(?:(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}|" +
                    "(?=(?:[A-F0-9]{0,4}:){0,7}?[A-F0-9]{0,4}$)(([0-9A-F]{1,4}:){1,7}|" +
                    ":)((:[0-9A-F]{1,4}){1,7}|" +
                    ":)?|(?:[A-F0-9]{1,4}:){7}:|" +
                    ":(:[A-F0-9]{1,4}){7})$" }}'
      tasks:
        - name: validate cluster -> topology_source_ip
          fail:
            msg: "topology_source ({{topology_source_ip}}) is not a valid IP address."
          when:
            - topology_source_ip is not regex(regex1)
            - topology_source_ip is not regex(regex2)
    

    Q: "ipaddr depends on python-netaddr, we can't guarantee target ansible server got it installed."

    A: ipaddr requires python-netaddr on controller not on the remote host. The task below gives the same result

      tasks:
        - name: validate cluster -> topology_source_ip
          fail:
            msg: "topology_source ({{topology_source_ip}}) is not a valid IP address."
          when: not topology_source_ip|ipaddr