setting variable in a playbook from a jinjia2 snippet

Hi all is it possible assign variable built from jingia2 fragment to other variable in the playbook:

  • name: “list files in an archive”
    unarchive:
    src: /root/mybundle.zip
    dest: /opt
    list_files: yes
    remote_src: yes
    register: archive_content
    loop:

  • /root/mybundle.zip

  • /root/mybudle2.zip

  • name: “debug archive_content”
    debug:
    var: “{{ path }}”
    vars:
    path: "{% set output = %}
    {% for file in item.files %}
    {% if file | regex_search(‘.rpm$’) %}
    {{ output.append(item.dest ~ ‘/’ ~ file) }}
    {% endif %}
    {% endfor %}\

{% output %}"

I got the following error

fatal: [server2]: FAILED! => {“msg”: “template error while templating string: Encountered unknown tag ‘output’… String: {% set output = %}{% for file in item.files %}{% if file | regex_search(‘.rpm$’) %} {{ output.append(item.dest ~ ‘/’ ~ file) }}{% endif %} {% endfor %}{% output %}”}

regards

Luca

Sorry for the stupid question

solved with

  • name: “debug archive_content”
    debug:
    var: path
    vars:
    path: “{% set output = %}
    {% for file in item.files %}
    {% if file | regex_search(‘.rpm$’) %}
    {{ output.append(item.dest ~ ‘/’ ~ file) }}
    {% endif %}
    {% endfor %}
    {{ output }}”
    loop: “{{ archive_content.results|list }}”

Luca

Also, look at the set_fact module, I use this extensively!

Thanks for the tip Jon.

So if the variable was necessary in subsequent tasks I could use set_fact module rather than defining a variable in the scope of the task or play

do you mean something like…

 - name: "list files in an archive"
    unarchive:
      src: /root/mybundle.zip
      dest: /opt
      list_files: yes
      remote_src: yes
    register: archive_content
    loop:
      - /root/mybundle.zip
      - /root/mybudle2.zip

  • name: “adapts structure”
    set_fact:
    path: "{% if output is undefined %}\

{% set output = %}
{% endif %}\

{% for file in item.files %}
{% if file | regex_search(‘.rpm$’) %}
{{ output.append(item.dest ~ ‘/’ ~ file) }}
{% endif %}
{% endfor %}\

{% output %}"
loop: “{{ archive_content.results|list }}”

  • debug:

var: path

Unfortunately in this moment I can’t test the playbook…

Regards

Luca


Looks right to me :slight_smile:

Like you, however, I don’t have a way to test it right now!