首页 > 解决方案 > 如何编写 Ansible 条件 for 循环

问题描述

我有一个文件/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

有人可以帮帮我吗?

标签: ansible

解决方案


在这种情况下,循环应该发生在Join the minions任务中。即在一个任务中读取文件内容,然后在下一个任务中遍历文件中的行。

例子:

- hosts: all_nodes

  tasks:
  - name: Get the existing node names
    command: cat /tmp/nodescount.txt
    register: node_names
  - name: Join the minions
    shell: ./join.sh
    args:
      chdir: /tmp
    when: ansible_hostname != item
    loop: "{{ node_names.stdout_lines }}"
    become: true

推荐阅读