仅当未指定标签时才运行 ansible 任务

cri*_*ret 5 tags ansible

假设我只想在特定标签不在命令行提供的标签列表中时运行任务,即使指定了其他标签。其中,只有最后一个在所有情况下都能按我的预期工作:

- hosts: all
  tasks:
    - debug:
        msg: 'not TAG (won't work if other tags specified)'
      tags: not TAG

    - debug:
        msg: 'always, but not if TAG specified (doesn't work; always runs)'
      tags: always,not TAG

    - debug:
        msg: 'ALWAYS, but not if TAG in ansible_run_tags'
      when: "'TAG' not in ansible_run_tags"
      tags: always
Run Code Online (Sandbox Code Playgroud)

尝试使用不同的 CLI 选项,你会希望看到为什么我觉得这有点令人困惑:

ansible-playbook tags-test.yml -l HOST
ansible-playbook tags-test.yml -l HOST -t TAG
ansible-playbook tags-test.yml -l HOST -t OTHERTAG
Run Code Online (Sandbox Code Playgroud)

问题:(a) 这是预期的行为吗?(b) 有没有更好的方法或我遗漏的一些逻辑?

我很惊讶我不得不深入研究 (undocumented, AFAICT) 变量ansible_run_tags


修正:有人建议我发布我的实际用例。我正在使用 ansible 来驱动 Debian 系列系统上的系统更新。我试图在最后通知是否需要重新启动,除非提供了标签reboot,在这种情况下会导致重新启动(并等待系统恢复)。这是相关的片段:

- name: check and perhaps reboot
  block:
  - name: Check if a reboot is required
    stat:
      path: /var/run/reboot-required
      get_md5: no
    register: reboot
    tags: always,reboot

  - name: Alert if a reboot is required
    fail:
      msg: "NOTE: a reboot required to finish uppdates."
    when:
      - ('reboot' not in ansible_run_tags)
      - reboot.stat.exists
    tags: always

  - name: Reboot the server
    reboot:
      msg: rebooting after Ansible applied system updates
    when: reboot.stat.exists or ('force-reboot' in ansible_run_tags)
    tags: never,reboot,force-reboot
Run Code Online (Sandbox Code Playgroud)

我认为我最初的问题仍然有价值,但我也愿意接受完成相同功能的替代方法。

cri*_*ret 10

为了完整起见,由于只有@paul-sweeney 提供了任何替代解决方案,我将用我目前的最佳解决方案回答我自己的问题,并让人们选择/投票他们最喜欢的:

---
- name: run only if 'TAG' not specified
  debug:
    msg: 'ALWAYS, but not if TAG in ansible_run_tags'
  when: "'TAG' not in ansible_run_tags"
  tags: always
Run Code Online (Sandbox Code Playgroud)