如何编写Ansible条件for循环

时间:2020-10-18 12:24:20

标签: ansible

我在/tmp/nodescount.txt中有一个文件,它具有如下所示的值:

instance-one
instance-two
instance-three

我需要读取文件line-by-line并在满足条件时执行另一个任务。

所以我这样做了:

---
- hosts: all_nodes
  tasks:

 - name: Get the existing node names
   with_lines: cat /tmp/nodescount.txt
   register: node_names    


 - name: Join the minions
   become: true
   shell: |
     cd /tmp/
     ./join.sh
   when: ansible_hostname != node_names # should loop over each node_name (instance-one, instance-two, instance-three)

因此,仅当该特定节点中的Join the minions值不等于三个值(实例一,实例二,实例三)中的任何一个时,我才想运行ansible_hostname任务。 / p>

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

在这种情况下,循环应该在<div class="div1"> <div class="other-shape"> </div> </div>任务中发生。即在一个任务中,读取文件内容,然后在下一个任务中遍历文件中的行。

示例:

Join the minions

答案 1 :(得分:0)

提供库存

shell> cat hosts
[all_nodes]
test_01
test_02
test_03

和远程主机上的文件

shell> ssh admin@test_01 cat /tmp/nodescount.txt
test_01
test_02

shell> ssh admin@test_02 cat /tmp/nodescount.txt
test_01
test_02

shell> ssh admin@test_03 cat /tmp/nodescount.txt
test_01
test_02

下面的剧本

- hosts: all_nodes
  tasks:
    - command: cat /tmp/nodescount.txt
      register: node_names
    - debug:
        msg: Join the minions
      when: inventory_hostname not in node_names.stdout_lines

给予(删节)

TASK [debug] ****
skipping: [test_01]
skipping: [test_02]
ok: [test_03] => 
  msg: Join the minions