【问题标题】:How can I pass terraform output as variables to k8s spec?如何将 terraform 输出作为变量传递给 k8s 规范?
【发布时间】:2021-08-29 23:00:39
【问题描述】:

我正在使用 terraform 将 EKS 和其他一些东西部署到 AWS 云。而且我还有一些 k8s 配置 yml 文件来部署 k8s pods/deployment/load balancer 等。

我需要从 terraform 输出中获取一些值,例如 vpc id、子网 id 等,并将它们放入 k8s 规范 yml 文件。自动执行此操作的最佳方法是什么?

例如,

我的配置文件如下:

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

角色 arn 值 arn:aws:iam::xxxx:role/xxxx 应该来自输出中部署的角色 terraform。如何将 terraform 输出传递给 k8s yml 文件?

我可以使用像kubectl apply -f xxx.yml -v variables.json 这样的命令吗?

【问题讨论】:

  • 你能说明你想要达到什么目标吗?你有任何代码展示你的用例吗?

标签: amazon-web-services kubernetes terraform


【解决方案1】:

您可以从

访问远程状态值
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}"
}

从这里你可以运行命令terraform output -json

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

terraform 输出文件之类的

output "example1" {
  value = "hello"
}

而不是hello 设置任何东西或变量。

terraform 命令将设置值

export EXAMPLE1='hello'

现在再次使用 ubuntu 简单命令,您可以将 OS 环境变量值替换为 K8s 规范文件。

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

【讨论】:

  • 这意味着我必须根据 terraform 输出设置这些环境变量并在 k8s 规范 yml 文件中使用它们?喜欢$EXAMPLE1
  • 是的,所以从 terraform 到 OS 环境并将这些变量替换为 K8s yaml 并将该 YAML 应用到 k8s。
猜你喜欢
  • 2017-03-14
  • 1970-01-01
  • 2019-03-04
  • 2011-04-16
  • 2012-06-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-14
  • 2018-09-07
相关资源
最近更新 更多