我想在aws ec2中完成以下内容:
现在,我想使用安全组名称而不是id,因为我希望能够在需要时使用ansible重新创建整个基础结构。
重新创建安全组会导致组的ID不同。 但ec2_lc模块只接受安全组ID。
有什么方法可以将安全组ID映射到名称?
我正在定义这样的安全组:
- name: create ec2 group
ec2_group:
name: "{{ item.name }}"
description: "{{ item.description }}"
vpc_id: "{{ item.vpc_id }}"
region: "{{ item.region }}"
state: present
rules: "{{ item.rules }}"
rules_egress: "{{ item.rules_egress }}"
register: sg
启动配置代码如下所示:
- name: Create Launch Configuration
ec2_lc:
region: "{{ item.region }}"
name: "{{ item.name }}"
image_id: "{{ item.image_id }}"
key_name: "{{ item.key_name }}"
security_groups: "{{ item.security_groups }}" # how can i refer to specific group_id based on a group name?
instance_type: "{{ item.instance_type }}"
user_data: "{{ item.ec2_user_data }}"
instance_profile_name: "{{ item.instance_profile_name }}"
assign_public_ip: "{{ item.assign_public_ip }}"
答案 0 :(得分:0)
对this问题表示敬意,你可以试试这个:
- name: Create Launch Configuration
ec2_lc:
...
security_groups: "{{ sg.results | selectattr('item.name','equalto',item) | join('',attribute='group_id') }}"
...
答案 1 :(得分:0)
您可以编写一个过滤器,可以动态地为您进行aws api调用。 例如,我的vars / main.yml
中有类似的东西public_sg_id: "{{ 'Public' |get_sg(public_vpc_id, aws_region) }}"
以下是get_sg过滤器的代码。
import boto.ec2
from ansible import errors
def get_sg(name, vpc_id, region):
connect = boto.ec2.connect_to_region(region)
filter_by = {
"tag-key": "Name",
"tag-value": name,
"vpc-id": vpc_id
}
sg_groups = connect.get_all_security_groups(filters=filter_by)
if len(sg_groups) == 1:
return sg_groups[0].id
elif len(sg_groups) > 1:
raise errors.AnsibleFilterError(
"Too many results for {0}: {1}".format(
name, ",".join(sg_groups)
)
)
else:
raise errors.AnsibleFilterError(
"Security Group {0} was not found".format(name)
)
答案 2 :(得分:0)
使用ec2_group-facts按名称查询安全组:
- ec2_group_facts:
filters:
group-name:
- "{{ sg.name }}"
register: ec2sgs
- debug:
msg: "{{ ec2sgs.security_groups | map(attribute='group_id')| list }}"