Python 如何通过Boto3动态获取实例安全组名称

Python 如何通过Boto3动态获取实例安全组名称,python,amazon-ec2,boto3,aws-security-group,Python,Amazon Ec2,Boto3,Aws Security Group,我制作了源实例的映像,现在我必须克隆新实例,因此我在目标实例创建中硬编码了源实例的安全组名称。现在我希望它是动态的。下面是我的代码: ec2 = boto3.resource('ec2',region_name='region') instance = ec2.create_instances( ImageId=image, InstanceType='t2.micro', KeyName='keyName', SecurityGroups=['sgr-ssh-http-pub

我制作了源实例的映像,现在我必须克隆新实例,因此我在目标实例创建中硬编码了源实例的安全组名称。现在我希望它是动态的。下面是我的代码:

    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',)

注意:请先学习在stackoverflow中如何提问的规则,以及如何设置问题的格式。既然你似乎是stackoverflow的初学者,我就不提你的问题了。请以后避免这些错误。

您的问题是什么?请说得更具体些。到目前为止你试过什么?为什么不上传代码?@vishal.k这是代码ec2=boto3.resource'ec2',region\u name='region'instance=ec2.create\u instances ImageId=image,InstanceType='t2.micro',KeyName='KeyName',SecurityGroups=['sgr-ssh-http-public',MaxCount=1,MinCount=1 SecurityGroups=['sgr-ssh-http-public']我希望这是动态的这不是在stackoverflow中编写代码的方式。此外,您应该在问题中添加代码,而不是在注释中添加代码