Ansible 数组变量

问题描述 投票:0回答:1

我在 ansible 中使用数组时遇到问题

我的主机变量:

ivr:

  • id:1

    名称:“将军”

    公告:“通用-ES”

    目的地:

    • 选项:“t”

      id_目的地:10000

      输入:“队列”

    • 选项:“我”

      id_目的地:10000

      输入:“队列”

我的任务:

  • 名称:Creamos el ivr si no Existe

    乌里:

    url:“http://{{ ansible_host }}:{{ api_port }}/ivr/create”

    方法:POST

    标题:

    Content-Type: "application/json"
    
    Authorization: "Bearer {{ result_post_token.json.token }}"
    

    返回内容:是

    正文格式:json

    主体:'{

    "name": "{{ item.name }}",
    
    "announcement" : "{{ item.announcement }}",
    
    "dests" : {
    
      "{{ item.dests.option }}":{
    
          "type": "{{ item.dests.type }}",
    
          "id": "{{ item.dests.id }}"
    
      },
    
    },
    

    }'

    状态代码:201

    超时:30

当我运行剧本时,它返回一个错误,指出“item.dests.option”不存在。

这是一个测试示例,最后目标的数量可能会有所不同,这就是为什么我需要使用将身体与所有目标组装在一起的东西

有人可以帮助我正确定义我的变量,并能够使用循环或类似的东西组装主体。

probe 定义变量如下:

ivr: - 编号:1 名称:《将军》 广告:“通用-ES” 目的地: 选项:“t” 目标 ID:10000 类型:“队列” 选项:“我” 目标 ID:10000 类型:“队列”

但它只向我展示了最后一个选项

ansible ansible-2.x ansible-facts ansible-template
1个回答
0
投票

当我运行剧本时,它返回一个错误,指出

item.dests.option
不存在。

这是预期的(如果您的任务尚未在循环中运行) - 您当前的示例不包含

item
变量的定义。

同时,

item
是循环变量的默认名称。 要迭代您的
ivr
列表,您需要将
loop
关键字添加到您的任务中。

但这也行不通,因为

item.dests
是一个列表,而您尝试访问
item.dests.option
,就好像
item.dests
是一个哈希一样。

要使其工作,您需要首先设置不同的循环变量来循环此任务,然后迭代该任务内的

dests
列表:

# playbook.yaml
---
- hosts: localhost
  connection: local
  gather_facts: false
  vars:
    ivr:
      - id: 1
        name: "General"
        announcement: "General-ES"
        dests:
          - option: "t"
            id_dest: 10000
            type: "Queue"

          - option: "i"
            id_dest: 10000
            type: "Queue"
  tasks:
    - name: Iterate over the `ivr` variable
      include_tasks: tasks/task.yaml
      loop: "{{ ivr }}"
      loop_control:
        loop_var: ivr_item
# tasks/task.yaml
---
- name: Creamos el ivr si no existe
  uri:
    url: "http://{{ ansible_host }}:{{ api_port }}/ivr/create"
    method: POST
    headers:
      Content-Type: "application/json"
      Authorization: "Bearer {{ result_post_token.json.token }}"
    return_content: yes
    body_format: json
    body: '{
      "name": "{{ ivr_item.name }}",
      "announcement": "{{ ivr_item.announcement }}",
      "dests": {
        "{{ item.dests.option }}": {
          "type": "{{ item.dests.type }}",
          "id": "{{ item.dests.id }}"
        },
      },
    }'
    status_code: 201
    timeout: 30
  loop: "{{ ivr_item.dests }}"

注意不同的

item
ivr_item
变量。 我还建议始终设置特定的循环变量名称,以便您的任务在可能的重构和添加到其他嵌套循环后表现相同。

probe 定义变量如下:

此示例无效,因为

Destinations
哈希包含重复的键。

© www.soinside.com 2019 - 2024. All rights reserved.