21

インスタンスを作成するときにタグを指定するbotopythonAPIを使用する方法はありますか?インスタンスを作成し、それをフェッチしてからタグを追加する必要がないようにしようとしています。次のコマンドを実行するときに、特定のタグを持つようにインスタンスを事前構成するか、タグを指定する方がはるかに簡単です。

ec2server.create_instance(
        ec2_conn, ami_name, security_group, instance_type_name, key_pair_name, user_data
    )
4

4 に答える 4

23

この回答は、執筆時点では正確でしたが、現在は古くなっています。AWS APIとライブラリ(boto3など)は、「create_instances」呼び出しの実行時にタグを指定できる「TagSpecification」パラメーターを使用できるようになりました。


インスタンスが作成されるまで、タグを作成することはできません。関数はcreate_instanceと呼ばれますが、実際に実行しているのは予約とインスタンスです。次に、そのインスタンスが起動される場合と起動されない場合があります。(通常はそうですが、時々...)

そのため、タグが起動されるまでタグを追加することはできません。そして、ポーリングせずに起動されたかどうかを判断する方法はありません。そのようです:

reservation = conn.run_instances( ... )

# NOTE: this isn't ideal, and assumes you're reserving one instance. Use a for loop, ideally.
instance = reservation.instances[0]

# Check up on its status every so often
status = instance.update()
while status == 'pending':
    time.sleep(10)
    status = instance.update()

if status == 'running':
    instance.add_tag("Name","{{INSERT NAME}}")
else:
    print('Instance status: ' + status)
    return None

# Now that the status is running, it's not yet launched. The only way to tell if it's fully up is to try to SSH in.
if status == "running":
    retry = True
    while retry:
        try:
            # SSH into the box here. I personally use fabric
            retry = False
        except:
            time.sleep(10)

# If we've reached this point, the instance is up and running, and we can SSH and do as we will with it. Or, there never was an instance to begin with.
于 2012-05-24T02:39:35.720 に答える
3

boto 2.9.6 を使用すると、run_instances から応答が返された直後にインスタンスにタグを追加できます。このようなものはスリープなしで動作します:

reservation = my_connection.run_instances(...)
for instance in reservation.instances:
    instance.add_tag('Name', <whatever>)

タグを正常に追加した後、インスタンスがまだ保留状態であることを確認しました。元の投稿で要求されたものと同様の関数でこのロジックをラップするのは簡単です。

于 2013-07-02T17:22:16.010 に答える
1

この方法は私のために働いています:

rsvn = image.run(
  ... standard options ...
)

sleep(1)

for instance in rsvn.instances:
   instance.add_tag('<tag name>', <tag value>)
于 2011-11-09T19:21:54.023 に答える