Search code examples
pythonaws-lambdaboto3

Python boto3 creating EC2 instance says "An error occurred (VPCIdNotSpecified)"


I am using python boto3 script in a lambda to create an Ec2 instance. But it says VPC is needed. Boto3 documentation never says VPC is mandatory to create a ec2 instance.

import json
import boto3
import pprint


def lambda_handler(event, context):
  aws_mgmt_console = boto3.session.Session()
  ec2_console_resource = aws_mgmt_console.resource('ec2')
  ec2_console_client = aws_mgmt_console.client('ec2')
  
  ec2_console_resource.create_instances(
    ImageId="ami-018d291ca9ffc002f",
    MinCount=1,
    MaxCount=1,
    InstanceType="t2.micro")

The error is : "errorMessage": "An error occurred (VPCIdNotSpecified) when calling the RunInstances operation: No default VPC for this user. GroupName is only supported for EC2-Classic and default VPC.", "errorType": "ClientError", "requestId": "c8ca209b-223a-478b-8130-41b72daa0483",


Solution

  • The boto3 library cannot tell you all the validation rules implemented by the underlying AWS services.

    In this case, I suspect, you are deploying from an AWS account into a region that, in combination, does not support EC2 Classic and hence VPC is necessary. However, you do not have a default VPC in this region, hence the EC2 service cannot infer which VPC you want to deploy the EC2 instance into.

    You must therefore indicate a VPC when launching the instance(s) and you do that by supplying SubnetId.