9

What is the syntax within the regex_search() to match against a variable?

For below, vcsourcekit = 10, I want to match regex ^10. It doesn't evaluate the variable, rather interprets literally.

- name: Do something awesome
  vmware_guest:
  hostname: "{{ vcenterhostname }}"
  ...

 when:
      - item.key | regex_search('^(vcsourcekit)')
 with_dict: "{{ vmfacts.virtual_machines }}"

Thanks!

jacksonp
  • 151
  • 1
  • 3
  • 9

4 Answers4

7

Not the most beautiful thing but this works:

- item.key | regex_search('^' + vcsourcekit | string)

Without the cast to string, I get a cannot concatenate 'str' and 'int' objects on ansible 2.2.0.0 and I don't have time to update just now.

jscott
  • 24,484
  • 8
  • 79
  • 100
4

This concatenation works without casting :

when:
      - item.key | regex_search('^(' ~ vcsourcekit ~ ')')
 with_dict: "{{ vmfacts.virtual_machines }}"

(Tested in Ansible 2.5.6)

Timm
  • 41
  • 1
1

This code:

tasks:
- set_fact: 
    keytype: ed25519

- set_fact: 
    matchstring: ".*_{{ keytype }}_.*"

- debug:
    var: item
  with_fileglob: "/etc/ssh/ssh_host_*_key"
  when: not item is match(matchstring)

selects just /etc/ssh/ssh_host_ed25519_key which seems analogous to the OP's requirement. It seems that "match" requires a pattern that matches the whole string, hence the *. before and after that string to be matched.

Two separate "set_fact" stanzas are needed so that "keytype" is set before it is used.

The code works in Ansible 2.4.3.0 running on Debian 9 (Raspbian "Stretch").

My application required "not" in the "when" statement but it would not be needed to answer the original question.

For the OP, the critical statement would appear to be:

matchstring: "^vcsourcekit.*"

Clearly too late to help the OP but the approach might help someone else.

0

Personally I'd use something along the lines of

- item.key | regex_search('^%d' % vcsourcekit)

This is untested BTW. I'm also not sure if it's consitent with Ansible/Jinja2 best practice.

EDIT: One of these ( also untested ) might be more correct.

- item.key | regex_search('^{0}'.format(vcsourcekit))

- item.key | regex_search('^%d' | format(vcsourcekit))
Rory Browne
  • 101
  • 1