【问题标题】:Ansible - How to save output from loop cycle 1 that I can use in the following loop cycles (2,3...)Ansible - 如何保存循环循环 1 的输出,我可以在以下循环循环中使用(2,3 ...)
【发布时间】:2022-08-02 19:20:26
【问题描述】:

我有一个 API 调用任务,它返回字典作为输出。从这个输出中,我只需要一个 ID。此 API 调用仅触发一次(当 item == \"1\" 时),但我需要它的输出在以下周期中也可用。这是我使用的代码示例:

        register: output
        when: item == \"1\"
        ignore_errors: yes
    
      - debug:
          var: output.json.id
    
      - name: show id
        debug:
          msg: output.json.id is \"{{ output.json.id }}\"

这是我在第一个周期得到的过滤输出结果:

    ok: [localhost] => {
        \"msg\": \"output.json.id is \\\"kjfld4343009394\\\"\"
    }

在第二个周期中,API 调用被跳过(项目不是 1),但前一个周期的输出不再可用:

    ok: [localhost] => {
        \"output.json.id\": \"VARIABLE IS NOT DEFINED!: \'dict object\' has no attribute \'json\'\"
    }

顺便说一句,如果 \"debug: var: output.json.id\" 应该在第一个周期中执行,我尝试将它与条件 item=1 和 ignore_errors=yes 一起执行,但这没有帮助。

      - debug:
          var: output.json.id
        when: item == \"1\"
        ignore_errors: yes

我该怎么做才能使此输出在其他周期中可用?

谢谢!

    标签: loops ansible var


    【解决方案1】:

    我刚刚找到了set_fact 的解决方案。

    - name: Set var id (set_fact)
      set_fact:
        var_id: "{{ output.json.id }}"
      when: item == "1"
          
    - debug:
      msg: id is "{{ var_id }}"
    

    当像这样保存var_id 时,可以在以下循环周期中使用。

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 2011-04-14
      相关资源
      最近更新 更多