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的哲学理念

    1、由目的单一的小程序组成,通过使用者的组合形成一个能够完成复杂任务的应用程序 2、一切皆为文件 3、尽量避免捕获用户接口;也就是说Linux运行的程序大多数是不需要过多的反复输入/输出人机交互信息,运行程序命令,直接获得反馈的结果,是一种目的单一的程序 4、配置文件保存为纯文本格式

    Linux干货 2016-10-29
  • CentOS系统启动流程

    概述:系统启动流程是Linux一个重要的内容,深入了解启动流程会对我们学习Linux起到一个顺水推舟的作用。因为CentOS 7改动较大,所以下面的内容只是针对CentOS 5和6来说的。下面进入正题。 启动流程:  第一步:POST加电自检    此过程的就是为了检测一下外界的硬件设备是否能够正常运行,如CPU,内存设备,硬盘…

    Linux干货 2016-09-13
  • 系统启动和内核管理

    Linux组成 Linux:kernel+rootfs kernel:进程管理、内存管理、网络管理、驱动程序、文件系统、安全功能 rootfs:程序和glibc 库:函数集合,function,调用接口(头文件负责描述) 过程调用:procedure,无返回值; 函数调用:function;有返回值,可以赋值于变量中; 程序:二进制执行文件 包括根目录以及包…

    Linux干货 2017-05-14
  • Linux磁盘管理详解

    linux磁盘管理 添加磁盘步骤: fdisk 管理磁盘分区 格式化文件系统。 设备挂载 开机自动挂载 UUID挂载 取消挂载点 Parted(gpt大于2G分区) 查看文件系统的使用情况。 df 查看挂载信息与磁盘使用量 du 查看使用量 查看分区状况lsblk 查看设备信息blkid linux磁盘管理 当全新安装了一块新的硬盘设备后,为了更充分、安全的…

    Linux干货 2016-09-07
  • 配置路由实例

    路由的分类和管理 路由:跨网络通信; 路由分类:     主机路由     网络路由     默认路由 路由管理命令: route 命令是在本地 IP 路由表中显示和修改条目网络命令; 查看:route -n 添加:route add ro…

    Linux干货 2016-09-12
  • N22-第四周博客作业

    1、复制/etc/skel目录为/home/tuser1,要求/home/tuser1及其内部文件的属组和其它用户均没有任何访问权限。 [root@localhost ~]# ll -d  /etc/skel/drwxr-xr-x. 3 root root 74 3月&…

    Linux干货 2016-09-19

评论列表(1条)

  • stanley
    stanley 2015-11-26 17:19

    向写书的标准努力