I would like to configure an EC2 instance in a public subnet within a VPC. To accomplish this, I have the code below, using boto3. To summarize, I create a VPC, enable DNS support and hostnames for it, create a security group to ALLOW all ingress traffic, create a subnet for the VPC (and require it to map a public IP on launch), create and attach an Internet Gateway to the VPC, and then finally, create a route table with a CIDR destination I then create an instance with the subnet that we created inside the VPC.

def setup_network():
    use_dry_run = False
    ec2_resource = boto3.resource('ec2', region_name=AWS_REGION)
    ec2_client = boto3.client('ec2', region_name=AWS_REGION)

    #Create a VPC
    vpc = ec2_resource.create_vpc(DryRun=use_dry_run, CidrBlock='')
    ec2_client.modify_vpc_attribute(VpcId=vpc.vpc_id, EnableDnsSupport={'Value':True})
    ec2_client.modify_vpc_attribute(VpcId=vpc.vpc_id, EnableDnsHostnames={'Value':True})

    #Create an EC2 Security Group
    ip_permissions = [
            'IpProtocol': '-1',
            'FromPort': -1,
            'ToPort': -1,
            'IpRanges': [{'CidrIp': ''}]
    security_group = ec2_client.create_security_group(GroupName='gpu_group', Description='Allow_all_ingress_egress', VpcId=vpc.vpc_id)
    group_id = security_group['GroupId']
    ec2_client.authorize_security_group_ingress(GroupId=group_id, IpPermissions=ip_permissions)
    #Create the subnet for the VPC
    subnet = vpc.create_subnet(DryRun=use_dry_run, CidrBlock='', AvailabilityZone=AWS_AVAILABILITY_ZONE)
    ec2_client.modify_subnet_attribute(SubnetId=subnet.subnet_id, MapPublicIpOnLaunch={'Value':True})

    #Create an Internet Gateway
    gateway = ec2_resource.create_internet_gateway(DryRun=use_dry_run)
    gateway.attach_to_vpc(DryRun=use_dry_run, VpcId=vpc.vpc_id)

    #Create a Route table and add the route
    route_table = ec2_client.create_route_table(DryRun=use_dry_run, VpcId=vpc.vpc_id)
    route_table_id = route_table['RouteTable']['RouteTableId']
    ec2_client.create_route(DryRun=use_dry_run, DestinationCidrBlock='',RouteTableId=route_table_id,GatewayId=gateway.internet_gateway_id\
    return vpc, subnet

I cannot ssh into any of my instances; did I forget anything?

  • 1
    Associate the route table with the subnet? – Michael - sqlbot Feb 24 '17 at 10:34
  • Hi, this is totally not an answer to your question, but I highly suggest you check out Terraform to take care of VPC/Instance provisioning. In my opinion boto3 is fantastic for scripting tasks in AWS, but Terraform is far superior for provisioning the actual infrastructure. Totally free and super intuitive to use. – emmdee Oct 27 '17 at 21:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.