使用 Ansible Blocks 进行错误处理
注:机翻,未校。
How to Use Ansible Blocks
Make your Playbooks more readable and maintainable using Blocks feature in Ansible.
使用 Ansible 中的块功能使 Playbook 更具可读性和可维护性。
Jul 15, 2024 — LHB Community
How to Use Ansible Blocks 如何使用 Ansible 块
Blocks are a powerful feature in Ansible that allows you to group tasks together and apply common attributes, such as when conditions or become directives, to all tasks within the block.
块是 Ansible 中的一项强大功能,它允许 将任务分组在一起,并将通用属性(例如 when 条件或成为指令)应用于块中的所有任务。
This can make your Ansible playbooks more readable and maintainable.
这可以使 Ansible playbook 更具可读性和维护性。
With blocks, you can also gracefully handle errors, escalate privileges for multiple tasks at once, and organize tasks hierarchically with nested blocks.
使用块, 还可以优雅地处理错误,一次提升多个任务的权限,并使用嵌套块分层组织任务。
In this tutorial, we’ll explore how to use Ansible blocks with practical examples.
在本教程中,我们将通过实际示例来探索如何使用 Ansible 块。
Basic Syntax of Ansible Blocks Ansible 块的基本语法
The basic syntax for an Ansible block is straightforward. Here’s an example:
Ansible 块的基本语法很简单。下面是一个示例:
- name: Example blockblock:- name: Task 1ansible.builtin.command: echo "This is task 1"- name: Task 2ansible.builtin.command: echo "This is task 2"
In this example, both tasks are grouped within a block. You can apply common attributes to the entire block, such as when
, become
, or rescue
.
在此示例中,两个任务都分组在一个块中。 可以将通用属性应用于整个块,例如 when
、become
或 rescue
。
Using Blocks with Conditional Execution 使用有条件执行的块
Imagine you want to execute a group of tasks only when a certain condition is met. You can apply the condition to the entire block instead of each individual task.
想象一下, 只想在满足特定条件时执行一组任务。 可以将条件应用于整个块,而不是每个单独的任务。
Create a playbook with the following content.
创建包含以下内容的 playbook。
- name: Conditional block examplehosts: localhostvars:run_tasks: truetasks:- name: Execute tasks if condition is metblock:- name: Task 1ansible.builtin.command: echo "This is task 1"- name: Task 2ansible.builtin.command: echo "This is task 2"when: run_tasks
In this playbook, we define a variable run_tasks
and set it to true
. We then use a block to group two tasks. The when
condition is applied to the block, so both tasks will only run if run_tasks
is true
.
在此 playbook 中,我们定义了一个变量 run_tasks
并将其设置为 true
。然后,我们使用一个块对两个任务进行分组。when
条件应用于块,因此仅当 run_tasks
为 true
时,两个任务才会运行。
This approach simplifies the playbook by applying the condition once to the block instead of individually to each task.
这种方法通过将条件应用于块一次而不是单独应用于每个任务来简化 playbook。
Run the above playbook.
运行上述 playbook。
ansible-playbook conditional_block_example.yml
This will run the block of tasks only if the condition run_tasks is true.
仅当条件 run_tasks 为 true 时,才会运行任务块。
PLAY [Conditional block example] ***********************************************TASK [Gathering Facts] **********************************************
ok: [localhost]TASK [Execute tasks if condition is met] ***************************************
skipping: [localhost]TASK [Task 1] *******************************************************
ok: [localhost] => {"changed": false,"msg": "This is task 1"
}TASK [Task 2] *******************************************************
ok: [localhost] => {"changed": false,"msg": "This is task 2"
}PLAY RECAP **********************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
Using Blocks with Error Handling 使用块进行错误处理
You can use blocks to handle errors gracefully by adding rescue and always sections.
可以通过添加 rescue 和 always 部分来使用块来优雅地处理错误。
Let’s create a playbook.
让我们创建一个剧本。
- name: Error handling block examplehosts: localhosttasks:- name: Block with error handlingblock:- name: Task that might failansible.builtin.command: /bin/false- name: Task that won't be executedansible.builtin.command: echo "This won't run"rescue:- name: Handle the erroransible.builtin.command: echo "An error occurred"always:- name: This always runsansible.builtin.command: echo "This runs always"
In this playbook, the block
section contains tasks that might fail. The rescue
section contains tasks to run if any task in the block fails, and the always
section contains tasks that will run regardless of success or failure.
在此 playbook 中,block
部分包含可能会失败的任务。rescue
部分包含在块中的任何任务失败时要运行的任务,而 always
部分包含无论成功还是失败都将运行的任务。
This structure allows you to manage errors gracefully and ensure certain actions are always performed.
通过此结构, 可以优雅地管理错误,并确保始终执行某些操作。
Now, run the above playbook.
现在,运行上述剧本。
ansible-playbook error_handling_block_example.yml
This will handle errors and ensure certain tasks always run.
这将处理错误并确保某些任务始终运行。
PLAY [Error handling block example] ********************************************TASK [Gathering Facts] **********************************************
ok: [localhost]TASK [Block with error handling] ***********************************************
fatal: [localhost]: FAILED! => {"changed": false, "cmd": "/bin/false", "rc": 1}TASK [Handle the error] **********************************************
ok: [localhost] => {"changed": false,"msg": "An error occurred"
}TASK [This always runs] **********************************************
ok: [localhost] => {"changed": false,"msg": "This runs always"
}PLAY RECAP **********************************************
localhost : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=1 ignored=0
Using Blocks with Privilege Escalation 使用具有权限提升的块
You can use blocks to apply privilege escalation (become) to multiple tasks at once.
可以使用块一次将权限提升 (become) 应用于多个任务。
Create a playbook with the following content.
创建包含以下内容的 playbook。
- name: Privilege escalation block examplehosts: localhosttasks:- name: Block with privilege escalationblock:- name: Task 1 as rootansible.builtin.command: echo "Task 1 as root"- name: Task 2 as rootansible.builtin.command: echo "Task 2 as root"become: yes
In this playbook, the become: yes
directive is applied to the block, so both tasks will run with elevated privileges. This is useful when you need multiple tasks to run as a different user, reducing redundancy by applying the privilege escalation to the entire block.
在此 playbook 中,become: yes
指令应用于块,因此这两个任务都将以提升的权限运行。当 需要多个任务以不同用户身份运行时,这非常有用,通过对整个块应用权限提升来减少冗余。
Now, let’s run this playbook.
现在,让我们运行这个剧本。
ansible-playbook privilege_escalation_block_example.yml
This playbook executes the tasks in the block with root privileges.
此 playbook 以 root 权限执行块中的任务。
PLAY [Privilege escalation block example] **************************************TASK [Gathering Facts] **********************************************
ok: [localhost]TASK [Block with privilege escalation] *****************************************
ok: [localhost] => {"changed": false,"msg": "Task 1 as root"
}ok: [localhost] => {"changed": false,"msg": "Task 2 as root"
}PLAY RECAP **********************************************
localhost : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Nested Blocks 嵌套块
You can nest blocks within other blocks to create complex task structures. This can help organize tasks into logical groups and apply specific attributes to different levels of the hierarchy.
可以将块嵌套在其他块中,以创建复杂的任务结构。这有助于将任务组织到逻辑组中,并将特定属性应用于层次结构的不同级别。
Create a playbook and add the following content.
创建 playbook 并添加以下内容。
- name: Nested blocks examplehosts: localhosttasks:- name: Outer blockblock:- name: Task in outer blockansible.builtin.command: echo "This is in the outer block"- name: Inner blockblock:- name: Task in inner blockansible.builtin.command: echo
In this playbook, the outer block contains another block within it. The outer block has a task that echoes a message indicating it is in the outer block. The inner block is nested within the outer block and contains a task that echoes a message indicating it is in the inner block.
在此 playbook 中,外部块包含另一个块。外部块有一个任务,该任务会回显一条消息,指示它位于外部块中。内部块嵌套在外部块中,并包含一个任务,该任务会回显一条消息,指示它位于内部块中。
Run the above playbook.
运行上述 playbook。
ansible-playbook nested_blocks_example.yml
You will get the following output.
将获得以下输出。
PLAY [Nested blocks example] **********************************************TASK [Gathering Facts] **********************************************
ok: [localhost]TASK [Outer block] **********************************************
ok: [localhost] => {"changed": false,"msg": "This is in the outer block"
}TASK [Inner block] **********************************************
ok: [localhost] => {"changed": false,"msg": "This is in the inner block"
}PLAY RECAP **********************************************
localhost : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Using Blocks with Handlers 将块与处理程序一起使用
You can use blocks to notify handlers, which can be useful for managing tasks that need to be executed conditionally based on previous task outcomes.
可以使用块来通知处理程序,这对于管理需要根据先前的任务结果有条件执行的任务非常有用。
Create a playbook with the following content:
创建包含以下内容的 playbook:
- name: Blocks with handlers examplehosts: localhosttasks:- name: Block with handler notificationblock:- name: Task that changes somethingansible.builtin.command: echo "This changes something"notify: Restart service- name: Another taskansible.builtin.command: echo "This is another task"notify: Restart servicehandlers:- name: Restart serviceansible.builtin.command: echo "Service restarted"
In this example, the block contains two tasks, both of which notify the handler Restart service
. The handler Restart service
is defined to echo a message indicating the service has been restarted.
在此示例中,该块包含两个任务,这两个任务都通知处理程序 Restart service
。处理程序 Restart service
被定义为回显指示服务已重新启动的消息。
Now, run this playbook.
现在,运行此 playbook。
ansible-playbook blocks_with_handlers_example.yml
This playbook use blocks to notify handlers, ensuring that specific tasks run based on the outcomes of tasks within the block.
此 playbook 使用块通知处理程序,确保特定任务根据块内任务的结果运行。
PLAY [Blocks with handlers example] ********************************************TASK [Gathering Facts] **********************************************
ok: [localhost]TASK [Block with handler notification] *****************************************
ok: [localhost] => {"changed": false,"msg": "This changes something"
}ok: [localhost] => {"changed": false,"msg": "This is another task"
}RUNNING HANDLER [Restart service] **********************************************
ok: [localhost] => {"changed": false,"msg": "Service restarted"
}PLAY RECAP **********************************************
localhost : ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Conclusion 结论
In this article, you explored the basics of using Ansible blocks, including their syntax and practical applications. You saw how blocks can simplify conditional execution, error handling, privilege escalation, nested structures, and handler notifications in your playbooks. By using blocks, you can make your Ansible playbooks more organized and easier to maintain.
在本文中, 探讨了使用 Ansible 块的基础知识,包括它们的语法和实际应用。 了解了块如何简化 playbook 中的条件执行、错误处理、权限提升、嵌套结构和处理程序通知。通过使用块, 可以使 Ansible playbook 更有序且更易于维护。
via:
-
How to Use Ansible Blocks
https://linuxhandbook.com/ansible-blocks/
相关文章:
使用 Ansible Blocks 进行错误处理
注:机翻,未校。 How to Use Ansible Blocks Make your Playbooks more readable and maintainable using Blocks feature in Ansible. 使用 Ansible 中的块功能使 Playbook 更具可读性和可维护性。 Jul 15, 2024 — LHB Community How to Use Ansible…...
java中的静态变量和实例变量的区别
java中的静态变量和实例变量的区别 在Java中,静态变量(也称为类变量)和实例变量是两种不同类型的变量,它们在多个方面存在显著的区别。以下是它们之间的一些主要区别: 存储位置 静态变量:存储在方法区&am…...
【Effecutive C++】条款02 尽量以const, enum, inline替换 #define
Prefer consts, enums, and inline to #define. 这个条款或许改为“宁可以编译器替换预处理器”比较好,因为或许#define不被视为语言的一部分。那正是它的问题所在。当你做出这样的事情: #define ASPECT_RATIO 1.653记号名称ASPECT_RATIO也许从未被编译…...
leetcode-226. 翻转二叉树
题目描述 给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。 示例 1: 输入:root [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]示例 2: 输入:root [2,1,3] 输出:[2,3,1]…...

用的到linux-tomcat端口占用排查-Day5
前言: 最近使用tomcat搭建了一套测试环境的应用,整个搭建过程也很简单,就是将部署包上传至服务器☞解压☞启动tomcat服务器,当然服务器也是成功启动了,但是发现前端应用报404,具体如下图所示。 一、现象及思…...

mqtt协议详解(0)初步认识mqtt
文章目录 1. 介绍2. 主要特性3. 架构1. 介绍 MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议)是一种构建在TCP/IP协议之上的轻量级、基于发布-订阅模式的消息传输协议,适用于资源受限的设备和低带宽、高延迟或不稳定的网络环境,例如IOT。 MQTT 协议于 1…...

Java语言程序设计基础篇_编程练习题*16.7 (设置时钟的时间)
*16.7 (设置时钟的时间) 编写一个程序,显示一个时钟,并通过在三个文本域中输入小时、分钟和秒 钟来设置时钟的时间,如图16-38b 所示。使用程序清单14-21的ClockPane改变时钟大小使其居于面板中央 习题思路 实例化一个ClockPane(在程序清单1…...

YOLOv8新版本支持实时检测Transformer(RT-DETR)、SAM分割一切
原文:YOLOv8新版本支持实时检测Transformer(RT-DETR)、SAM分割一切 - 知乎 (zhihu.com) 一、SAM 分割任何模型 (Segment Anything Model - SAM) 是一种突破性的图像分割模型,可实现具有实时性能的快速分割。 项目地址 https://github.com/facebookresearch/segment-…...

【传输层协议】UDP和TCP协议
文章目录 UDP协议UDP特点UDP的缓冲区基于UDP的应用层协议 TCP协议6位标志位:确认应答机制超时重传机制连接管理机制(握手和挥手)服务端状态转换过程客户端状态转换过程TIME_WAIT状态CLOSE_WAIT状态 为什么是三次握手和四次挥手滑动窗口如果发…...

Java Excel复杂表头,表头合并单元格
Java Excel复杂表头,表头合并单元格 效果预览 一、maven依赖 <!--操作excel --><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.1.1</version><scope>test</…...

Java整合腾讯云发送短信实战Demo
简介 在现代应用开发中,短信服务是非常重要的功能之一。它可以用于用户验证、通知等各种场景。本文将介绍如何使用Java整合腾讯云短信服务,并提供一个完整的实战示例代码。 环境准备 在开始之前,确保你已经完成以下准备工作: 注…...

电路中电阻,电容和电感作用总结
电阻作用 1,上拉电阻 电阻的连接一般是一端接上拉的电源(一般与芯片信号的电压值相匹配),另一端连接芯片引脚所对应的信号大概如下图 功能:一、预置某些引脚的功能,例如复位信号拉高(失能&…...

OrangePi AIpro学习1 —— 烧写和ssh系统
目录 一、下载烧写工具和系统 二、烧写和启动 2.1 烧写和启动 2.2 烧写失败后的问题解决 三、串口连接到主机 3.1 串口连接到主机 四、网络连接到主机 4.1 修改香橙派IP地址 4.2 win11配置以太网静态ip 4.4 主机和香橙派直连 4.5 主机和香橙派连接到同一个路由器 五…...
Gather 全球化进程迅速 多重利好推动未来发展
在过去的几周里,Gather的全球化发展十分迅速,并取得了一系列重要成绩,这些成绩进一步巩固了Gather在区块链和去中心化通信领域的地位,并为未来的发展注入了强劲的动力。 $GAT代币成功进驻多家顶级交易所 7月19日,Gath…...

面试经典 222. 完全二叉树的节点个数
二叉树我最近刷的特别多,差不多快刷完了,但是有一种题型差点给我忽略了,那就是完全二叉树,这也是一个很重要的题型,今天刚好有一道题目可以来复习一下完全二叉树的特性 题目链接如下:https://leetcode.cn/…...

【css】3d柱状图-vue组件版
创建一个响应式圆柱形进度条组件 在现代网页设计中,圆柱形进度条是一种非常流行的视觉元素,用于展示数据的进度或状态。本文将介绍如何使用Vue.js和LESS创建一个响应式的圆柱形进度条组件。 组件结构 我们的组件由两部分组成:一个圆柱形的…...

《计算机组成原理》(第3版)第3章 系统总线 复习笔记
第3章 系统总线 一、总线的基本概念 总线是连接多个部件的信息传输线,是各部件共享的传输介质,如图3-1所示。 图3-1 面向CPU的双总线结构框图 倘若将CPU、主存和I/O设备都挂到一组总线上,便形成单总线结构的计算机,如图3-2所示…...

【网络安全】https协议的加密方案避免中间人攻击(MITM攻击)导致的数据泄露风险
目录 引言 概念准备 中间人 加密 数据摘要 && 数据指纹 数字签名 密钥加密 中间人攻击 CA证书 https加密的解决方案 个人主页:东洛的克莱斯韦克-CSDN博客 引言 http在应用层协议中是明文传输协议,它是通信双方传输数据时的一种约定。【…...
拼多多商家电话采集 拼多多店铺爬虫软件使用教程
拼多多商家电话采集和店铺爬虫软件使用教程: 商家电话采集: a. 打开拼多多网站,进入需要采集电话号码的店铺页面。 b. 打开浏览器开发者工具(一般按F12键或右键选择“检查”)。 c. 在开发者工具中切换到“网络”或“Ne…...

RK3566 MIPI屏调试记录
文章目录 1. 前言2. 环境介绍3. 思路介绍4. 确认要修改的设备树文件5. 设备树中修改关键引脚5.1. 添加dsi0节点5.2. 修改屏幕背光引脚5.3. 添加屏幕复位引脚5.4. 添加屏幕使能引脚 6. 修改屏幕timing参数7. 修改上下电时序8. 修改初始化序列和反初始化序列9. 显示路由配置10. 最…...
后进先出(LIFO)详解
LIFO 是 Last In, First Out 的缩写,中文译为后进先出。这是一种数据结构的工作原则,类似于一摞盘子或一叠书本: 最后放进去的元素最先出来 -想象往筒状容器里放盘子: (1)你放进的最后一个盘子(…...
uniapp 对接腾讯云IM群组成员管理(增删改查)
UniApp 实战:腾讯云IM群组成员管理(增删改查) 一、前言 在社交类App开发中,群组成员管理是核心功能之一。本文将基于UniApp框架,结合腾讯云IM SDK,详细讲解如何实现群组成员的增删改查全流程。 权限校验…...

Zustand 状态管理库:极简而强大的解决方案
Zustand 是一个轻量级、快速和可扩展的状态管理库,特别适合 React 应用。它以简洁的 API 和高效的性能解决了 Redux 等状态管理方案中的繁琐问题。 核心优势对比 基本使用指南 1. 创建 Store // store.js import create from zustandconst useStore create((set)…...

Vue3 + Element Plus + TypeScript中el-transfer穿梭框组件使用详解及示例
使用详解 Element Plus 的 el-transfer 组件是一个强大的穿梭框组件,常用于在两个集合之间进行数据转移,如权限分配、数据选择等场景。下面我将详细介绍其用法并提供一个完整示例。 核心特性与用法 基本属性 v-model:绑定右侧列表的值&…...
镜像里切换为普通用户
如果你登录远程虚拟机默认就是 root 用户,但你不希望用 root 权限运行 ns-3(这是对的,ns3 工具会拒绝 root),你可以按以下方法创建一个 非 root 用户账号 并切换到它运行 ns-3。 一次性解决方案:创建非 roo…...

Mac软件卸载指南,简单易懂!
刚和Adobe分手,它却总在Library里给你写"回忆录"?卸载的Final Cut Pro像电子幽灵般阴魂不散?总是会有残留文件,别慌!这份Mac软件卸载指南,将用最硬核的方式教你"数字分手术"࿰…...
【决胜公务员考试】求职OMG——见面课测验1
2025最新版!!!6.8截至答题,大家注意呀! 博主码字不易点个关注吧,祝期末顺利~~ 1.单选题(2分) 下列说法错误的是:( B ) A.选调生属于公务员系统 B.公务员属于事业编 C.选调生有基层锻炼的要求 D…...

C++ 求圆面积的程序(Program to find area of a circle)
给定半径r,求圆的面积。圆的面积应精确到小数点后5位。 例子: 输入:r 5 输出:78.53982 解释:由于面积 PI * r * r 3.14159265358979323846 * 5 * 5 78.53982,因为我们只保留小数点后 5 位数字。 输…...
GitHub 趋势日报 (2025年06月06日)
📊 由 TrendForge 系统生成 | 🌐 https://trendforge.devlive.org/ 🌐 本日报中的项目描述已自动翻译为中文 📈 今日获星趋势图 今日获星趋势图 590 cognee 551 onlook 399 project-based-learning 348 build-your-own-x 320 ne…...

打手机检测算法AI智能分析网关V4守护公共/工业/医疗等多场景安全应用
一、方案背景 在现代生产与生活场景中,如工厂高危作业区、医院手术室、公共场景等,人员违规打手机的行为潜藏着巨大风险。传统依靠人工巡查的监管方式,存在效率低、覆盖面不足、判断主观性强等问题,难以满足对人员打手机行为精…...