2

我有一个 .json 文件,其中包含数百个 Axis 网络摄像机的配置值。内容如下所示:

          {
              "Name": "HTTPS.Port",
              "Value": "443"
          },
          {
              "Name": "Image.DateFormat",
              "Value": "YYYY-MM-DD"
          },
          {
              "Name": "Image.MaxViewers",
              "Value": "20"
          },

称为Vapix的 Axis API仅提供更新单个值的更新函数,因此我必须循环遍历这些值并在每次迭代时触发新的 API 调用:

    name: update parameters
  local_action:
    module: uri 
    user: x
    password: y
    url: "{{ axis_snmp_role.server_url }}?action=update&{{ item }}"
  with_items:
    - "SNMP.V2c=yes"
    - "SNMP.Enabled=yes"
    - "ImageSource.I0.Sensor.ExposureValue=100"

现在上面的例子需要我将数百个配置值硬编码到循环中。有没有办法告诉 Ansible 通过相机配置 json,通过新的 api 调用更新每个值,并在 json 文件中没有更多值时停止?

4

1 回答 1

3

Given the configuration's values is a list. For example

shell> cat data.yml 
config: [
  {"Name": "HTTPS.Port", "Value": "443"},
  {"Name": "Image.DateFormat", "Value": "YYYY-MM-DD"},
  {"Name": "Image.MaxViewers", "Value": "20"}]

The play

- hosts: localhost
  tasks:
    - include_vars:
        file: data.json
    - debug:
        msg: "?action=update&{{ item.Name }}={{ item.Value }}"
      loop: "{{ config }}"

gives

ok: [localhost] => (item={u'Name': u'HTTPS.Port', u'Value': u'443'}) => {
    "msg": "?action=update&HTTPS.Port=443"
}
ok: [localhost] => (item={u'Name': u'Image.DateFormat', u'Value': u'YYYY-MM-DD'}) => {
    "msg": "?action=update&Image.DateFormat=YYYY-MM-DD"
}
ok: [localhost] => (item={u'Name': u'Image.MaxViewers', u'Value': u'20'}) => {
    "msg": "?action=update&Image.MaxViewers=20"
}

If this is what you want loop the uri module. For example

- local_action:
  module: uri 
    user: x
    password: y
    url: "{{ axis_snmp_role.server_url }}?action=update&{{ item.Name }}={{ item.Value }}"
  loop: "{{ config }}"
于 2019-12-10T11:52:12.260 回答