【问题标题】:How can I run only ansible tasks with multiple tags?如何仅运行具有多个标签的 ansible 任务?
【发布时间】:2015-05-04 17:23:57
【问题描述】:

想象一下这个可靠的剧本:

- 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 标记的任务。这可能吗?

我试过了,但它会运行所有 3 个任务:

ansible-playbook foo.yml -t foo,bar

【问题讨论】:

  • 到目前为止,我唯一的解决方法是使用像 tags: ['foo', 'bar', 'foo-bar'] 这样的复合标签,这有点难看...... :-(
  • 这个工作就像一个魅力!非常感谢。可悲的是,这未被接受为答案。

标签: ansible ansible-playbook


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    试试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'
    

    【讨论】:

    • 如果只给出一个标签(foobar),这将不会运行baz。如果在没有标签的情况下调用 ansible,这也不会运行
    【解决方案3】:

    如果同时给出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 ''}}"
    

    如果您需要它在foobarfoobar 都给出时运行(即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
    

    【讨论】:

      【解决方案4】:

      我相信正确的语法是:

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

      【讨论】:

      • 抱歉标记不正确。实际上就是剧本中的样子。
      • 好的,认为这是关于将多个标签分配给单个元素,但不要认为只运行具有 multiple 标签的元素会有帮助...
      • 好吧,我的错,我误解了你的问题。不幸的是,你不能通过标签来做到这一点。标签将始终运行标签的联合。它将像 OR 运算符与 AND 运算符一样应用它们。所以我认为布鲁斯是正确的
      【解决方案5】:

      如果你用这种方式:

      - 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
      

      将执行此任务。

      【讨论】:

      • 那行不通。在您的“AND”示例中定义的任务在这样调用时不会执行。
      • 如果标签之间有空格,则需要将标签放在引号中:--tags "foo, bar"
      猜你喜欢
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2020-08-20
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      相关资源
      最近更新 更多