如果我只想获取其标签的env值为"dev"的EC2实例, ,如何根据此脚本修改代码? [英] If I just wanted to get EC2 instances whose value of tag's env is "dev" , how should I modify code based on this script?

查看:98
本文介绍了如果我只想获取其标签的env值为"dev"的EC2实例, ,如何根据此脚本修改代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[此脚本允许我获取所有实例]

[This script let me get all instances]

如何使用Python字典按标签名称对AWS实例进行分组?

当我在此链接中运行脚本时:

When I run the script in this link :

#!/usr/bin/env python
# -*- encoding: utf8 -*-

import boto.ec2
conn = boto.ec2.connect_to_region('us-west-1')
reservations = conn.get_all_instances()
InstanceMap={}
for reservation in reservations:
    for instance in reservation.instances:
        if 'Name' in instance.tags:
            tag_name = instance.tags['Name']
            if tag_name in InstanceMap:
                InstanceMap[tag_name].append(instance.id)
            else:
                InstanceMap[tag_name] = [instance.id,]

我获得了所有EC2实例ID和实例标签的名称.

I get all EC2 Instances ID and Instances tag's name.

结果是

{'ap1-dev': ['i-04ebd1403d93bef01'],

 'ap1-prod': ['i-08f0c8a3f495bad71', 'i-0508a3800cd0ec331'],

 'ap1-stage': ['i-0716b2fd4089c7471', 'i-025002d2da8396171'],

 'ap2-dev': ['i-08ffb39676b7b1c81'],

 'ap2-prod': ['i-019dbf70c2f061521', 'i-0d2d482cb85419131'],

 'ap2-stage': ['i-04d71424b7257b4b1', 'i-02c0046baae635d31']}

实例标签名称的值为ap1-dev,其标签环境的值为dev

The value of instance tags's name is ap1-dev , the value of its tags's env is dev

instacne标签名称的值是ap1-prod,其标签env的值是prod

The value of instacne tags's name is ap1-prod, the value of its tags's env is prod

现在我的问题是:

如果我只想获取其标签的env值为"dev"的EC2实例. 我想要得到的结果是:

If I just wanted to get EC2 instances whose value of tag's env is "dev" . The result I want to get is this :

{'ap1-dev': ['i-04ebd1403d93bef01'],

 'ap2-dev': ['i-08ffb39676b7b1c81']}

如何基于此脚本修改代码?

How should I modify code based on this script?

推荐答案

您要考虑以-dev结尾的标签.

You want to consider the tags which end with -dev.

更改此行:

if 'Name' in instance.tags:

收件人:

if 'Name' in instance.tags and instance.tags['Name'].endswith('-dev'):

您也可以将此方法用作方法,并传递devprodstage之类的环境",而不是每次都修改代码.

You can also make this as a method and pass your "environment" like dev, prod, stage instead of modifying code each time.

这篇关于如果我只想获取其标签的env值为"dev"的EC2实例, ,如何根据此脚本修改代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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