如何仅运行具有多个标签的ansible任务?

38

想象一下这个 Ansible Playbook:

- name: debug foo
  debug: msg=foo
  tags:
     - foo

- name: debug bar
  debug: msg=bar
  tags:
     - bar

- name: debug baz
  debug: msg=baz
  tags:
     - foo
     - bar

我该如何仅运行debug baz任务?我想要运行所有被标记为foobar的任务。这可能吗?
我尝试了以下内容,但它会运行所有三个任务:
ansible-playbook foo.yml -t foo,bar

5
到目前为止,我唯一的解决方法是使用复合标签,例如tags: ['foo', 'bar', 'foo-bar'],但这有点难看...... :-( - chmac
这个工作得非常好!非常感谢。可惜,这个答案没有被接受。 - Judge
5个回答

31

Ansible标签使用“或”而不是“和”作为比较条件。创建另一个标签的解决方案是合适的。


5
尝试使用 when 指令:
- name: debug foo
  debug: msg=foo
  tags:
     - foo

- name: debug bar
  debug: msg=bar
  tags:
     - bar

- name: debug baz
  debug: msg=baz
  when:
    - '"foo" in ansible_run_tags'
    - '"bar" in ansible_run_tags'

1
如果只提供一个标签(foobar),则此命令不会运行baz。如果没有标签调用ansible,也不会运行此命令。 - wolfrevo
这对我有用,谢谢。@wolfrevo,那是预期的行为。 - gambarimas87

2

如果同时给定foobar,请使用以下命令来运行任务(即ansible-playbook foo.yml -t foo,bar):

- debug:
    msg: "(foo and bar)"
  tags:
    - "{{ 'always' if 'foo' in ansible_run_tags and 'bar' in ansible_run_tags else ''}}"

如果需要在给定foobar或两者都给定(即ansible-playbook foo.yml -t fooansible-playbook foo.yml -t baransible-playbook foo.yml -t foo,bar)时运行它,请使用以下命令:

- debug:
    msg: "(foo and bar) or foo or bar"
  tags:
    - "{{ 'always' if 'foo' in ansible_run_tags and 'bar' in ansible_run_tags else ''}}"
    - foo
    - bar

-2
如果您使用这种方式:
- name: debug baz
  debug: msg=baz
  tags:
    - foo
    - bar

你进行了一个OR操作。因此,如果你使用以下命令:

ansible-playbook -i inventory test.yml --tags foo

或者

ansible-playbook -i inventory test.yml --tags bar

将执行此任务。

如果您使用:

- name: debug baz
  debug: msg=baz
  tags:
    - foo, bar

你进行了一个 AND 操作。因此只有命令:

ansible-playbook -i inventory test.yml --tags foo, bar

将执行此任务。


2
那不起作用。像你的“AND”示例中定义的任务在这样调用时不会被执行。 - Judge
1
如果标签之间有空格,您需要将标签放在引号中:--tags“foo,bar” - rubo77

-2

我相信正确的语法是:

- name: debug baz
  debug: msg=baz
  tags: foo, bar

抱歉,标记错误了。实际上,这就是在playbook中的样子。 - foofunner
好的,我认为这是关于给单个元素分配多个标签,但我不认为它有助于仅运行具有多个标签的元素... - chmac
1
好的,我的错,我误解了你的问题。很遗憾,你不能通过标签来实现这一点。标签总是运行标签的并集。它们会像OR运算符而不是AND运算符一样应用它们。所以我认为Bruce是正确的。 - foofunner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接