How can I run only ansible tasks with multiple tags?

Ansible tags use "or" not "and" as a comparison. Your solution to create yet another tag is the appropriate one.


Use the following to run the task if both fooand bar are given (i.e. 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 ''}}"

If you need it to run either when foo or bar or both fooand bar are given (i.e. ansible-playbook foo.yml -t foo, ansible-playbook foo.yml -t bar or ansible-playbook foo.yml -t foo,bar) then use the following:

- 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

Try when directive:

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