Ansible-playbook之循环判断

1.循环 (loop)

# 使用循环创建硬连接:x连接到y;z连接到k;
- hosts: web
  - name: Create two hard links
    file:
      src: "{{ item.src }}"
      dest: "{{ item.dest }}"
      state: hard
    loop:
      - "{ src: x , dest: y }"
      - "{ src: z , dest: k }"
# 使用循环修改rsync配置文件
- hosts: rsync
  - name:
    copy:
      src: "{{ item.src }}"
      dest: "{{ item.dest }}"
      mode: "{{ item.mode }}"
    loop:
      - "{ src: ./rsyncd.conf.j2 , dest: /etc/rsyncd.conf , mode: '0644' }"
      - "{ src: ./rsyncd.passwd.j2 , dest: /etc/rsync.passwd , mode: '0600' }"
# 使用循环启动多个服务
- hosts: web
  tasks:
    - name: Systemd nginx and firewalld
      systemd:
        name: "{{ item }}"
        state: started
        enabled: yes
      loop:
        - nginx
        - firewalld

2.判断 (when)

# 根据不同的操作系统,安装不同的软件
- hosts: all
  tasks:
    - name: Installed nginx in centos
      yum:
        name: nginx
        state: present
      # 当操作系统是CentOS并且是7版本时执行以上操作
      when: ( ansible_distribution == "CentOS" ) and ( ansible_distribution_major_version == "7" )
# 根据不同的主机名称,配置不同的源
- hosts: all
  tasks:
    - name: Install repositories
      yum_repository:
        description: nginx.repo
        baseurl: http://nginx.org/packages/centos/  $releasever/$basearch/
      # 判断,只有web主机组能执行以上操作
      when: (ansible_hostname is match ("web*") )
原文地址:https://www.cnblogs.com/IMSCZ/p/12069615.html