EC2インスタンスのAMIを作成するタグをAWSラムダ関数に追加しようとしています。EC2 AWSラムダバックアップスクリプトにタグを追加
import boto3
import collections
import datetime
import sys
import pprint
ec = boto3.client('ec2')
retention_days = 7
def lambda_handler(event, context):
reservations = ec.describe_instances(
Filters=[
{'Name': 'tag-key', 'Values': ['backup', 'Backup', 'Client']},
]
).get(
'Reservations', []
)
print (reservations)
instances = sum(
[
[i for i in r['Instances']]
for r in reservations
], [])
print "Found %d instances that need backing up" % len(instances)
to_tag = collections.defaultdict(list)
for instance in instances:
name_tag = [
str(t.get('Value')) for t in instance['Tags']
if t['Key'] == 'Name'][0]
print (name_tag)
print ("check_loop")
create_time = datetime.datetime.now()
create_fmt = create_time.strftime('%Y-%m-%d')
AMIid = ec.create_image(InstanceId=instance['InstanceId'], Name="Lambda12 - " + instance['InstanceId'] + " " + name_tag +" from " + create_fmt, Description="Lambda created AMI of instance " + instance['InstanceId'] + " " + name_tag + " from " + create_fmt, NoReboot=True, DryRun=False)
to_tag[retention_days].append(AMIid['ImageId'])
delete_date = datetime.date.today() + datetime.timedelta(days=retention_days)
delete_fmt = delete_date.strftime('%m-%d-%Y')
instancename = ''
for tags in instance["Tags"]:
if tags["Key"] == 'Client':
print ("This is instance inside if with key" + tags["Key"])
instancename = tags["Value"]
print ("This is instancename" + instancename)
ec.create_tags (
DryRun=False,
Resources=to_tag[retention_days],
Tags=[
{'Key': 'Client', 'Value': instancename},
]
)
print "This is last instancename" + instancename
ec.create_tags(
Resources=to_tag[retention_days],
Tags=[
{'Key': 'DeleteOn', 'Value': delete_fmt},
]
)
print ("Name tag " + name_tag)
print ("check_loopend")
を今、このコードでは、私が直面しています問題は、この部分に関連している::以下は、私が使用していますラムダ関数である
instancename = ''
for tags in instance["Tags"]:
if tags["Key"] == 'Client':
print ("This is instance inside if with key" + tags["Key"])
instancename = tags["Value"]
print ("This is instancename" + instancename)
ec.create_tags (
DryRun=False,
Resources=to_tag[retention_days],
Tags=[
{'Key': 'Client', 'Value': instancename},
]
)
print "This is last instancename" + instancename
私はインスタンスがタグを持っているときのAMIにタグを追加します
{'Key': 'Client', 'Value': 'XYZ'}
ここで、XYZは値です。
しかし、上記のループが終了すると、すべてのインスタンスにループの最後の反復時の値がタグ付けされます。
Ex。
インスタンス1から{'Key': 'Client', 'Value': 'ABC'}
インスタンス2 - キーが インスタンス3が存在しません - これら三つの終わりに{'Key': 'Client', 'Value': 'XYZ'}
を、全てそれぞれのAMIはタグが付いなっています {'Key': 'Client', 'Value': 'XYZ'}
があります何か私は行方不明ですか?
ご協力いただければ幸いです。
P.S. - コードの始めに字下げの問題はありません。
実際の問題は何ですか? – mootmoot
例のセクションを見てください。私の問題は、 '{'Key': 'Client'、 'Value':instancename}'というタグを追加することになっています。すべてのAMIは 'instancename'変数の単一の値でタグ付けされています。 –