JMESPathTypeError 在 Ansible 中使用 json_query 过滤器和 starts_with 时出错

Yeh*_*paz 6 ansible boto3 jmespath

我正在尝试过滤从 Ansible 中的 boto3 到达的结果。

当我在没有“[?starts_with(...)]”的结果上使用 json 查询时,它运行良好,但是在添加 starts_with 语法时:

"state_machines[?starts_with(name,'hello')].state_machine_arn"
Run Code Online (Sandbox Code Playgroud)

为了过滤结果:

{u'boto3': u'1.4.4', u'state_machines': 
[{u'state_machine_arn': u'<state machine arn 1>', u'name': u'hello_world_sfn', u'creation_date': u'2017-05-16 14:26:39.088000+00:00'}, 
{u'state_machine_arn': u'<state machine arn 2>', u'name': u'my_private_sfn', u'creation_date': u'2017-06-08 07:25:49.931000+00:00'}, 
{u'state_machine_arn': u'<state machine arn 3>', u'name': u'alex_sfn', u'creation_date': u'2017-06-14 08:35:07.123000+00:00'}], 
u'changed': True}" }
Run Code Online (Sandbox Code Playgroud)

我希望得到第一个 state_machine_arn 值:“状态机 arn 1”

但相反,我得到了例外:

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: JMESPathTypeError: In function contains(), invalid type for value: <lamdba_name>, expected one of: ['array', 'string'], received: "unknown" fatal: [localhost]: FAILED!
=> {"failed": true, "msg": "Unexpected failure during module execution.", "stdout": ""}
Run Code Online (Sandbox Code Playgroud)

可能是什么问题?

fal*_*zer 11

问题是 json_query 过滤器期望得到一个带有 ascii 字符串的字典,但是你提供的是 unicode 字符串(注意u'blabla'你输入中的 )。

这是 json_query 的一个问题,显然是在 Ansible 2.2.1 中引入的(虽然不是很清楚),这里有更多细节:https : //github.com/ansible/ansible/issues/20379#issuecomment-284034650

我希望这在未来的版本中得到修复,但现在这是一个对我们有用的解决方法:

"{{ results | to_json | from_json | json_query(jmespath_query) }}"
Run Code Online (Sandbox Code Playgroud)

wherejmespath_query是包含starts_with查询的变量。这个往返 json 的技巧将 unicode 字符串转换为 ASCII 字符串 :)