Created
December 21, 2022 15:47
-
-
Save klpx/3b4ff31eb3a55b3305b31dfb9211dc87 to your computer and use it in GitHub Desktop.
Terraform script to breakdown kube config into specific configs to use each in its directory using direnv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Put this script in `~/.kube/` directory | |
# > terraform init | |
# > terraform apply | |
locals { | |
# preferences | |
context2nicename_preference = { | |
"long-cluster-main" = "longcl" | |
} | |
# Directory in which a directory is created for each context from .kube/config | |
# Then in those directories, an .envrc file is created to use specific config | |
kubecontext_dir = "/home/user/kubernetes" | |
} | |
data "local_file" "mainconfig" { | |
filename = "./config" | |
} | |
locals { | |
mainconfig = yamldecode(data.local_file.mainconfig.content) | |
clusters = {for cl in local.mainconfig["clusters"]: cl["name"] => cl["cluster"]} | |
users = {for us in local.mainconfig["users"]: us["name"] => us["user"]} | |
context2nicename = { | |
for context in local.mainconfig["contexts"]: | |
context["name"] => lookup(local.context2nicename_preference, context["name"], regex("^(?:arn:aws:eks:.*:\\d+:cluster/)?(.+)$", context["name"])[0]) | |
} | |
context2filename = { | |
for context in local.mainconfig["contexts"]: | |
context["name"] => "_config_${local.context2nicename[context["name"]]}" | |
} | |
contexts = {for context in local.mainconfig["contexts"]: | |
context["name"] => { | |
apiVersion = "v1" | |
kind = "Config" | |
contexts = [ | |
context | |
] | |
current-context = context["name"] | |
preferences = {} | |
clusters = [ | |
{ | |
name = context["context"]["cluster"] | |
cluster = local.clusters[context["context"]["cluster"]] | |
} | |
] | |
users = [ | |
{ | |
name = context["context"]["user"] | |
user = local.users[context["context"]["user"]] | |
} | |
] | |
} | |
} | |
} | |
resource "local_file" "specific_config" { | |
for_each = local.contexts | |
filename = local.context2filename[each.key] | |
content = yamlencode(each.value) | |
} | |
resource "local_file" "envrc" { | |
for_each = local.context2nicename | |
filename = "${local.kubecontext_dir}/${each.value}/.envrc" | |
content = "export KUBECONFIG=~/.kube/${local.context2filename[each.key]}" | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment