我制作了源实例的映像,现在我必须克隆新实例,因此我在目标实例创建中硬编码了源实例的安全组名称。现在我希望它是动态的。下面是我的代码:
ec2 = boto3.resource('ec2',region_name='region')
instance = ec2.create_instances( ImageId=image, InstanceType='t2.micro', KeyName='keyName', SecurityGroups=['sgr-ssh-http-public'], MaxCount=1, MinCount=1 )
这是实现所需输出的多种方法之一。
import boto3
client = boto3.client('ec2',region_name='ap-south-1')
response = client.describe_instances()
for i in response['Reservations']:
for j in i['Instances']:
if (j['InstanceId']=="yourparentinstanceid"):
for k in j['SecurityGroups']:
sgname=k['GroupId']
ec2 = boto3.resource('ec2',region_name='ap-south-1')
instance = ec2.create_instances( ImageId='imageid', InstanceType='t2.micro', KeyName='keyname',SecurityGroupIds=[sgname], MaxCount=1, MinCount=1,SubnetId='subnetid',)