首页 > 解决方案 > 如何在 Ansible 中为块添加标签?

问题描述

Ansible 举个例子:

https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html#adding-tags-to-blocks

# myrole/tasks/main.yml
tasks:
- block:
  tags: ntp

并说“使用块并在该级别定义标签”,然后在此页面上:

https://docs.ansible.com/ansible/latest/user_guide/playbooks_blocks.html

他们使用:

 tasks:
   - name: Install, configure, and start Apache
     block:
       - name: Install httpd and memcached
         ansible.builtin.yum:
           name:
           - httpd
           - memcached
           state: present

如果我尝试“使用块并在该级别定义标签”,例如:

 tasks:
   - name: Install, configure, and start Apache
     block:
     tag: broken
       - name: Install httpd and memcached

或(绝望地)

 tasks:
   - name: Install, configure, and start Apache
     block:
     - tag: broken
       - name: Install httpd and memcached
     

我得到:

Syntax Error while loading YAML.
  did not find expected key

有什么问题,您如何为第二个示例添加标签?

标签: ansibleyaml

解决方案


标签(和任何其他块 keyworkds)放在之外,例如在块之前

 tasks:
   - name: Install, configure, and start Apache
     tags: not_broken
     block:
       - name: Install httpd and Memcached
       ...

, 或在块结束之后

 tasks:
   - name: Install, configure, and start Apache
     block:
       - name: Install httpd and Memcached
       ...
     tags: not_broken

文件说_

“块中的所有任务都继承在块级别应用的指令。”

这不适用于tagsa 内部block。下面的代码片段将失败并显示消息mapping values are not allowed in this context

- block:
  tags: ntp
  - name: Install ntp

它已经在上游修复了。tags位于 之外的代码片段block按预期工作

- name: ntp tasks
  tags: ntp
  block:
  - name: Install ntp

在此上下文中不允许映射值

当你tags放入block例如

    - name: Block
      block:
      tags: t1
        - name: Task
          debug:
            msg: Task 1

播放将失败并显示错误消息

ERROR! Syntax Error while loading YAML.
  mapping values are not allowed in this context

“标签”不是块的有效属性

正确的关键字不是例如tagstag

    - name: Block
      tag: t1
      block:
        - name: Task
          debug:
            msg: Task 1

播放将失败并显示错误消息

ERROR! 'tag' is not a valid attribute for a Block

推荐阅读