如何使用资源名称前缀使用预先定义的标记集标记AWS资源



我在python方面经验不足,正在寻找构建lambda的想法,该lambda通过在实例名称标记中使用前缀来标记AWS资源,尤其是ec2实例及其卷。

示例:

  • dev-cassandra-01
  • dev-cassandra-02

我想通过使用前缀";dev cassandra";其应当应用于使用该前缀创建的任何新实例。

类似地,不同应用程序实例的不同标签集。

这可以通过配置工具应用于常规实例,但不能应用于现有的ASG实例。

您可以使用资源方法create_instances在创建实例时插入标记"TagSpecifications"属性中。

或者,您也可以使用客户端方法create_tags编辑特定的实例标记。对于此方法,您需要首先获得实例id。前缀逻辑可以根据需要添加到python脚本中。

以下是这些方法的两个例子:

创建实例

# Getting resource object with aws credentials
s = boto3.Session(
region_name=<region_name>,
aws_access_key_id=<aws_access_key>,
aws_secret_access_key=<aws_secret_access_key>,
)
ec2 = s.resource('ec2')
# Some of these options are optional
instance = ec2.create_instances(
ImageId=<ami_id>,
MinCount=1,
MaxCount=1,
InstanceType=<instance_type>,
KeyName=<instance_key_pair>,
IamInstanceProfile={
'Name': <instance_profile>
},
SecurityGroupIds=[
<instance_security_group>,
],
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [
{
'Key': <key_name>,
'Value': <value_data>,
},
]
},
],
)

create_tags:

# Next line is for getting client object from resource object
ec2_client = ec2.meta.client  
ec2_client.create_tags(
Resources=[
<instance_id>,
],
Tags=[
{
'Key': 'Name',
'Value': <dev-cassandra><_your_name>
},
{
'Key': <key_name>,
'Value': <value_data>,
},
]
)

值得一提的是;实例名称";也是一个标签。例如:

{
'Key': 'Name',
'Value': <dev-cassandra><_your_name>
}

最新更新