0

I generate a list of users members of a group:

"ansible_facts": {
    "adminsys_members": [
        "user1", 
        "user2", 
        "user3", 
    ], ...

And I want to use it as a string in a json_query filtering expression, but if I just write:

query: "[?contains( {{ adminsys_members }}, username)].authorized_keys"

I obtain (debug in execution):

"query": "[?contains( [u'ulvida', u'apias', u'cchoque', u'vtorterola', u'santiagomr4', u'victor'], username)].authorized_keys"

And then when I try to execute the json_query:

debug: 
  msg: "{{ users | json_query( query ) }}"

It fails with:

fatal: [ta.interior.edu.uy]: FAILED! => {
    "msg": "Error in jmespath.search in json_query filter plugin:\n'literal'"
}

When I manually define my query, with the appropriate syntax and quotes in list:

query: "[?contains( ['user1', 'user2', 'user3'], username)].authorized_keys"

It works ok.

I'm puzzled in building a filter that gives me the string:

['user1', 'user2', 'user3']

when I apply it to the list:

    "adminsys_members": [
        "user1", 
        "user2", 
        "user3", 
    ]

I think I'm not too far from this bug where the only solution I din't try is to define a new filter n python, and this bug, which only answer doesn't work.

Am I in a hell of impossible escaping of characters? Thanks in advance.

mdaniel
  • 31,240
  • 5
  • 55
  • 58
Ulvida
  • 25
  • 5

1 Answers1

0

You will need to take advantage of the "literal" syntax in JMESPath, to embed "raw" JSON into the query, and then ask jinja to render your list in a JSON-compliant way:

- debug:
    msg: "{{ users | json_query( query ) }}"
  vars:
    query: '[?contains(`{{ adminsys_members|to_json }}`, username)].authorized_keys'
mdaniel
  • 31,240
  • 5
  • 55
  • 58
  • It worked well for me! Thank you!! It also worked with escaped simple ticks '', instead of `. What was not acceptable was to have external double quotes. – Ulvida Jan 28 '19 at 23:01
  • Please consider marking the answer as accepted, to help others find both my approach and your comment on it (I didn't try escaping because I've had such good experiences with the literal syntax, but I can imagine circumstances under which your way can be easier) – mdaniel Jan 29 '19 at 05:44
  • Accepted (I didn't figure out how to accept it :) Thanks for your help in my newbe path! – Ulvida Jan 30 '19 at 13:06