diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 74b9b4ea..c11bc269 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -4,6 +4,7 @@ variables: TF_HTTP_ADDRESS: ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/terraform/state/${CI_COMMIT_BRANCH} TF_STATE_NAME: ${CI_COMMIT_BRANCH} TF_CACHE_KEY: ${CI_COMMIT_BRANCH} + TF_VAR_branch: ${CI_COMMIT_BRANCH} cache: key: "${TF_ROOT}" paths: @@ -12,6 +13,7 @@ cache: # Test before_script: - cd ${TF_ROOT} + - export TF_VAR_subnet="$(python3 helpers/subnet_prefix.py)" stages: - prepare-tf diff --git a/subnet_prefixes.txt b/subnet_prefixes.txt new file mode 100644 index 00000000..3ab1380b --- /dev/null +++ b/subnet_prefixes.txt @@ -0,0 +1,4 @@ +main: 10.101.23.0/24 +dev: 10.101.24.0/24 +aaron-dev: 10.101.25.0/24 +default: 10.101.26.0/24 diff --git a/terraform/helpers/subnet_prefix.py b/terraform/helpers/subnet_prefix.py new file mode 100644 index 00000000..bdd51b21 --- /dev/null +++ b/terraform/helpers/subnet_prefix.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +# Outputs string with correct subnet prefix based on +# the current git branch. +# ATS +import os +import sys + +branch = os.getenv("CI_COMMIT_BRANCH") +mapping_file = f"{os.getenv('CI_PROJECT_DIR')}/subnet_prefixes.txt" + +subnets = {} +with open(mapping_file) as myfile: + for line in myfile: + name, var = line.partition(":")[::2] + subnets[name.strip()] = str(var).strip() + +if branch in subnets: + print(subnets[branch]) + exit(0) +else: + print(f"Could not find branch {branch} in {mapping_file}", file=sys.stderr) + exit(1) diff --git a/terraform/lxc-dhcp.tf b/terraform/lxc-dhcp.tf index 3254040c..d4381623 100644 --- a/terraform/lxc-dhcp.tf +++ b/terraform/lxc-dhcp.tf @@ -1,12 +1,13 @@ module "dhcp1" { - source = "./modules/lxc" - ip_address = "10.101.23.253/24" - hostname = "dhcp1.dev.magevent.net" + source = "./modules/lxc" + cluster_name = "pve1" + ip_address = "${cidrhost(var.subnet, 253)}/${local.cidr_suffix}" + hostname = "dhcp1.${local.domain}" } module "dhcp2" { source = "./modules/lxc" cluster_name = "pve2" - ip_address = "10.101.23.254/24" - hostname = "dhcp2.dev.magevent.net" + ip_address = "${cidrhost(var.subnet, 254)}/${local.cidr_suffix}" + hostname = "dhcp2.${local.domain}" } diff --git a/terraform/main.tf b/terraform/main.tf index 3730ff29..54f02065 100644 --- a/terraform/main.tf +++ b/terraform/main.tf @@ -22,3 +22,18 @@ provider "proxmox" { _capturelog = "" } } + +variable "branch" { + type = string + description = "Git branch, which is also used as subdomain name." +} + +variable "subnet" { + type = string + description = "Subnet for the branch in format 192.168.1.0/24" +} + +locals { + cidr_suffix = element(split("/", var.subnet), 1) + domain = "${var.branch}.magevent.net" +}