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

查看:81
本文介绍了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:

当与剧本中的程序包名称循环一起使用时, 优化对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天全站免登陆