Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Boto3 how does one assign a public IP when creating an instance

Tags:

boto3

I am working on an AWS VPC that has one subnet that does not auto-assign a public IP by default. I would like to use boto3 to create the instance and automatically assign the public IP. It's not clear how to do this from the boto3 documentation.

The closest I got was the following, but this still has errors:

self._ec2.create_instances( ImageId=self._cluster._image, KeyName="key_pair_1", InstanceType="t2.micro", MinCount=1, MaxCount=1, SecurityGroupIds=["sg-someid"], SubnetId="subnet-anotherid", BlockDeviceMappings=[{ "DeviceName": "/dev/sda1", "Ebs": { "VolumeType": "gp2", "VolumeSize": disk_size, "DeleteOnTermination": True }, }], NetworkInterfaces=[{ "DeviceIndex": 0, "AssociatePublicIpAddress": True }] )

like image 538
hbar Avatar asked Apr 06 '16 14:04

hbar


2 Answers

Might help someone: You have to put the SecurityGroupIds, and the subnetID as a network interface parameter, and remove them from the instance parameters, then it will run fine.

NetworkInterfaces=[
    {
        'DeviceIndex': 0,
        'SubnetId' : 'subnet-xxxxxx',
        'Groups': [
            'sg-xxxxxx','sg-xxxx','sg-xxxxxx'
        ],
        'AssociatePublicIpAddress': True            
    },
like image 138
Imre K. Avatar answered Nov 13 '22 03:11

Imre K.


If you launch any EC2 instance inside a VPC subnet that make private (Without the Auto-assign Public IP turn on), there is only 2 ways you can make it Internet ready 1. Attach Elastic IP after you create the instances 2. Create NAT gateway that reroute the traffic to a Subnet that allow to connect to Internet.

This instance network setup will never overwrite the VPC private subnet rules.

"AssociatePublicIpAddress": True 

If the subnet features doesn't change to Auto-assign Public IP, the easiest way to do it is Elastic IP. So just add 2 extra process 1. allocate_address : get an Elastic IP address 2. associate_address : Attach the EIP-id to the Instance-id

like image 32
mootmoot Avatar answered Nov 13 '22 03:11

mootmoot