【问题标题】:How to fetch instance security group name dynamically via Boto3如何通过 Boto3 动态获取实例安全组名称
【发布时间】:2018-12-13 21:32:33
【问题描述】:

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

    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 ) 

【问题讨论】:

  • 您的问题到底是什么?请更具体。你都尝试了些什么?你为什么不上传你的代码?
  • @vishal.k 这里是代码 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) "SecurityGroups=['sgr-ssh-http-public']" 我希望这是动态的
  • 这不是您在 stackoverflow 中编写代码的方式。此外,您应该在问题中而不是在 cmets 中添加代码

标签: python amazon-ec2 boto3 aws-security-group


【解决方案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 的初学者,因此我不会标记您的问题。以后请避免这些错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-15
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    相关资源
    最近更新 更多