Background
This is a follow up on previous post.
The create_vpc
does not have a parameter to name the VPC, instead another method create_tags
is required for naming the VPC.
From the documentation the create_tags
takes in two arguments:
- Resources argument which is a list, in this context VPC id is the resource.
- Tags argument takes in which parameter i need to change, in this context i need to change the name of the VPC, this is a dictionary data type.
import boto3 import ipaddress vpc_resource_names = [] ec2_client = boto3.client('ec2') # boto3 autocomplete https://blog.wavycloud.com/2016/12/27/boto3-pyboto3-autocomplete/ """ :type : pyboto3.ec2 """ user_response_vpc = input("Enter VPC subnet:") user_response_vpc_name = input("Enter VPC name: ") try: subnet = str(ipaddress.ip_network(user_response_vpc)) response = ec2_client.create_vpc(CidrBlock=subnet) # print(type(response['ResponseMetadata']['HTTPStatusCode'])) # print(response) # Resources is a parameter in create_tags method, which is a list. vpc_resource_names.append(response['Vpc']['VpcId']) if response['ResponseMetadata']['HTTPStatusCode'] == 200: print("VPC, {}, was created successfully at {}".format(vpc_resource_names, response['ResponseMetadata']['HTTPHeaders']['date'])) else: print("There seems to be a problem fulfilling the request.") if user_response_vpc_name is not "": vpc_tags = [ { 'Key': 'Name', 'Value': user_response_vpc_name } ] tag_response = ec2_client.create_tags(Resources=vpc_resource_names, Tags=vpc_tags) if tag_response['ResponseMetadata']['HTTPStatusCode'] == 200: for name_id in vpc_resource_names: print("{} was successfully named".format(name_id)) else: print("It seems there is problem in fulfilling the request.") except ValueError as e: print(e)
Results
Create VPC without name.
Create VPC with a name.