-2

I made image of source instance and now i had to clone new instance, Thus i hardcoded the security group name of source instance in target instance creation. now I want it to be dynamically. Below is my code:

    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
  • 1,646
  • 5
  • 28
  • 56
  • 2
    What exactly is your question? Please be more specific. What have you tried so far? Why didn't you upload your code? – vishal Jul 05 '18 at 16:14
  • @vishal.k here is the code 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']" i want this to be dynamic – aneesha kumari Jul 06 '18 at 05:58
  • This is not how you write code here in stackoverflow. Moreover you should have added the code in your question and not in the comments – vishal Jul 09 '18 at 22:27

1 Answers1

0

Here is one of the many ways by which you can achieve your desired output.

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

Note: Please study the rules on how to ask a question here in stackoverflow first and also how to format it. Since you seem to be a beginner here in stackoverflow I'm not flagging your question. Please avoid these mistakes in future.

vishal
  • 1,646
  • 5
  • 28
  • 56