2017-03-28 88 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