ansible逻辑控制语句

条件判断语句 when

  1. when 的基本用法
    when 是条件判断语句,类似编程语言的if
tasks:
    - command: /bin/false
      register: result
      ignore_errors: True
    - command: /bin/command
      when: result |failed
    - commadn: /bin/command_else
      when: result|success
    - command: /bin/command_else_else
      when: result|skipped
  1. 与include一起使用
- include: tasks/sometasks.yml
  when: “‘reticulating splines’ in output”

  1. 与role 一起使用
- host: all
roles:
    - {role: debian_stock_config, when: ansible_os_family == 'debian'}

loop 循环

  1. 字典循环
    with_items 用于迭代的list类型变量,支持简单的字符列表,哈希列表
- name: add several users
  user: name{{item.name}} state=present groups={{item.groups}}
  with_iterms:
    - {name: 'name1', groups: 'group1'}
    - {name" 'name2', groups: 'group2'}

使用 .号访问内层和外层的变量

  1. 循环也可以嵌套,使用[ ]访问内层和外层的循环,例如item[0]
  2. 对哈希表的循环
    在变量文件中或者使用vars区域定义了一组列表变量items,可以这样使用
vars:
    items: ["user1","user2"]
tasks:
    ....

    with_items: "{{iterms}}"
    with_dict: "{{字典名}}"
  1. 文件循环(with_file, with_fileglob)
      with_file 是将每个文件的文件内容作为item的值
      with_fileglob 是将每个文件的全路径作为item的值, 在文件目录下是非递归的, 如果是在role里面应用改循环, 默认路径是roles/role_name/files_directory
- copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
      with_fileglob:
        - /playbooks/files/fooapp/*

bolck 块

  1. 使用block关键字可以将多个任务整合成一个块,把这个块当成一个整体,对这个块进行判断,当条件成立时,执行块中的所以语句
tasks:
  - debug:
      msg: "task1 not in block"
  - block:
      - debug:
          msg: "task2 in block1"
      - debug:
          msg: "task3 in block1"
    when: 2 > 1
  1. 错误处理功能
    错误处理功能就是当任务出错时,执行指定的其他任务
**failed 的用法**
tasks:
  - block:
      - shell: 'ls /ooo'
    rescue:
      - debug:
          msg: 'I caught an error'

**rescue的用法**
tasks:
  - block:
      - shell: 'ls /opt'
      - shell: 'ls /testdir'
      - shell: 'ls /c'
    rescue:
      - debug:
          msg: 'I caught an error'
    always:
      - debug:
          msg:"this always executes"

如上例所示,block中有三个任务,这三个任务中的任何一个任务错了,就会执行rescue中的任务,所以通常会使用block和rescue结合,完成“错误捕捉,报出异常”的功能
我们还可以加入always关键字,加入always以后,无论block中的任务执行成功还是失败,always中的任务总是被执行。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ORA-00001: 违反唯一约束条件 (.) 错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。 O...
    我想起个好名字阅读 5,450评论 0 9
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,917评论 0 38
  • 1 Block机制 (Very Good) Block技巧与底层解析 http://www.jianshu.com...
    Kevin_Junbaozi阅读 4,084评论 3 48
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,144评论 1 32
  • 坐上车,打开音乐,心想必须找个喜欢的歌,哼,必须滴。结果〈朋友的酒〉从耳机穿出,所有准备偃旗息鼓,就是喜欢嘛。 所...
    欣然_简然阅读 391评论 1 2