Ansible:如何用with_items将同一变量传递给source和dest的index
问题:Ansible uri模块中用with_items给source和dest的index传递同一值失败
我尝试在Ansible的uri模块请求体里,把同一个值传递给source和dest的index字段,编写的Playbook代码如下:
- name: Add to servers ignore_errors: yes uri: url: "{{proto}}://{{newserver}}:{{port}}/_reindex" method: POST headers: Authorization: 'Basic ABCDEFGHI==' body: source : remote: host: "{{proto}}://{{oldserver}}:{{port}}" username: abc password: def index: "{{item}}" type: "_doc" dest: index: "{{item}}" type: "_doc" with_items: "{{jsoncontent.content[6:].splitlines()}}" delay: 5 body_format: json
运行时抛出如下错误:
{"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefined
The error appears to be in '/somefile/abc.yml: line 72, column 3, but may
be elsewhere in the file depending on the exact syntax problem }...ignoring
我推测是with_items的缩进位置不正确,尝试调整缩进但仍失败,请问如何实现将with_items的同一值传递给source和dest的index?
解决方案
问题核心是with_items的缩进层级错误:你把它嵌套在了body字段内部,属于uri模块的参数范畴,但with_items是Ansible的任务级循环控制,必须和name、uri这些任务属性同级,不能放在模块参数里。
修正后的Playbook代码如下:
- name: Add to servers ignore_errors: yes with_items: "{{jsoncontent.content[6:].splitlines()}}" uri: url: "{{proto}}://{{newserver}}:{{port}}/_reindex" method: POST headers: Authorization: 'Basic ABCDEFGHI==' body: source : remote: host: "{{proto}}://{{oldserver}}:{{port}}" username: abc password: def index: "{{item}}" type: "_doc" dest: index: "{{item}}" type: "_doc" delay: 5 body_format: json
调整后,with_items处于任务级别,每次循环时item变量会被正确赋值,source和dest的index就能获取到同一个循环值,解决变量未定义的问题。
内容的提问来源于stack exchange,提问作者nonoob
相关产品推荐
相关产品推荐

