当前位置: 首页 > news >正文

使用 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.
在此示例中,两个任务都分组在一个块中。 可以将通用属性应用于整个块,例如 whenbecomerescue

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_taskstrue 时,两个任务才会运行。

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复杂表头&#xff0c;表头合并单元格 效果预览 一、maven依赖 <!--操作excel --><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.1.1</version><scope>test</…...

Java整合腾讯云发送短信实战Demo

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

电路中电阻,电容和电感作用总结

电阻作用 1&#xff0c;上拉电阻 电阻的连接一般是一端接上拉的电源&#xff08;一般与芯片信号的电压值相匹配&#xff09;&#xff0c;另一端连接芯片引脚所对应的信号大概如下图 功能&#xff1a;一、预置某些引脚的功能&#xff0c;例如复位信号拉高&#xff08;失能&…...

OrangePi AIpro学习1 —— 烧写和ssh系统

目录 一、下载烧写工具和系统 二、烧写和启动 2.1 烧写和启动 2.2 烧写失败后的问题解决 三、串口连接到主机 3.1 串口连接到主机 四、网络连接到主机 4.1 修改香橙派IP地址 4.2 win11配置以太网静态ip 4.4 主机和香橙派直连 4.5 主机和香橙派连接到同一个路由器 五…...

Gather 全球化进程迅速 多重利好推动未来发展

在过去的几周里&#xff0c;Gather的全球化发展十分迅速&#xff0c;并取得了一系列重要成绩&#xff0c;这些成绩进一步巩固了Gather在区块链和去中心化通信领域的地位&#xff0c;并为未来的发展注入了强劲的动力。 $GAT代币成功进驻多家顶级交易所 7月19日&#xff0c;Gath…...

面试经典 222. 完全二叉树的节点个数

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

【css】3d柱状图-vue组件版

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

《计算机组成原理》(第3版)第3章 系统总线 复习笔记

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

【网络安全】https协议的加密方案避免中间人攻击(MITM攻击)导致的数据泄露风险

目录 引言 概念准备 中间人 加密 数据摘要 && 数据指纹 数字签名 密钥加密 中间人攻击 CA证书 https加密的解决方案 个人主页&#xff1a;东洛的克莱斯韦克-CSDN博客 引言 http在应用层协议中是明文传输协议&#xff0c;它是通信双方传输数据时的一种约定。【…...

拼多多商家电话采集 拼多多店铺爬虫软件使用教程

拼多多商家电话采集和店铺爬虫软件使用教程&#xff1a; 商家电话采集&#xff1a; a. 打开拼多多网站&#xff0c;进入需要采集电话号码的店铺页面。 b. 打开浏览器开发者工具&#xff08;一般按F12键或右键选择“检查”&#xff09;。 c. 在开发者工具中切换到“网络”或“Ne…...

RK3566 MIPI屏调试记录

文章目录 1. 前言2. 环境介绍3. 思路介绍4. 确认要修改的设备树文件5. 设备树中修改关键引脚5.1. 添加dsi0节点5.2. 修改屏幕背光引脚5.3. 添加屏幕复位引脚5.4. 添加屏幕使能引脚 6. 修改屏幕timing参数7. 修改上下电时序8. 修改初始化序列和反初始化序列9. 显示路由配置10. 最…...

爬虫数据模拟真实设备请求头User-Agent生成(fake_useragent:一个超强的Python库)

在Python开发中&#xff0c;处理HTTP请求时经常需要模拟不同的用户代理&#xff08;User-Agent&#xff09;来绕过网站的反爬虫机制或进行兼容性测试。fake_useragent正是这样一个强大的Python库&#xff0c;它能够生成随机且多样化的用户代理字符串&#xff0c;让你的请求看起…...

【教育宝-注册安全分析报告】

前言 由于网站注册入口容易被黑客攻击&#xff0c;存在如下安全问题&#xff1a; 暴力破解密码&#xff0c;造成用户信息泄露短信盗刷的安全问题&#xff0c;影响业务及导致用户投诉带来经济损失&#xff0c;尤其是后付费客户&#xff0c;风险巨大&#xff0c;造成亏损无底洞…...

3.达梦数据库基础运维管理

文章目录 前言一、基础数据库管理权限角色管理1.1 DM 系统管理员的类型1.2 角色责则分类 DM 数据库2.1 数据库评估2.2 状态和模式 参考内容 前言 本篇博客为上一篇博客的进阶版&#xff0c;主要针对常规达梦数据库的基本管理上面 一、基础数据库管理 权限角色管理 1.1 DM 系…...

【Linux】【系统纪元】Linux起源与环境安装

快乐的流畅&#xff1a;个人主页 个人专栏&#xff1a;《C游记》《进击的C》《Linux迷航》 远方有一堆篝火&#xff0c;在为久候之人燃烧&#xff01; 文章目录 一、Linux的起源1.1 计算机硬件1.2 计算机软件 二、Linux的环境安装2.1 安装方式2.2 安装版本2.3 安装过程2.4 远程…...

Android笔试面试题AI答之Activity(9)

文章目录 1.如何在Application中获取当前Activity实例 &#xff1f;方法一&#xff1a;使用全局变量或单例方法二&#xff1a;使用LocalBroadcastManager或EventBus方法三&#xff1a;通过Fragment方法四&#xff1a;使用Service和Intent注意事项 2.Activity A跳转Activity B&a…...

什么是嵌入式

1、什么是嵌入式 对专用设备的控制&#xff0c;把不需要的功能能够裁剪、删除&#xff0c;适配于专用设备&#xff0c;就叫做嵌入式&#xff08;也叫做嵌入式系统&#xff09; 嵌入式系统定义&#xff1a;用于控制、监视或者辅助机器和设备的运行 一个嵌入式系统由硬件和软件…...

SAM 2:Segment Anything in Images and Videos 论文详解

SAM 2:Segment Anything in Images and Videos 文章目录 SAM 2:Segment Anything in Images and Videos摘要1 Introduction具体分析 2 Related work具体分析&#xff1a; 3 任务&#xff1a;可提示的视觉分割4 模型具体分析具体分析 5 数据5.1 Data engine5.2 SA - V数据集 6 Z…...

PYTHON专题-(10)基操之我要玩并发

什么是并发&#xff1f; 并发指的是两个或多个事件在同一时间间隔内发生。在计算机科学中&#xff0c;并发通常指的是一个程序同时执行多个独立的任务。这些任务可以同时进行&#xff0c;而不会相互干扰或阻塞彼此。并发可以提高程序的执行效率和资源利用率&#xff0c;但也需要…...

双指针实现删除字符串中的所有相邻重复项

class Solution:def removeDuplicates(self, s: str) -> str:res list(s)slow fast 0length len(res)while fast < length:# 如果一样直接换&#xff0c;不一样会把后面的填在slow的位置res[slow] res[fast]# 如果发现和前一个一样&#xff0c;就退一格指针if slow …...

vue(vue2和vue3)项目打包去除console.log

1.Vue2去除 module.exports { configureWebpack: (config) > {// 取消console打印config.optimization.minimizer[0].options.terserOptions.compress.drop_console truereturn {name: "项目名称",resolve: {alias: {"": resolve("src")}}…...