Ansible Conditionals & Loops

 一、条件语句

    条件判断语句,就是根据某些变量的值来控制Ansible的执行流程。控制某些主机执行某些操作与不执行某些操作。根据某些操作结果,判断是否执行其它操作等等。

    Ansible的条件判断语句只有 when 语句,结合变量使用才能显示出它的价值。when的用法:在想要进行判断的语句下面添加when语句即可进行条件判断.

二、示例

支持判断的操作符

1、比较操作符

       ==       !=       >       >=       <       <=

2、逻辑运算符

       and       or       not

tasks:                #简单的判断
   - name: "shutdown Debian flavored systems"
     command: /sbin/shutdown -t now
     when: ansible_os_family == "Debian"
tasks:                 #组合形式的判断
  - name: "shutdown CentOS 6 and Debian 7 systems"
    command: /sbin/shutdown -t now    
    when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6") or
          (ansible_distribution == "Debian" and ansible_distribution_major_version == "7")
tasks:                   #基于某些task的结果,执行相应的task
  - command: /bin/false
    register: result   
    ignore_errors: True
  - command: /bin/something
    when: result|failed
  - command: /bin/something_else
    when: result|success
  - command: /bin/still/something_else
    when: result|skipped
tasks:                      #如果一些变量没有定义,可以使用Jinja2的define测试。,来执行一些操作
    - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined      
 
    - fail: msg="Bailing out. this play requires 'bar'"
      when: bar is undefined
tasks:               #有时一些变量的返回结果是字符串,但是你想对它做一些数学运算
  - shell: echo "only on Red Hat 6, derivatives, and later"
    when: ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6
---              #对是否执行一些外部任务进行条件判断
- hosts: local
  vars:
   test: true
 
  tasks:
  - name: Test test
    debug: msg="Hello When"
    when: test
 
  - include: pre.yml         #根据条件判断,是否include某个外部任务文件。
    when: test           
 
  roles:
    - { role: /home/aheahe/roles/test, when: test }   #结合条件判断,是否加载某个Role

 

可以看出条件判断主要就是结合变量使用。

循环

一、简介    

      通常一个任务会做很多事情,如创建大量的用户,安装很多包,或重复的轮询特定的步骤,直到某种结果条件为止,Ansible为我们提供了此支持。下面是关于循环的一些语句。

 

with_items     #标准循环

with_nested    #嵌套循环

with_dict          #字典循环(Looping over hashed)

with_file       #循环文件

with_fileglob    #通配符循环文件

with_together    #循环映射

with_subelements  #子元素循环

with_sequence      #生成一系列的数字

with_random_choice   #任意选择

#with_first_found      #选择第一个找到的,不会用

with_lines          #循环程序执行的输出信息with_items:{{command_result.stdout_lines}}

with_flattened      #循环列表中的列表的item

 

二、实例

---
- hosts: local                        #with_item 和 with_nested 用法
  vars:
    Sta: false
    User: [ "Aheahe","yunzhonghe" ]
  tasks:
  - name: Standard Loops
    debug: msg="{{ item.name }},{{ item.fun }}"
    with_items:                  #生成标准循环
     - { name: Loops, fun: xx }
     - { name: Conditional, fun: yy }
    when: Sta
  - name: Nested Loops
    debug: msg= "name={{ item[0] }},priv={{ item[1] }}"
    with_nested:                  #嵌套循环
     - "{{ User }}"                #这里的User 可以直接使用列表。
     - [ "Student","Engineer","Friends" ]

---
- hosts: local          #with_dict 用法
#  vars_files:
#    hash.yml
  vars:
    users:
      alice:
        name: Alice Appleworth
        telephone: 123-456-7890
      bob:
        name: Bob Bananarama
        telephone: 987-654-3210
  tasks:
  - name: Print phone records
    debug: msg="User  item.key  is  item.value.name   item.value.telephone "
    with_dict: users              #循环列表可以查看输出信息。以获取结果

 

---
- hosts: local                 #with_file 与 with_fileglob 用法。
  vars:
    test_file: false
  tasks:
  - name: test file
    shell: echo {{ item }}
    with_file:         #循环文件的内容
     - test                          #test文件里面为任意内容。
     - test1
    when: test_file
 
  - name: Test file Glob
    shell: echo {{ item }}
    with_fileglob:     #循环文件的通配符。
    - /home/aheahe/playbook/*

 

---
- hosts: local                 #with_together用法
  vars:
    alpha: [ 'a', 'b', 'c', 'd' ]
    numbers:  [ 1, 2, 3, 4 ]
    test: [ 'A', 'B', 'C', 'D' ]
  tasks:
   - debug: msg="{{ item.0 }} and {{ item.1 }} and {{ item.2 }}"
     with_together:                #循环映射信息
       - "{{alpha}}"
       - "{{numbers}}"
       - "{{test}}"

 

---
- hosts: local         #with_subelement用法
  vars:
    users:
      - name: alice
        authorized:
          - /tmp/alice/onekey.pub
          - /tmp/alice/twokey.pub
        mysql:
            password: mysql-password
            hosts:
              - "%"
              - "127.0.0.1"
              - "::1"
              - "localhost"
            privs:
              - "*.*:SELECT"
              - "DB1.*:ALL"
      - name: bob
        authorized:
          - /tmp/bob/id_rsa.pub
        mysql:
            password: other-mysql-password
            hosts:
              - "db1"
            privs:
              - "*.*:SELECT"
              - "DB2.*:ALL"
  tasks:
  - name: Test1
    shell: echo "name={{ item.name }}"
    with_items: "{{users}}"
  - name: Test2
    shell: echo "User={{ item.0.name }},key={{ item.1 }}"
    with_subelements:         #循环子元素。
    - users
    - authorized

 

---
- hosts: local
  tasks:
  - name: Learn loop sequence
    debug: msg={{ item }}
    with_sequence: start=0 end=6 stride=2

 

---
- hosts: local                 # with_random_choice 用法
  tasks:
  - name: Learn Random
    debug: msg={{ item }}
    with_random_choice:
     - "go through the door"
     - "drink from the goblet"
     - "press the red button"
     - "do nothing"

 

---
- hosts: local         #with_lines 用法
  tasks:
  - name: test result
    shell: echo {{ item }}
    with_lines: /bin/df -Th
 
- name: flattened loop demo                       #with_flatted用法
  yum: name={{ item }} state=installed
  with_flattened:
     - "{{packages_base}}"
     - "{{packages_apps}}"
----
# file: roles/foo/vars/main.yml
packages_base:
  - [ 'foo-package', 'bar-package' ]
packages_apps:
  - [ ['one-package', 'two-package' ]]
  - [ ['red-package'], ['blue-package']]

原创文章,作者:艾贺,如若转载,请注明出处:http://www.178linux.com/9446

(1)
艾贺艾贺
上一篇 2015-11-19 15:39
下一篇 2015-11-23 21:03

相关推荐

  • Linux文件类型及颜色标识

    查看文件类型:      指令:ll 文件名或目录名      –  白色 普通文件(可执行文件)      l  扩写:sysbolic link 淡蓝色 符号链接文件   &…

    Linux干货 2016-10-18
  • LVM逻辑卷扩展与缩小

    逻辑卷扩容:扩展逻辑卷前一定要卸载设备和挂载点的关联 第一步:把逻辑卷lv扩展至300M 第二步:检查硬盘,并重置硬盘容量 第三步:重新挂载,查看挂载状态   缩小逻辑卷:对逻辑卷缩容时,丢失数据的风险更大。在执行操作前一定要提前备份好数据。在进行缩减前先把文件系统卸载掉。 第一步:检查文件 第二步:把逻辑卷lv减小到100M 第三步:重新挂载并查…

    2017-12-17
  • Linux文本处理工具grep

    文件查看工具:cat     将[文件]或标准输入组合输出到标准输出。               -A, –show-all       &nbs…

    Linux干货 2016-08-10
  • 网络管理总结

      在学习Linux的快两个月时间的这个阶段,我们学习到了网络的相关知识,哇,原来我们上网是需要这么多步骤的,玩了这么久的电脑,打开过无数网站还只是停留在以为打开网站只需要点点鼠标的层面,惭愧惭愧。学习了一周,终于了解了一些网络的基层结构和一些网络协议,下面是对这一周所学知识的一些总结,加强记忆和理解。还停留在以为打开一个网站只是动动鼠标…

    2017-09-02
  • Linux初探

    1.计算机组成: CPU:运算器(指令集)、控制器、寄存器、缓存; 存储器:内存,RAM; Input:下指令,提供数据; Ouput:输出数据加工的结果 一般来说,从磁盘中读取程序和数据放到内存中排队,由cpu从内存中读取执行。由于cpu处理速度远大于磁盘的I/O速度,因此引入缓存。在计算机中有缓存为王这个说法。 2.操作系统的背景: 1.统一规范 2.由…

    Linux干货 2016-10-30
  • sed和awk和数组实践-week15

    1、总结sed和awk的详细用法; (1) sedsed:Stream EDitor,流编辑器,行编辑器 基本原理:一次从文本中读取一行,放到sed自己的工作车间加工, 该工作车间叫做模式空间(pattern space)判断该行是否符合过滤模式, 如果符合过滤模式: 送往标准输出(终端) 执行编辑操作, 从模式空间中处理以后,处理过后送到标准输出(不一定有…

    Linux干货 2017-05-06

评论列表(1条)

  • stanley
    stanley 2015-11-26 17:19

    向写书的标准努力