使用 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. 最…...

K8S认证|CKS题库+答案| 11. AppArmor
目录 11. AppArmor 免费获取并激活 CKA_v1.31_模拟系统 题目 开始操作: 1)、切换集群 2)、切换节点 3)、切换到 apparmor 的目录 4)、执行 apparmor 策略模块 5)、修改 pod 文件 6)、…...
React hook之useRef
React useRef 详解 useRef 是 React 提供的一个 Hook,用于在函数组件中创建可变的引用对象。它在 React 开发中有多种重要用途,下面我将全面详细地介绍它的特性和用法。 基本概念 1. 创建 ref const refContainer useRef(initialValue);initialValu…...
R语言AI模型部署方案:精准离线运行详解
R语言AI模型部署方案:精准离线运行详解 一、项目概述 本文将构建一个完整的R语言AI部署解决方案,实现鸢尾花分类模型的训练、保存、离线部署和预测功能。核心特点: 100%离线运行能力自包含环境依赖生产级错误处理跨平台兼容性模型版本管理# 文件结构说明 Iris_AI_Deployme…...
SciencePlots——绘制论文中的图片
文章目录 安装一、风格二、1 资源 安装 # 安装最新版 pip install githttps://github.com/garrettj403/SciencePlots.git# 安装稳定版 pip install SciencePlots一、风格 简单好用的深度学习论文绘图专用工具包–Science Plot 二、 1 资源 论文绘图神器来了:一行…...

智慧工地云平台源码,基于微服务架构+Java+Spring Cloud +UniApp +MySql
智慧工地管理云平台系统,智慧工地全套源码,java版智慧工地源码,支持PC端、大屏端、移动端。 智慧工地聚焦建筑行业的市场需求,提供“平台网络终端”的整体解决方案,提供劳务管理、视频管理、智能监测、绿色施工、安全管…...

P3 QT项目----记事本(3.8)
3.8 记事本项目总结 项目源码 1.main.cpp #include "widget.h" #include <QApplication> int main(int argc, char *argv[]) {QApplication a(argc, argv);Widget w;w.show();return a.exec(); } 2.widget.cpp #include "widget.h" #include &q…...

DBAPI如何优雅的获取单条数据
API如何优雅的获取单条数据 案例一 对于查询类API,查询的是单条数据,比如根据主键ID查询用户信息,sql如下: select id, name, age from user where id #{id}API默认返回的数据格式是多条的,如下: {&qu…...
Python 包管理器 uv 介绍
Python 包管理器 uv 全面介绍 uv 是由 Astral(热门工具 Ruff 的开发者)推出的下一代高性能 Python 包管理器和构建工具,用 Rust 编写。它旨在解决传统工具(如 pip、virtualenv、pip-tools)的性能瓶颈,同时…...
【无标题】路径问题的革命性重构:基于二维拓扑收缩色动力学模型的零点隧穿理论
路径问题的革命性重构:基于二维拓扑收缩色动力学模型的零点隧穿理论 一、传统路径模型的根本缺陷 在经典正方形路径问题中(图1): mermaid graph LR A((A)) --- B((B)) B --- C((C)) C --- D((D)) D --- A A -.- C[无直接路径] B -…...

vulnyx Blogger writeup
信息收集 arp-scan nmap 获取userFlag 上web看看 一个默认的页面,gobuster扫一下目录 可以看到扫出的目录中得到了一个有价值的目录/wordpress,说明目标所使用的cms是wordpress,访问http://192.168.43.213/wordpress/然后查看源码能看到 这…...