stefan-engel
stefan-engel

Reputation: 13

Ansible search content of variable in another variable

I'm trying to check if the content of variable B is in variable ssl_certs. The following works, but gives me a warning:

[WARNING]: conditional statements should not include jinja2 templating delimiters such as {{ }} or {% %}.

Working playbook:

  vars:
    B: 'test-cert'

  tasks:

  - name: Collect bigip facts
    bigip_device_facts:
      provider: '{{ provider }}'
      gather_subset: ssl-certs
    register: ssl_certs

  - name: debug SSL cert exists
    debug:
      msg: "cert-test already exists"
    when: ssl_certs is search('{{B}}')

If I just add the content of B in search, I can get rid of the warning. But how do I search the content of one var being in another var for the conditional statement?

I have tried the following, which doesnt work as no exact match

when: "B == ssl_certs"

Thanks

Upvotes: 1

Views: 424

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68044

For example, given the line below is in the text stored in ssl_certs

         Subject: CN=Jane Doe, OU=Finance, O=test-cert, C=US

Jinja test in is the simplest way of testing whether the content of B is in the text stored in ssl_certs or not. The task below

    - debug:
        msg: cert-test already exists
      when: B in ssl_certs
      vars:
        B: test-cert

gives

  msg: cert-test already exists

The same result gives the Ansible test search

    - debug:
        msg: cert-test already exists
      when: ssl_certs is search(B)
      vars:
        B: test-cert

This test can be used to search for more details, .e.g

    - debug:
        msg: cert-test already exists
      when: ssl_certs is search(regex)
      vars:
        B: test-cert
        regex: 'Subject:(.*)O={{ B }}'

Upvotes: 2

Yayati Sule
Yayati Sule

Reputation: 1631

The when clause is a raw Jinja2 expression without double curly braces. You can try this code snippet. vars: B: 'test-cert'

  tasks:

  - name: Collect bigip facts
    bigip_device_facts:
      provider: '{{ provider }}'
      gather_subset: ssl-certs
    register: ssl_certs

  - name: debug SSL cert exists
    debug:
      msg: "cert-test already exists"
    when: ssl_certs in B 

Ansibles' parser parses the when conditional at runtime and since it is a raw jinja2 template we do not need to provide the '{{}}' of jinja2 templates.

Upvotes: 0

Related Questions