我一直在寻找解决这个问题的方法,但是我正在努力解决这个问题,因为我是python的新手,我不知何故相信我的问题大部分在这里,而BOTO3却没有。
>我想做的是从JSON文件中读取配置,并使用该配置创建EC2实例。 如果该配置仅包含一种配置以从中创建EC2实例,并且我从加载的JSON获取所需的参数并将其存储在新列表中,则该配置对我有用:
imageId = instance[0]["ImageId"]
ec2params['ImageId'] = imageId
但是..如果我还有更多,这就是问题所在。
我正在尝试使用for循环在配置上循环并将所需的参数存储在列表中,然后将其传递给接受** kwargs的BOTO3 create_instances()函数。
当我尝试将BOTO3部件移到for循环内时,会发生此问题。
代码示例: 导入json 导入boto3
with open('EC2_us_east') as json_file:
config = json.load(json_file)
ec2region = "us-east-2"
reservation = region["Reservations"]
for reserv in reservation:
ec2params = {}
if "Instances" in reserv:
instance = reserv["Instances"]
else:
print("No Instances object present in JSON file")
break
if "ImageId" in instance[0]:
imageId = instance[0]["ImageId"]
ec2params['ImageId'] = imageId
else:
print("No ImageId preset in Instances")
break
if "InstanceType" in instance[0]:
instanceType = instance[0]["InstanceType"]
ec2params["InstanceType"] = instanceType
ec2params["MaxCount"] = 1
ec2params["MinCount"] = 1
else:
print("No InstanceType present in Instances")
if "KeyName" in instance[0]:
keyName = instance[0]["KeyName"]
ec2params["KeyName"] = keyName
else:
print("No KeyName present in Instances")
if "Monitoring" in instance[0]:
monitoring = instance[0]["Monitoring"]["State"]
if monitoring == 'disabled':
ec2params["Monitoring"] = {"Enabled": False}
else:
ec2params["Monitoring"] = {"Enabled": True}
else:
print("No Monitoring present in Instances")
if "IamInstanceProfile" in instance[0]:
iamInstanceProfile = instance[0]["IamInstanceProfile"]
ec2params["IamInstanceProfile"] = iamInstanceProfile
else:
print("No IamInstanceProfile present in Instances")
if "BlockDeviceMappings" in instance[0]:
blockDeviceMappings = instance[0]["BlockDeviceMappings"]
ec2params["BlockDeviceMappings"] = blockDeviceMappings
else:
print("No BlockDeviceMappings present in Instances")
if "NetworkInterfaces" in instance[0]:
networkInterfaces = instance[0]["NetworkInterfaces"]
ec2params["NetworkInterfaces"] = networkInterfaces
else:
print("No NetworkInterfaces present in Instances")
print(ec2params)
ec2 = boto3.resource('ec2', ec2region)
response = ec2.create_instances(**ec2params)
instance_id = response[0].instance_id
print("Instance: " + ec2params['InstanceType'] + " with ID: " +
instance_id + " was created")
当create实例部分发生在for循环内时,它对我失败,并且在传递ec2params 时,我从BOTO3收到验证错误
但是当我在外面做那部分工作正常并创建一个EC2实例时。
我想让它在for循环中工作,该循环将迭代保留并从那里获取实例。稍后,我将其分解为功能,以使其更具可读性,并希望使其起作用:/
感谢您的协助!