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

查看:19
本文介绍了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 运行 playbook 只会启动 EC2 匹配 serv1 和 serv3.

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 行而不是为每个服务器增加多个任务,将变量从字典更改为列表,几个标签,一切都很好:) 现在如果我添加一个新服务器,它只需要几行.

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天全站免登陆