filteransiblejinja2

Prepend every element of a list in ansible


I am looking to prepend a list of users with the netbios domain name and backslash. So far this is the best I can come up with:

- hosts: servers 
   vars:
    mylist: 
     - Alice
     - Bob 
     - Carol
    mystring: test
    mylist2: "{{ mylist | map('regex_replace', '^', mystring + '\' ) | list }}" 
  tasks:
   - debug: var=mylist2

Error message below:

The offending line appears to be:

mystring: test
mylist2: "{{ mylist | map('regex_replace', '^', mystring + '\' ) | list }}"
                                                            ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:

with_items:
  - {{ foo }}

Should be written as:

with_items:
  - "{{ foo }}"

I am facing an issue with concatenating a backslash to my variable because ansible thinks I am trying to escape something but haven't put what I want to escape. I have also tried to use a double backslash to no avail.

Can someone suggest what might work here or an alternative approach to this.


Solution

  • Simplify the expression and put the regex_replace parameters into variables. For example,

    - hosts: localhost
    
      vars:
    
        mylist: 
         - Alice
         - Bob 
         - Carol
        mystring: test
        mylist2: "{{ mylist |
                     map('regex_replace', _my_regex, _my_replace) |
                     list }}"
        _my_regex: '^(.*)$'
        _my_replace: '{{ mystring ~ "\\" ~ "\1" }}'
        # simlified option is below
        # _my_replace: '{{ mystring }}\\\1'
    
      tasks:
    
        - debug:
            var: mylist2
    

    gives probably what you want

      mylist2:
      - test\Alice
      - test\Bob
      - test\Carol
    

    Optionally, join the products. The below declaration gives the same result

      mylist2: "{{ [mystring] |
                   product(mylist) |
                   map('join', '/') }}"