Ansible:为循环中的每个项目设置标签 [英] Ansible: Set Tags per Item in a Loop

查看:26
本文介绍了Ansible:为循环中的每个项目设置标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 with_item 语句中为每个项目设置 tags?

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

假设我有一个任务:

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

当用户在命令行中定义 --tags "second" 时,我只想安装 package_2.

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

是否可以使用 tags 表达式或任何其他方式来获得所需的行为?

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

推荐答案

我不相信这是可能的.yum 模块(我认为它类似于 apt)状态:

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

当与 playbook 中的包名循环一起使用时,ansible优化对 yum 模块的调用.而不是调用模块每次循环使用一个包时,ansible 调用模块一次,包含循环中的所有包名.

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.

您需要将命令拆分为两个单独的包任务,并在 package_2 任务上标记second".

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

编辑

请参阅下面的示例,该示例使用 when 条件迭代集合,因此它仅打印具有正确标签的第二项.希望这会有所帮助.

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"

这篇关于Ansible:为循环中的每个项目设置标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆