在循环中注册多个变量

时间:2017-05-14 08:29:48

标签: 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 concat无效。

我怎样才能实现?

1 个答案:

答案 0 :(得分:3)

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

Variables.yml Here we are defining variables

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

<强> Stats.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