DEV Community

Simon Shine
Simon Shine

Posted on

1 2

Extracting the KUBE_CONFIG for a DigitalOcean Kubernetes cluster from a Terraform .tfstate

When provisioning a Kubernetes cluster from DigitalOcean with Terraform, the .tfstate contains a field called raw_config that authenticates kubectl. It can elegantly be extracted with jq:

$ jq -r '.resources[]
        | select(.type == "digitalocean_kubernetes_cluster")
        | .instances[].attributes.kube_config[].raw_config' \ 
    terraform.tfstate
apiVersion: v1
kind: Config
clusters:
- cluster:
    certificate-authority-data: ...
    server: https://...k8s.ondigitalocean.com
  name: your-cluster-name
contexts:
- context:
    cluster: your-cluster-name
    user: your-cluster-name-admin
  name: your-cluster-name
current-context: your-cluster-name
users:
- name: your-cluster-name-admin
  user:
    token: ...
Enter fullscreen mode Exit fullscreen mode

If you provision multiple clusters, you cannot simply pipe the multiple kind: Configs, but otherwhise, this output can be dumped straight into ~/.kube/config. Otherwise, you may want to dump it to a specific file before you run

KUBECONFIG=some.config kubectl ...
Enter fullscreen mode Exit fullscreen mode

Now, I'd like if the ~/.kube/config could get populated as part of the provisioning, so that kubectl commands work immediately after. This is possible with the local-exec provisioner:

  provisioner "local-exec" {
    command = <<EOF
      mkdir -p ~/.kube && jq -r \
        '.resources[]
        | select(.type == "digitalocean_kubernetes_cluster")
        | .instances[].attributes.kube_config[].raw_config' \
            terraform.tfstate > ~/.kube/config
EOF
Enter fullscreen mode Exit fullscreen mode

I'm not sure exactly how useful this last step is yet. This was just another demonstration of how powerful and useful jq is.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site