Ansible字典和标签 [英] Ansible Dict and Tags

查看:118
本文介绍了Ansible字典和标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本剧本,它使用在 vars:中声明的字典来创建EC2,然后将IP注册到一个组中以备后用.

I have a playbook creating EC2 by using a dictionary declared in vars: then registering the IPs into a group to be used later on.

字典看起来像这样:

servers:
  serv1:
    name: tag1
    type: t2.small
    region: us-west-1
    image: ami-****
  serv2:
    name: tag2
    type: t2.medium
    region: us-east-1
    image: ami-****
  serv3:
    [...]

我想以最简单的方式将标签应用于该剧本,因此我可以使用标签创建其中的一些标签.例如,使用--tags tag1,tag3运行剧本只会启动与serv1和serv3匹配的EC2.

I would like to apply tags to this playbook in the simplest way so I can create just some of them using tags. For example, running the playbook with --tags tag1,tag3 would only start EC2 matching serv1 and serv3.

在字典上应用标签似乎不太可能,我想避免执行类似的乘法任务:

Applying tags on the dictionary doesn't seem possible and I would like to avoid doing multiplying tasks like:

  • 创建EC2
  • 注册信息
  • 从先前注册的信息中获取私有IP
  • 将主机添加到组

虽然我已经有一个要立即创建所有EC2的工作循环,但是有什么方法可以实现这一点(无需依赖--extra-vars,这需要key = value)?例如,通过在运行EC2循环之前仅保留标记的内容来过滤字典?

While I already have a working loop for the case I want to create all EC2 at once, is there any way to achieve that (without relying on --extra-vars, which would need key=value) ? For example, filtering out the dictionary by keeping only what is tagged before running the EC2 loop ?

推荐答案

我找到了一种满足我的需求而又不涉及其他需求的方法,所以我分享了它,以防其他人有类似的需求. 我需要根据标签来组合字典,所以我的主"字典不会是静态的.

I found a way to match my needs without touching to the rest so I'm sharing it in case other might have a similar need. I needed to combine dictionaries depending on tags, so my "main" dictionary wouldn't be static.

变量变为:

- serv1:
  - name: tag1
    type: t2.small
    region: us-west-1
    image: ami-****
- serv2:
  - name: tag2
    type: t2.medium
    region: us-east-1
    image: ami-****
- serv3:
 [...]

因此,我没有重复执行任务,而是将 set_fact 标签一起使用,如下所示:

So instead of duplicating my tasks, I used set_fact with tags like this:

- name: Combined dict
# Declaring empty dict
  set_fact:
    servers: []
  tags: ['always']
- name: Add Server 1
  set_fact:
    servers: "{{ servers + serv1 }}"
  tags: ['tag1']
- name: Add Server 2
  set_fact:
    servers: "{{ servers + serv2 }}"
  tags: ['tag2']
[..]

使用20行代替每个服务器的乘法任务,将vars从字典更改为列表,添加几个标签,然后一切都很好:)现在,如果我添加一个新服务器,则只需花费几行.

20 lines instead of multiply tasks for each server, change vars from dictionary to lists, a few tags and all good :) Now if I add a new server it will only take a few lines.

这篇关于Ansible字典和标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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