Skip to content

Commit 27a7fb7

Browse files
committed
random cidr for GCP vpc
1 parent 6862c63 commit 27a7fb7

File tree

4 files changed

+31
-14
lines changed

4 files changed

+31
-14
lines changed

terraform/google/google-compute-instance/main.tf

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -38,19 +38,6 @@ module "vpc" {
3838
region = local.region
3939

4040
name = local.name
41-
42-
subnets = [
43-
{
44-
subnet_name = "subnet-${local.region}-10-0-121"
45-
subnet_ip = "10.0.121.0/24"
46-
subnet_region = local.region
47-
},
48-
{
49-
subnet_name = "subnet-${local.region}-10-0-122"
50-
subnet_ip = "10.0.122.0/24"
51-
subnet_region = local.region
52-
}
53-
]
5441
}
5542

5643
resource "tailscale_tailnet_key" "main" {

terraform/google/google-compute-instance/outputs.tf

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@ output "instance_id" {
22
value = module.tailscale_instance.instance_id
33
}
44

5+
output "subnets_ips" {
6+
value = module.vpc.subnets_ips
7+
}
8+
59
output "user_data_md5" {
610
description = "MD5 hash of the VM user_data script - for detecting changes"
711
value = module.tailscale_instance.user_data_md5

terraform/google/internal-modules/google-vpc/main.tf

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,28 @@
1+
locals {
2+
cidr = length(var.subnets) == 0 ? [cidrsubnet("10.0.0.0/16", 6, random_integer.vpc_cidr[0].result)] : [] # /22
3+
# subnets = length(var.subnets) == 0 ? [cidrsubnet(local.cidr[0], 2, 0), cidrsubnet(local.cidr[0], 2, 1)] : var.subnets # /24 inside the /22
4+
subnets = length(var.subnets) == 0 ? [
5+
{
6+
subnet_name = "subnet-0"
7+
subnet_ip = cidrsubnet(local.cidr[0], 2, 0)
8+
subnet_region = var.region
9+
},
10+
{
11+
subnet_name = "subnet-1"
12+
subnet_ip = cidrsubnet(local.cidr[0], 2, 1)
13+
subnet_region = var.region
14+
}
15+
] : var.subnets
16+
}
17+
18+
# Pick a random /22 within 10.0.0.0/16
19+
resource "random_integer" "vpc_cidr" {
20+
count = length(var.subnets) == 0 ? 1 : 0
21+
22+
min = 0
23+
max = 63 # 2^(22-16)-1 = 64 slices in a /16
24+
}
25+
126
module "vpc" {
227
# https://registry.terraform.io/modules/terraform-google-modules/network/google/latest
328
source = "terraform-google-modules/network/google"
@@ -6,7 +31,7 @@ module "vpc" {
631
project_id = var.project_id
732
network_name = var.name
833

9-
subnets = var.subnets
34+
subnets = local.subnets
1035
}
1136

1237
module "cloud_router" {

terraform/google/internal-modules/google-vpc/variables.tf

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,5 @@ variable "subnets" {
2525
subnet_region = string
2626
}
2727
))
28+
default = []
2829
}

0 commit comments

Comments
 (0)