Search code examples
amazon-web-servicesamazon-ec2boto3amazon-vpcaws-vpc

AWS SDK - How to set the VPC name tag using Boto3


How can I specify the VPC name tag using the AWS SDK when creating vpc? I tried a number of options as shown here but no success.

Here is how I create my VPC using python, boto3 SDK.

import os
import boto3
import time    
....
....
print('Creating VPC')
# Create new VPC environment
vpc = client.create_vpc(CidrBlock='10.0.0.0/16', InstanceTenancy='default')
client.modify_vpc_attribute(VpcId=vpc['Vpc']['VpcId'], EnableDnsSupport={'Value': True})
client.modify_vpc_attribute(VpcId=vpc['Vpc']['VpcId'], EnableDnsHostnames={'Value': True})

Currently, it creates the vpc without a name tag.

I tried specifying the tag either during creating vpc or when I am modifying it as shown below but none of the options work.

vpc = client.create_vpc(CidrBlock='10.0.0.0/16', InstanceTenancy='default', Tags="myvpcnametag")
client.modify_vpc_attribute(VpcId=vpc['Vpc']['VpcId'], Tags="myvpctag")

Solution

  • Something like this should work if you have the VPC id:

    client = boto3.client('ec2')
    client.create_tags(Resources=['vpc-78a54011'], Tags=[{'Key': 'Name', 'Value': 'MyVPC'}])
    

    Here is how I modified it and worked great.

    Create new VPC environment

    vpc = client.create_vpc(CidrBlock='10.0.0.0/16', InstanceTenancy='default')
    
    client.modify_vpc_attribute(VpcId=vpc['Vpc']['VpcId'], EnableDnsSupport={'Value': True})
    client.modify_vpc_attribute(VpcId=vpc['Vpc']['VpcId'], EnableDnsHostnames={'Value': True})
    
    client.create_tags(Resources=[vpc['Vpc']['VpcId']], Tags=[{'Key': 'Name', 'Value': 'DariusVPC'}])