-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubnet.py
More file actions
91 lines (78 loc) · 2.83 KB
/
subnet.py
File metadata and controls
91 lines (78 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import os
import sys
import random
import boto3
from botocore.exceptions import ClientError
from utils.tagger import tagit
from utils.region_azs import list_available_zones_names
from dotenv import load_dotenv
load_dotenv()
project = os.getenv('PROJECT')
env = os.getenv('ENV')
subnet_base_name = f'subnets_{project}_{env}'
subnets_cidr = ['10.0.1.0/24','10.0.2.0/24','10.0.3.0/24','10.0.4.0/24']
def create_subnets(client:boto3.client, vpc_id:str):
subnets_describe_response = client.describe_subnets(
Filters=[
{'Name': 'tag:project','Values': [project]},
],
)
if len(subnets_describe_response['Subnets'])!=0:
subnets_names = []
for sn in subnets_describe_response['Subnets']:
for tag in sn['Tags']:
if tag['Key'] == 'Name':
subnets_names.append(tag['Value'])
print(f'Subnets already exist')
return subnets_names
try:
subnets_names = []
subnets_ids = []
az_list = list_available_zones_names(client)
print('Creating subnets...')
for i in range(4):
subnet_name = f"{subnet_base_name}_{i}"
subnets_names.append(subnet_name)
create_subnet_response = client.create_subnet(
TagSpecifications=[
{
'ResourceType': 'subnet',
'Tags': tagit(
[
{
'Key': 'Name',
'Value': subnet_name
},
{
'Key': 'env',
'Value': env
},
]
)
},
],
VpcId=vpc_id,
CidrBlock=subnets_cidr[i],
AvailabilityZone=az_list[i],
)
subnets_ids.append(create_subnet_response['Subnet']['SubnetId'])
print(f"Subnet created: {create_subnet_response['Subnet']['Tags'][-1]['Value']}")
print(f'Subnets are available')
return subnets_ids
except ClientError as e:
print(f'Could not create Subnet: {e}')
# Destroys all subnets with the project name Tag associated
def destroy_all_subnets(client:boto3.client):
response = client.describe_subnets(
Filters=[
{'Name': 'tag:project','Values': [project,]},
],
)
if response['Subnets']:
for i in response['Subnets']:
response = client.delete_subnet(
SubnetId=i['SubnetId'],
)
print(f"Subnet {i['SubnetId']} has been deleted successfully")
else:
print(f'There are no Subnets to destroy')