使用 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 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.
在此示例中,两个任务都分组在一个块中。 可以将通用属性应用于整个块,例如 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 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 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 example
  hosts: localhost
  tasks:
    - name: Block with error handling
      block:
        - name: Task that might fail
          ansible.builtin.command: /bin/false

        - name: Task that won't be executed
          ansible.builtin.command: echo "This won't run"

      rescue:
        - name: Handle the error
          ansible.builtin.command: echo "An error occurred"

      always:
        - name: This always runs
          ansible.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 example
  hosts: localhost
  tasks:
    - name: Block with privilege escalation
      block:
        - name: Task 1 as root
          ansible.builtin.command: echo "Task 1 as root"

        - name: Task 2 as root
          ansible.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 example
  hosts: localhost
  tasks:
    - name: Outer block
      block:
        - name: Task in outer block
          ansible.builtin.command: echo "This is in the outer block"

        - name: Inner block
          block:
            - name: Task in inner block
              ansible.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 example
  hosts: localhost
  tasks:
    - name: Block with handler notification
      block:
        - name: Task that changes something
          ansible.builtin.command: echo "This changes something"
          notify: Restart service

        - name: Another task
          ansible.builtin.command: echo "This is another task"
      notify: Restart service

  handlers:
    - name: Restart service
      ansible.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:

  • 8
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值