注:机翻,未校。
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 block
block:
- name: Task 1
ansible.builtin.command: echo "This is task 1"
- name: Task 2
ansible.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 example
hosts: localhost
vars:
run_tasks: true
tasks:
- name: Execute tasks if condition is met
block:
- name: Task 1
ansible.builtin.command: echo "This is task 1"
- name: Task 2
ansible.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 a