根据 AWS 标签分配 ansible 变量 [英] Assign ansible vars based on AWS tags

查看:26
本文介绍了根据 AWS 标签分配 ansible 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据我在 AWS 中拥有的标签找出一种在 Ansible 中分配变量的方法.我正在尝试使用 ec2_remote_tags 但它返回的信息比我需要的要多得多.似乎应该有一种更简单的方法来做到这一点,而我只是没有想到.

I'm trying to figure out a way to assign variables in Ansible based on tags I have in AWS. I was experimenting with ec2_remote_tags but it's returning alot more information than I need. It seems like there should be an easier way to do this and I'm just not thinking of it.

例如,如果我有一个名为 function 的标签,它使用动态库存创建了 tag_function_api 组,并且我想分配一个变量 function到值 api.有什么想法可以有效地做到这一点吗?

For example, if I have a tag called function that creates the tag_function_api group using dynamic inventory and I want to assign a variable function to the value api. Any ideas on an efficient way to do this?

推荐答案

我已经成功地制作了一个带有值列表的标签字典:

I've managed to make a dict of tags with lists of values:

- hosts: localhost
  tasks:
    - ec2_remote_facts:
        region: eu-west-1
      register: ec2_facts

    # get all possible tag names
    - set_fact: tags="{{ item.keys() }}"
      with_items: "{{ ec2_facts.instances | map(attribute='tags') | list }}"
      register: tmp_tags

    # get flattened list of tags (for some reason lookup() returns string, so we use with_)
    - assert: that=true
      with_flattened: "{{ tmp_tags.results | map(attribute='ansible_facts.tags') | list }}"
      register: tmp_tags

    # get unique tag names
    - set_fact: tags="{{ tmp_tags.results | map(attribute='item') | list | unique }}"

    - set_fact: my_tags="{{ {} }}"

    # get all possible values for a given tag
    - set_fact:
        my_tags: "{{ my_tags | combine( {''+item: ec2_facts.instances | map(attribute='tags.'+item) | select('defined') | list | unique}) }}"
      with_items: "{{ tags }}"

    - debug: var=my_tags

这篇关于根据 AWS 标签分配 ansible 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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