2

I want to generate a new list from files by prepending /auto and appending _sw_table to each element. While I can do this by explicitly mentioning the new strings as args to regex_replace in map, I want to achieve the same using variables. The following works:

- hosts: localhost
  gather_facts: no
  tasks:
  - set_fact:
      my_lst: []
      top_dir: /auto
      extra: sw_table
      files: ['/etc/passwd', '/etc/group']

  - set_fact:
      my_lst: "{{ files | map('regex_replace', '(.*)', '/auto\\1_sw_table') | list }}"

  - debug: var=my_lst

Output:

$ ansible-playbook -i localhost, ./test.yaml 

PLAY [localhost] **************************************************************************************************

TASK [set_fact] ***************************************************************************************************
ok: [localhost]

TASK [set_fact] ***************************************************************************************************
ok: [localhost]

TASK [debug] ******************************************************************************************************
ok: [localhost] => {
    "my_lst": [
        "/auto/etc/passwd_sw_table", 
        "/auto/etc/group_sw_table"
    ]
}

How can I use the variables top_dir and extra in the call to map to get the same result?

1 Answer 1

8

You can use string concatenation in Jinja2:

  - set_fact:
      my_lst: "{{ files | map('regex_replace', '(^.*$)', top_dir + '\\1' + extra) | list }}"

Do take note of the updated regex pattern that I used. I had different results to your output above, and needed to update the pattern.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.