如何将Ansible变量传递给JMESPath查询?
问题描述:
鉴于以下剧本:如何将Ansible变量传递给JMESPath查询?
---
- 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)]"
我想在ansible bar: ['dd','ee']
定义的变量传递给jmes_path查询像。不幸的是,这不起作用,脚本失败。
致命:[localhost]:FAILED! => {“failed”:true,“msg”:“字段 'args'的值无效([]),无法转换为 字典。错误为:期待:逗号,got:literal:解析错误列 28,token \“dd \”(LITERAL),用于表达式:\ n \“[?a =='cc'& &包含 ([u'dd',u'ee'],b )] \“\ n^\ n \ n错误 似乎在 '/home/vagrant/testnew/lieferschein-deployment/stack.yml'中:第16行,第 列第6列,但可能在其他位置\ n \ n任务:\ n - debug:\ n^here \ n“}
但是,在查询本身,内联像"[?a == 'cc' && contains (['dd','ee'],b)]"
定义列表,它的工作原理没有问题
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'}] "
}
是否有可能把一个Ansible变量到查询,如果是这样,怎么样?
答
变化:
bar: ['dd','ee']
到:
bar: "['dd','ee']"
否则,它被定义为一个对象,但你想要的字符串。
如果您已经定义的列表,你需要弯腰检查the documentation,找到一个合适的过滤器,并对其进行修改以满足您的需求:
要连接列表转换为字符串:
{{ list | join(" ") }}
这是有效的,但在真实的手册中我想使用定义在其他地方的变量。所以在这种情况下,我需要将其转换为字符串。 – user140547
因此,将其转换为字符串,有什么问题? – techraf
下次在写下“*鉴于以下剧本:*”时,你实际上希望读者忽略“给定的剧本”并阅读你的想法。 – techraf