ansible - 在循环中注册多个变量

标签 ansible

我有一个可变的 yaml 文件:

---
apps:
  - client
  - node
  - gateway
  - ic
  - consul

和这个任务:

- name: register if apps exists
  stat: path="/etc/init.d/{{ item }}"
  with_items: apps
  register: "{{ item.stat.exists }}exists"

无论文件是否存在,我都需要为每个应用程序设置一个值为 true 或 false 的变量:

clientexists = true
nodeexists = true
gatewayexists = false
icexists = true
consulexists = false

由于某种原因,itemexists 连接不起作用。

我怎样才能做到这一点?

最佳答案

试试这个希望这会帮助你。在 Stats.yml 中循环时,msg 字段将包含您想要的输出。

Variables.yml 这里我们定义变量

---
apps:
  - client
  - node
  - gateway
  - ic
  - consul

统计.yml

---
- hosts: localhost
  name: Gathering facts
  vars_files:
  - /path/to/variables.yml
  tasks:
  - name: "Here we are printing variables"
    debug:
     msg: "{{apps}}"

  - name: "Here we are gathering stats and registering it"
    stat:
     path: "/etc/init.d/{{item}}"
    register: folder_stats
    with_items:
    - "{{apps}}"

  - name: "Looping over registered variables, Its msg field will contain desired output"
    debug:
     msg: "{{item.invocation.module_args.path}}: {{item.stat.exists}}"
    with_items:
    - "{{folder_stats.results}}"

...

folder_stats 将包含整个结果,用于单独引用单个结果 - 单个结果你可以在你的剧本中像这样使用它。

folder_stats.results[0].stat.exists 
folder_stats.results[1].stat.exists 
folder_stats.results[2].stat.exists 
folder_stats.results[3].stat.exists

关于ansible - 在循环中注册多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43961903/

相关文章:

Ansible 模块 : should I configure using systemd or service?

Ansible 手册与角色

loops - 如果变量之一未定义,如何不在 ansible 中循环

ansible - 如何在ansible替换模块中转义+字符

Ansible 循环变量

ansible - 对同一台主机的同一任务的多个同时请求给出“数据无法发送到远程主机 IP。确保可以通过 ssh 访问该主机

ansible-inventory --list 主机组命令行

Ansible默认变量命名似乎不一致

parallel-processing - 如何在 Ansible 剧本中并行运行几个角色?

Ansible blockinfile 模块幂等?