简体   繁体   English

使用 boto,我如何命名新生成的 EC2 实例?

[英]With boto, how can I name a newly spawned EC2 instance?

I'm using boto to spawn a new EC2 instance based on an AMI.我正在使用 boto 生成一个基于 AMI 的新 EC2 实例。

The ami.run method has a number of parameters, but none for "name" - maybe it's called something different? ami.run 方法有许多参数,但没有用于“名称”的参数 - 也许它被称为不同的东西?

import boto
c = boto.connect_ec2(ec2_key, ec2_secret)
image = c.get_image(ec2_ami)

reservation = image.run(key_name=ec2_keypair,
                        security_groups=ec2_secgroups,
                        instance_type=ec2_instancetype)

instance = reservation.instances[0]
c.create_tags([instance.id], {"Name": instance_name})

In EC2 there's no api to change the actually name of the machine.在 EC2 中,没有 api 可以更改机器的实际名称。 You basically have two options.你基本上有两个选择。

  1. You can pass the desired name of the computer in the user-data and when the server starts run a script that will change the name of the computer.您可以在用户数据中传递所需的计算机名称,并在服务器启动时运行将更改计算机名称的脚本。
  2. You can use an EC2 tag to name the server ec2-create-tags <instance-id> --tag:Name=<computer name> .您可以使用 EC2 标签来命名服务器ec2-create-tags <instance-id> --tag:Name=<computer name> Downside to this solution is the server wont actually update to this name.此解决方案的缺点是服务器实际上不会更新到此名称。 This tag is strictly for you or for when you're querying the list of servers in aws.此标签仅适用于您或在 aws 中查询服务器列表时使用。

Generally speaking if you're at the point where you want your server to configure itself when starting up I've found that renaming your computer in EC2 just causes more trouble than it's worth.一般来说,如果您希望您的服务器在启动时自行配置,我发现在 EC2 中重命名您的计算机只会带来更多的麻烦。 I suggest not using them if you don't have to.如果没有必要,我建议不要使用它们。 Using the tags or elb instances is the better way to go.使用标签或 elb 实例是更好的方法。

For those who are looking for the boto3 version of @Roberto 's answer:对于那些正在寻找 @Roberto 答案的boto3版本的人:

ec2 = boto3.resource('ec2')
ec2.create_tags(Resources=[instance.id], Tags=[
        {
            'Key': 'Name',
            'Value': instance_name,
        },
    ])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM