在循环中的模板查找中使用item变量

时间:2019-04-04 14:12:29

标签: ansible templating

我正在努力迭代with_subelements并在通过item.0.id加载的模板文件中使用lookup('template',...)

在模板化期间似乎变量不可用。

# data:
grafana_app_data:
  pKWGOV9mk:
    boardFiles: [
      "server-ping.json.j2"
    ], 
    id: "2", 
    title: "SERVER"
  kju...

# working:
- name: debug merge result
  debug:
    msg: "{{item.0.id}} --- {{item.1}}"
  with_subelements:
    - "{{ grafana_app_data }}"
    - boardFiles

# not working:
- name: iterate over folders and create respective dashboards
  win_uri:
    url: '{{ grafana_app_external_url }}api/dashboards/db'
    validate_certs: false
    method: POST
    status_code: '200,409'
    headers:
      Accept:        'application/json'
      Content-Type:  'application/json'
      Authorization: '{{ grafana_app_authorization_header }}'
    body: "{{ lookup('template', 'dashboards/' + item.1 ) }}"
  with_subelements:
    - "{{ grafana_app_data }}"
    - boardFiles

win_uri始终返回并显示错误:

fatal: [....net]: FAILED! => {"msg": "The task includes an option with an
undefined variable. The error was: 'env' is undefined\n\nThe error appears
to have been in '/.../roles/...inject/tasks/main.yml': line 123, column 3,
but may\nbe elsewhere in the file depending on the exact syntax 
problem.\n\nThe offending line appears to be:\n\n\n- name: iterate over
folders and create respective dashboards\n  ^ here\n"}

有什么想法吗?

提前THX!

更新

找到了根本原因:用于模板化的我的文件是JSON文件。这意味着:

  1. 可能会出现“}}”
  2. 这些值有时已经包含“ {{...}}”,这意味着我必须使用不同的起始边界。
  3. 计划在ansible 2.8(https://github.com/ansible/ansible/pull/49711)中对lookup + template + variable_start / end_string进行支持,其外观应为:body: "{{ lookup('template', 'dashboards/' + item.1, variable_start_string='[%', variable_end_string='%]' ) }}"

THX !!!

1 个答案:

答案 0 :(得分:0)

您似乎没有定义grafana_app_external_urlgrafana_app_authorization_header