美文网首页
ansible逻辑控制语句

ansible逻辑控制语句

作者: 天天向上_ac78 | 来源:发表于2018-12-23 21:00 被阅读0次

条件判断语句 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中的任务总是被执行。

相关文章

网友评论

      本文标题:ansible逻辑控制语句

      本文链接:https://www.haomeiwen.com/subject/svhokqtx.html