1

Given the following playbook:

---
- name: "foo bar"
  hosts: localhost
  connection: local
  gather_facts: false
  vars:
    foo:
     -
       a: aa
       b: bb
     -
       a: cc
       b: dd

  tasks:
   - debug:
       msg: " filter {{foo}} to  {{ foo | json_query(query)}} "

     vars:
       bar:  ['dd','ee']
       query: "[?a == 'cc' && contains (['dd','ee'],b)]"
       #query: "[?a == 'cc' && contains ( {{bar}} ,b)]"

I would like to pass a variable defined in ansible bar: ['dd','ee'] to a jmes_path query like "[?a == 'cc' && contains ( {{bar}} ,b)]". Unfortunately, this does not work, the script fails.

fatal: [localhost]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value ([]), and could not be converted to an dict. Error was: Expecting: comma, got: literal: Parse error at column 28, token \"dd\" (LITERAL), for expression:\n\"[?a == 'cc' && contains ( [u'dd', u'ee'] ,b)]\"\n ^\n\nThe error appears to have been in '/home/vagrant/testnew/lieferschein-deployment/stack.yml': line 16, column 6, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - debug:\n ^ here\n"}

However, defining the list in the query itself, inline like "[?a == 'cc' && contains (['dd','ee'],b)]", it works without problems

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": " filter [{u'a': u'aa', u'b': u'bb'}, {u'a': u'cc', u'b': u'dd'}] to  [{u'a': u'cc', u'b': u'dd'}] "
}

Is it possible to put an Ansible variable into the query, and if so, how?

techraf
  • 64,883
  • 27
  • 193
  • 198
user140547
  • 7,750
  • 3
  • 28
  • 80

1 Answers1

4

Change:

bar:  ['dd','ee']

to:

bar: "['dd','ee']"

Otherwise it is defined as an object, but you want a string.


If you already have a list defined, you need to stoop to checking the documentation, find a proper filter and modify it to suit your needs:

To concatenate a list into a string:

{{ list | join(" ") }}
Community
  • 1
  • 1
techraf
  • 64,883
  • 27
  • 193
  • 198
  • this works, but in a real playbook I would like to use a variable defined somewhere else. So in this cases, I would need something to convert it to a string. – user140547 Mar 09 '17 at 13:07
  • So convert it to a string, what's the problem? – techraf Mar 09 '17 at 13:08
  • And next time make a clear statement when writing "*Given the following playbook:*" that you actually expect readers to ignore "the given playbook" and read your mind. – techraf Mar 09 '17 at 13:15
  • Well if I used a literal string, it would not provide much benefit over using the inline version. Anyway, converting to a string is not that simple, since it has to be exactly the same string as the inline version. I ended up with `"{{bar| to_json| replace ('\"',\"'\") }}"`. Anyway, thanks for the pointer – user140547 Mar 09 '17 at 14:00