onknows
onknows

Reputation: 6711

Format list of strings using Jinja2 filter with Ansible

I have a list similar to

my_apps:
  - bootstrap-client
  - theme-client
  - engine-client

I want to turn this array into a string similar to

$LOCAL_DIR/bootstrap-client-*.war $LOCAL_DIR/theme-client-*.war $LOCAL_DIR/engine-client-*.war

Is this possible using Jinja2 filters? In a Ansible template?

Upvotes: 1

Views: 1139

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39314

You can use the Ansible filter regex_replace in combination with the map and join filters to achieve this.

So so have to regex match the whole list item ^(.*)$ and back reference it using \\1 in your replacement.

Giving you:

"{{ my_apps | map('regex_replace', '^(.*)$', '$LOCAL_DIR/\\1-*.war' ) | join(' ') }}" 

Given the playbook:

- hosts: all
  gather_facts: yes

  tasks:
    - debug:
        msg: "{{ my_apps | map('regex_replace', '^(.*)$', '$LOCAL_DIR/\\1-*.war' ) | join(' ') }}" 
      vars:
        my_apps:
          - bootstrap-client
          - theme-client
          - engine-client

This yields:

PLAY [all] ********************************************************************************************************

TASK [debug] ******************************************************************************************************
ok: [localhost] => 
  msg: $LOCAL_DIR/bootstrap-client-*.war $LOCAL_DIR/theme-client-*.war $LOCAL_DIR/engine-client-*.war

PLAY RECAP ********************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Upvotes: 1

Related Questions