Ansible: Set Tags per Item in a Loop

2019-06-05 04:01发布

Is it possible to set tags per each item in a with_item statement?

Assume I have a task:

- name: ensure required packages are installed
  apt: pkg={{ item }} state=present
  with_items:
    - package_1
    - package_2
  sudo: yes

When user defines --tags "second" in a command line I want only package_2 to be installed.

Is it possible to do with tags expression or any other ways to get desired behaviour?

标签: ansible
1条回答
贪生不怕死
2楼-- · 2019-06-05 04:28

I don't believe this is possible. The yum module (which I imagine is similar to apt) states:

When used with a loop of package names in a playbook, ansible optimizes the call to the yum module. Instead of calling the module with a single package each time through the loop, ansible calls the module once with all of the package names from the loop.

You would need to split the command into two seperate package tasks with tag "second" on the package_2 task.

EDIT

See below of an example of iterating a collection with a when condition so it only prints the second item with the correct tag. Hopefully this helps.

---
- name: Only run certain items in a list
  hosts: localhost
  tasks:
      - name: Echo items based on a tag condition
        shell: echo {{item.cmd}}
        with_items:
           - {cmd: 'package_1', tag: 'first'} 
           - {cmd: 'package_2', tag: 'second'}
        when: item.tag == "second"
查看更多
登录 后发表回答