Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List subnets in an AWS by VPC ID

Tags:

python

boto3

I need to list the subnets in a specific VPC in AWS.

I am getting this error when I do:

Traceback (most recent call last):
  File ".\aws_create_ec2.py", line 253, in <module>
    main()
  File ".\aws_create_ec2.py", line 249, in main
    create_instances()
  File ".\aws_create_ec2.py", line 146, in create_instances
    subnet_list = ec2_client.describe_subnets(
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\botocore\client.py", line 272, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\botocore\client.py", line 548, in _make_api_call
    request_dict = self._convert_to_request_dict(
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\botocore\client.py", line 596, in _convert_to_request_dict
    request_dict = self._serializer.serialize_to_request(
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\botocore\validate.py", line 297, in serialize_to_request
    raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:
Unknown parameter in input: "VpcIds", must be one of: Filters, SubnetIds, DryRun, NextToken, MaxResults

I'm using these commands:

 vpc_id = input("Enter the vpc id: ")
 subnet_list = ec2_client.describe_subnets(
     VpcIds=[
         vpc_id,
       ]
    )

How can I filter for the VPC I want correctly with this command?

Also how can I validate the user input with a regex so that it fits the right format? For example so that the user input matches something resembling: vpc-68b1ff12

like image 772
bluethundr Avatar asked Sep 09 '25 11:09

bluethundr


1 Answers

The error message means VpcIds is not a valid parameter for describe_subnets. The list of valid parameters are documented here.

Another way of getting the subnets in a VPC is:

subnets = boto3.resource("ec2").subnets.filter(
    Filters=[{"Name": "vpc-id", "Values": [vpc_id]}]
)
subnet_ids = [sn.id for sn in subnets]
like image 86
nibs Avatar answered Sep 11 '25 01:09

nibs