ansible 循环与条件判断when

普通循环

with_itemes  变量组

  { item }  循环变量

示例

- name: 覆盖配置文件
      copy: src=/root/{{ item }} dest=/root/test/{{ item }}
      with_items:
      - a.txt
      - b.txt
      - c.txt
      - d.txt
      - shell   (目录)
##会依次将abcd 四个txt文件和 shell目录拷贝到目标文件夹下

引用sc的一个示例:

字典循环

#添加用户

- name: add users
  user: name={{ item }} state=present groups=wheel
  with_items:     
  - testuser1
  - testuser2

- name: add users
  user: name={{ item.name }} state=present groups={{ item.groups }}
  with_items:
  - { name: 'testuser1', groups: 'test1' }
  - { name: 'testuser2', groups: 'test2' }

示例二

users:
  alice:
    name: Alice Appleworth
    telephone: 123-456-7890
  bob:              #key
    name: Bob Bananarama    #value1
    telephone: 987-654-3210   #value2

tasks:
  - name: Print records
    debug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
    with_dict: "{{ users }}"

示例三

执行结果

嵌套循环

---
- name: test
  hosts: test
  tasks:
    - name: test
      command: "echo name={{ item[0] }} priv={{ item[1] }}"
      with_nested:
        - [ 'alice', 'bob' ]
        - [ 'clientdb', 'employeedb', 'providerdb' ]

##item[0]是循环的第一个列表的值['alice','bob'];item[1]是第二个列表的值。

 

打印结果:

  

文件循环

inventory循环(with_inventory_hostnames)

# show all the hosts in the inventory
- debug: msg={{ item }}
  with_inventory_hostnames: all

# show all the hosts matching the pattern, ie all but the group www
- debug: msg={{ item }}
  with_inventory_hostnames: all:!www

with_fileglob:

---
- hosts: test
  gather_facts: False
  tasks:
      - name: display value    ##列举某个目录下的某些文件
        debug: msg="file is {{ item }}"
        with_fileglob:
            - /root/*.zip

条件判断when与register变量

register官网示例

register 可接受多个task的结果作为变量临时存储,示例:

---
- hosts: test
  gather_facts: False
  tasks:
      - name: display value
        shell: "{{ item }}"
        with_items:
            - hostname
            - uname
        register: ret
      - name: display loops
        debug: msg="{% for i in ret.results %} {{ i.stdout }} {% endfor %}"

 执行结果:

 

when 官网示例

 

其它示例:

判断分支是否在git分支列表,如果不在,运行某个脚本

- command: chdir=/path/to/project  git branch
  register: git_branches

- command: /path/to/project/git-clean.sh
  when: "('release-v2' no in git_branches.stdout)"

判断某个文件是否存在

- stat: path=/etc/hosts
   register: host_file

- copy: src=/path/to/local/file  dest=/path/to/remote/file
   when: host_file.stat.exists == false

其它示例

changed_when && failed_when

对命令运行结果进行判断。

示例

比如判断某个软件是否安装成功

- name: install git
   yum: name=git state=latest
   register: git_install

   changed_when: " 'nothing to install or upgrade' not in git_install.stdout"    #表示输出的结果中没有 notthing to install ..才返回change结果

ignore_errors: true 屏蔽错误信息

原文地址:https://www.cnblogs.com/FRESHMANS/p/8127023.html