当前位置: 首页 > 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/

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • Centos服务器root用户禁止远程登录
  • Html5总结
  • Node.js(8)——Express的基本使用
  • Opencv调用yolov5的onnx文件时报错记录
  • B站宋红康JAVA基础视频教程个人笔记chapter03
  • 22 - grace数据处理 - 补充 - 泄露误差改正 - Slepian局部谱分析法(二) - Slepian谱分析程序包初始化
  • Elasticsearch下篇
  • 《数据结构(C语言版)第二版》第五章-树和二叉树(5.6 树和森林)
  • 门控循环单元GRU
  • Eclipse 悬浮提示:提高编程效率的利器
  • 基于Springboot的运行时动态可调的定时任务
  • 【Java数据结构】---泛型
  • JVM类加载中的双亲委派机制
  • 智能闹钟能改善睡眠质量吗
  • vue使用响应式API和页面组件ref相同名称问题
  • Android组件 - 收藏集 - 掘金
  • linux学习笔记
  • Spring Cloud Feign的两种使用姿势
  • Twitter赢在开放,三年创造奇迹
  • 一个JAVA程序员成长之路分享
  • ​​​​​​​sokit v1.3抓手机应用socket数据包: Socket是传输控制层协议,WebSocket是应用层协议。
  • ​力扣解法汇总1802. 有界数组中指定下标处的最大值
  • # windows 安装 mysql 显示 no packages found 解决方法
  • (4)事件处理——(2)在页面加载的时候执行任务(Performing tasks on page load)...
  • (6)添加vue-cookie
  • (SpringBoot)第二章:Spring创建和使用
  • (附源码)ssm旅游企业财务管理系统 毕业设计 102100
  • (回溯) LeetCode 78. 子集
  • (入门自用)--C++--抽象类--多态原理--虚表--1020
  • (转)ABI是什么
  • (转)拼包函数及网络封包的异常处理(含代码)
  • (转)淘淘商城系列——使用Spring来管理Redis单机版和集群版
  • (最全解法)输入一个整数,输出该数二进制表示中1的个数。
  • * 论文笔记 【Wide Deep Learning for Recommender Systems】
  • .Net 6.0 处理跨域的方式
  • .net core 使用js,.net core 使用javascript,在.net core项目中怎么使用javascript
  • .net core 外观者设计模式 实现,多种支付选择
  • .net FrameWork简介,数组,枚举
  • .NET处理HTTP请求
  • @Conditional注解详解
  • @在php中起什么作用?
  • []sim300 GPRS数据收发程序
  • [Algorithm][动态规划][简单多状态DP问题][按摩师][打家劫舍Ⅱ][删除并获得点数][粉刷房子]详细讲解
  • [AutoSar]BSW_Com07 CAN报文接收流程的函数调用
  • [C#]winform利用seetaface6实现C#人脸检测活体检测口罩检测年龄预测性别判断眼睛状态检测
  • [codevs 2822] 爱在心中 【tarjan 算法】
  • [leetcode hot 150]第一百三十七题,只出现一次的数字Ⅱ
  • [Linux] 用LNMP网站框架搭建论坛
  • [Linux]:权限
  • [loj#115] 无源汇有上下界可行流 网络流
  • [Meachines] Lame smbd3.0-RCE
  • [misc]-流量包-wireshark-icmp
  • [one_demo_6]逆置整数
  • [Paper]Application of deep convolutional neural network for automated detection of myocardial...
  • [Phoenix] 七、如何使用自增ID