2017-03-28 89 views
0

我试图调用一些REST API并对Ansible服务执行一些POST请求。由于正文(JSON)发生变化,我正在尝试对某些文件执行循环。这里是剧本:Ansible:循环文件做POST请求


- hosts: 127.0.0.1 
    any_errors_fatal: true 

    tasks: 
    - name: do post requests            
     uri: 
     url: "https://XXXX.com" 
     method: POST 
     return_content: yes 
     body_format: json 
     headers: 
      Content-Type: "application/json" 
      X-Auth-Token: "XXXXXX" 
     body: "{{ lookup('file', "{{ item }}") }}" 
     with_file: 
      - server1.json 
      - server2.json 
      - proxy.json 

但是当我运行的剧本,我得到这个错误:

the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'item' is undefined

问题出在哪里?

回答

1

主要问题是with_指令应该属于一个任务字典(一个缩进级别)。

的第二个问题是,你应该用文件查找请使用with_items,或者干脆"{{ item }}"with_files

- name: do post requests            
    uri: 
    url: "https://XXXX.com" 
    method: POST 
    return_content: yes 
    body_format: json 
    headers: 
     Content-Type: "application/json" 
     X-Auth-Token: "XXXXXX" 
    body: "{{ item }}" 
    with_files: 
    - server1.json 
    - server2.json 
    - proxy.json 

- name: do post requests            
    uri: 
    url: "https://XXXX.com" 
    method: POST 
    return_content: yes 
    body_format: json 
    headers: 
     Content-Type: "application/json" 
     X-Auth-Token: "XXXXXX" 
    body: "{{ lookup('file', item) }}" 
    with_items: 
    - server1.json 
    - server2.json 
    - proxy.json 

此外,{{ ... }}结构不是必需的方式来引用每个变量 - 它是一个构造,打开一个Jinja2表达式,在其中使用va riables。对于一个变量它确实变成了:{{ variable }},但一旦你打开它,你不需要再做了,所以它是完美的罚款写:

body: "{{ lookup('file', item) }}" 
+0

另外一个问题。你提供的解决方案工作正常,但现在我得到这个错误:无法找到(...内容的server1.json ...)在预期的路径。 json文件位于剧本的相同目录中,这里会出现什么问题? – SegFault

+0

查看更新的答案。 – techraf

+0

谢谢。现在更清楚了。 – SegFault