ansible--循环

使用with_items

loops.yml

---
- hosts: all
  tasks: 
    - name: loop
      debug: msg="{{item}}"
      with_items:
        - one
        - two
        - three
        - four
  • with_items是ansible中的一个模块

应用

使用循环安装多个软件

---
- hosts: all
  tasks: 
    - name: loop
      yum: name="{{item}}" state="present"
      with_items:
        - nginx
        - zabbix
        - php
        - mysql

使用字典循环

---
- hosts: all
  tasks:
     - name: loop dicts
       debug: msg="key--->{{item.key}},value--->{{item.value}}"
       with_items:
       - {key: "one", value: "va1"}
       - {value: "two", value: "va2"}

使用嵌套循环

---
- hosts: all
  tasks:
     - name: loop nested
       debug: msg="key--->{{item[0]}},value--->{{item[1]}}"
       with_nested:
       - ['A', 'B']
       - ['a', 'b', 'c']

使用散列循环

---
- hosts: all
  gather_facts: no
  vars:
    user:
      shan:
        name: shan
        shell: bash
      ceshi:
        name: ceshi
        shell: zsh
  tasks:
    - name: debug loops
      debug: msg="{{item.key}}"
      with_dict: "{{ user }}"

使用文件循环

---
- hosts: all
  tasks: 
    - name: debug loops
      debug: msg="{{item}}"
      with_fileglob:
        - ./*.yml

条件判断循环

---
- hosts: all
  tasks:
    - name: debug loops
      shell: cat /root/ansible
      register: hosts
      until: hosts.stdout.startswith("Master")
      retries: 5
      delay: 5
  • until: 直到整个文件以Master开始为结束
  • retries: 5次
  • delay: 延迟五秒

使用jinjia语法的for循环

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

你可能感兴趣的:(ansible--循环)