【问题标题】:Ansible Registers - Dynamic namingAnsible 寄存器 - 动态命名
【发布时间】:2019-04-22 16:46:32
【问题描述】:

我正在尝试使用 Ansible playbook 中的寄存器来存储我的输出。下面是我正在使用的代码。

我试过下面的代码

- name: Check if Service Exists
  stat: path=/etc/init.d/{{ item }}
  register: {{ item }}_service_status
  with_items:
     - XXX
     - YYY
     - ZZZ

我需要根据代码中提到的项目将不同的输出存储在不同的寄存器变量中。它失败了,无法继续。任何帮助将不胜感激。

【问题讨论】:

  • 哪一部分失败了?你能发布错误信息吗?
  • 另外,您能否根据名称说明如何在代码中的其他位置使用动态变量?

标签: ansible


【解决方案1】:

更新答案

我认为你需要在它周围加上引号:

register: "{{ item }}_service_status"

或者你可以使用set_fact1234

  • 将所有输出注册到单个静态变量output,然后通过循环遍历静态变量output 中的每个项目,使用循环迭代地构建新变量service_statuslist
- name: Check if Service Exists
  stat: path=/etc/init.d/{{ item }}
  register: output
  with_items:
     - XXX
     - YYY
     - ZZZ

- name: Setting fact using output of loop
  set_fact:
    service_status:
      - rc: "{{ item.rc }}"
        stdout: "{{ item.stdout }}"
        id: "{{ item.id }}"
  with_items:
    - "{{ output }}"

- debug:
    msg: "ID and stdout: {{ item.id }} - {{ item.stdout }}"
  with_items:
    - "{{ service_status }}"

初步回答

IIUC,Ansible 文档中的this link 展示了如何在循环中使用register(参见this SO post 中的另一个示例)。

几点

  • 将列表 (XXX, YYY, ZZZ) 分配给单独的变量(例如,12)可能更方便
  • 我不知道这是否是问题的一部分,但 with_items is no longer the recommended approach 循环变量:改为使用 loop - 请参阅 here 示例
vars:
  items:
    - XXX
    - YYY
    - ZZZ

- name: Check if Service Exists
  stat: path=/etc/init.d/{{ item }}
  register: service_status
  loop: "{{ items|flatten(levels=1) }}"

- name: Show the return code and stdout
  debug:
    msg: "Cmd {{ item.cmd }}, return code {{ item.rc }}, stdout {{ item.stdout }}"
  when: item.rc != 0
  with_items: "{{ service_status.results }}"

【讨论】:

  • 我在这里寻找寄存器的名称是动态的。不可能吗?因为我打算根据名称在代码中的其他位置使用该寄存器。
  • @SridharAdurthi,感谢您的回复。请查看我的更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
  • 2013-09-12
相关资源
最近更新 更多