How to apply jinja2 filter to ansible list items?

EvilAmarant7x

I'm just trying to loop over a list of strings and replace text. But when I do this:

----
- hosts: all
  tasks:
  - debug: msg= {{ item | replace('a','b') }}
    with_items:
      - 'apple'
      - 'banana'
      - 'cookie'
      - 'dad'

the output is just

ok: [host] => (item=apple) => {
    "item": "apple", 
    "msg": ""
}
ok: [host] => (item=banana) => {
    "item": "banana", 
    "msg": ""
}
ok: [host] => (item=cookie) => {
    "item": "cookie", 
    "msg": ""
}
ok: [host] => (item=dad) => {
    "item": "dad", 
    "msg": ""
}

I was expecting all instances of the letter 'a' to be replaced with 'b'. I know it works if I just use {{'a' | replace('a','b')}}. So what's different about the list processing?

What I'm trying to do is parse a file, make some manipulations to the content on some lines, and then execute a command based off of the manipulated content.

I could do this all in a bash script very easily, but wanted to know how/if it was possible in the ansible scripting.

tedder42

You are really close to having it working.

First, debug is slightly fussy. If you have jinja code on the debug line it must be inside the msg= parameter, and it won't show right on the "task name" line. So, "apple" and "banana" will always look like that on the first line.

Second, it's important to quote things properly. If you had quoted the {{jinja}} or removed the space, it would have worked. In other words:

# bad
msg= {{jinja}}
# good
msg={{jinja}}
msg="{{jinja}}"

That's the only change necessary to make your code work. Here's the code:

- hosts: all
  tasks:
  - debug: msg={{ item | replace('a','b') }}
    with_items:
      - 'apple'
      - 'banana'
      - 'cookie'
      - 'dad'

And here's the output:

TASK: [debug msg={{ item | replace('a','b') }}] ******************************* 
ok: [localhost] => (item=apple) => {
    "item": "apple",
    "msg": "bpple"
}
ok: [localhost] => (item=banana) => {
    "item": "banana",
    "msg": "bbnbnb"
}
ok: [localhost] => (item=cookie) => {
    "item": "cookie",
    "msg": "cookie"
}
ok: [localhost] => (item=dad) => {
    "item": "dad",
    "msg": "dbd"
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related