Joey Yi Zhao
Joey Yi Zhao

Reputation: 42480

How can I pass terraform output as variables to k8s spec?

I am using terraform to deploy EKS and some other stuff to AWS cloud. and I also has some k8s configuration yml file to deploy k8s pods/deployment/load balancer etc.

I need to grab some values from terraform output such as vpc id, subnet id etc. and put them to k8s spec yml file. What is the best way to do that automatically?

For example,

I have configure file as below:

apiVersion: v1
kind: ServiceAccount
metadata:
  annotations:
    eks.amazonaws.com/role-arn: arn:aws:iam::xxxx:role/xxxx
  name: aws-load-balancer-controller
  namespace: kube-syste

The role arn value arn:aws:iam::xxxx:role/xxxx should be from the role terraform deployed which is in the output. How can I pass the terraform output to k8s yml file?

Can I use a command like kubectl apply -f xxx.yml -v variables.json?

Upvotes: 0

Views: 1278

Answers (1)

Harsh Manvar
Harsh Manvar

Reputation: 30113

You can access the remote state value from the

https://www.terraform.io/docs/language/state/remote-state-data.html

data "terraform_remote_state" "vpc" {
  backend = "remote"

  config = {
    organization = "hashicorp"
    workspaces = {
      name = "vpc-prod"
    }
  }
}

# Terraform >= 0.12
resource "aws_instance" "foo" {
  # ...
  subnet_id = data.terraform_remote_state.vpc.outputs.subnet_id
}

# Terraform <= 0.11
resource "aws_instance" "foo" {
  # ...
  subnet_id = "${data.terraform_remote_state.vpc.subnet_id}"
}

from here what you can is to run the command terraform output -json

terraform output -json | jq -r '@sh "export EXAMPLE1=\(.example1.value)"'

terraform output file something like

output "example1" {
  value = "hello"
}

instead of hello set anything or varible.

terraform command will set value

export EXAMPLE1='hello'

now again using the ubuntu simple command you can replace the OS environment variables values will K8s spec file.

check example at : https://stackoverflow.com/questions/65315202/can-i-set-terraform-output-to-env-variables#:~:text=One%20way%20you%20could%20do,statements%20to%20set%20environment%20variables.

Upvotes: 1

Related Questions