三、Ansible任务控制

本文详细介绍了Ansible的任务控制,包括编写循环和条件任务,如循环字典列表、结合Register变量与Loop使用,以及各种条件判断。此外,还阐述了如何实施处理程序,介绍其好处和语法。在处理任务失败方面,文章讲解了如何忽略任务失败、强制执行处理程序,以及如何指定任务失败条件。最后,文章提到了Ansible块和错误处理的概念,提供了示例说明。
摘要由CSDN通过智能技术生成

任务控制

一、编写循环和条件任务

1. 循环简介

  • Ansible支持使用loop关键字对一组项目迭代任务(旧版本使用with_items,与loop用法一致)

    • 循环过程:
    • loop关键字添加到任务中,将应对其迭代任务的项目列表取为值
    • 循环变量item保存每个迭代过程中使用的值(内部原理有机会RHCA再研究吧)
  • 示例

# 如下示例除了参数name不一致,其余都一致,就可以写成循环
- name: Postfix is running
  service: 
    name: postfix
    state: started
    
- name: Dovecot is running
  service:
    name: dovecot
    state: started
    
    
# 改写为简单循环
- name: Postfix and Dovecot are running
  service:
    name: "{
   { item }}"
    state: started
  loop:
    - postfix
    - dovecot
# 简单来说就是将loop下的列表依次迭代的赋值给item

# loop下的列表也可以写成变量的形式(下面给出完整写法)
---
- name: 
  vars:
    mail_services:
      - postfix
      - dovecot
  tasks: 
    - name: Postfix and Dovecot are running
      service:
        name: "{
   { item }}"
        state: started
      loop: "{
   { mail_services }}"

2. 循环字典列表

  • 在上例中我们循环的是列表中的纯量
  • loop列表中的项也可以是散列或字典,使用item.xx的形式调用
  • 示例
# zhangsan存在且为wheel组,lisi存在且为root组
- name: Users exist and are in the correct groups
  user:
    name: "{
   { item.name }}"
    state: present
    group: "{
   { item.groups }}"
  loop:
    - name: zhangsan
      groups: wheel
    - name: lisi
      groups: root

3、将Register变量与Loop一起使用

  • register关键字也可以捕获循环任务的输出
  • 示例
vim loop_register.yml
---
- name: Loop Register Test
  gather_facts: no # 不收集事实,上一篇有讲
  hosts: localhost
  tasks: 
    - name: Looping Echo Task
      shell: "echo This is my item: {
   { item }}"
      loop:
        - one
        - two
      register: echo_results  # 注册运行结果echo_results变量
      
    - name: Show echo_results variable
      debug:
        var: echo_results
  • 分析结果
  • 查看Task[Show echo_results variable]下的"echo_results"变量

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值