仅在未指定标签的情况下运行ansible任务

问题描述 投票:2回答:2

说我仅在命令行提供的标签列表中特定标签为NOT时才运行任务,即使指定了其他标签也是如此。在这些情况下,只有最后一个在所有情况下都可以正常工作:

- 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

尝试使用不同的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

问题:(a)这是预期的行为吗?和(b)是否有更好的方法或我缺少的逻辑?

我很惊讶,我不得不深入研究(未记录的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

我认为我最初的问题仍然有优点,但我也愿意接受实现此相同功能的替代方法。

tags ansible
2个回答
1
投票

我知道这是一个古老的问题,但我有类似的要求。

这可能是用另一种方法实现的最好的方法,但是……有时它可能是有用的。

如果已指定标签,就可以通过设置事实来实现,然后仅在未设置事实的情况下才输出消息,例如:

----名称:“仅在标签缺失时才运行测试任务”主持人:全部任务:-名称:“如果给定标签,则禁止显示消息”set_fact:抑制消息=是标签:永远重启-名称:“消息”调试:msg:“您没有说'reboot'”时间:未定义抑制消息

0
投票

为了完整起见,由于只有@ 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
© www.soinside.com 2019 - 2024. All rights reserved.