简体   繁体   English

如何在 Terraform 中重用 SSH 隧道

[英]How to reuse SSH tunnel in Terraform

I have to create a k8s job via Terraform and somehow organize the mechanism of waiting for this job to be completed (since Terraform fails to do this https://github.com/terraform-providers/terraform-provider-kubernetes/issues/534 ). I have to create a k8s job via Terraform and somehow organize the mechanism of waiting for this job to be completed (since Terraform fails to do this https://github.com/terraform-providers/terraform-provider-kubernetes/issues/534 )。 I figured out nothing better than using a null resource with a command that waits for k8s job (namely kubectl wait ).我发现没有什么比使用 null 资源和等待 k8s 作业的命令(即kubectl wait )更好的了。 This stuff will be executed in a Docker container on a CI.这些东西将在 CI 上的 Docker 容器中执行。 Moreover, I need to go through the Bastion to get to the k8s cluster.此外,我需要通过堡垒 go 才能到达 k8s 集群。 I use an SSH tunnel for that:我为此使用 SSH 隧道:

provider "ssh" {
  port = ....
}
provider "kubernetes" {
  config_context         = "..."
  config_context_cluster = "..."
  host                   = "api.${k8s_host}:${data.ssh_tunnel.k8s.port}"
}

data "ssh_tunnel" "k8s" {
  host           = "bastion.....com"
  local_address  = "localhost:0"
  remote_address = "api.${k8s_host}:443"
}

All k8s resources successfully create so I assume that SSH tunnel works fine.所有 k8s 资源都成功创建,所以我假设 SSH 隧道工作正常。 But how to use it for a null resource?但是如何将它用于 null 资源? Here is it:就这个:

resource "null_resource" "wait" {
  provisioner "local-exec" {
    connection {
      type = "ssh"
      bastion_host = data.ssh_tunnel.k8s.host
      bastion_private_key = file("~/.ssh/id_rsa")
      bastion_port = data.ssh_tunnel.k8s.port
      host = "api.${k8s_host}"
      port = 443
    }
    command = "kubectl wait ...."
  }
  triggers = {
    job_ids = join(", ", kubernetes_job.a-job.*.id)
  }
}

But no luck, I got "The connection to the server api.${k8s_host} was refused - did you specify the right host or port?"但运气不好,我得到“与服务器 api.${k8s_host} 的连接被拒绝 - 你指定了正确的主机或端口吗?”

So there are two questions: 1. How to wait for a job in a different way 2. If 1 is impossible (I'm sure that it is) how to reuse the SSH tunnel in the right way.所以有两个问题:1.如何以不同的方式等待工作2.如果1是不可能的(我确定是)如何以正确的方式重用SSH隧道。

PS Yes, I read the documentation https://www.terraform.io/docs/provisioners/connection.html but I definitely do smth wrong. PS 是的,我阅读了文档https://www.terraform.io/docs/provisioners/connection.html但我肯定做错了。

I figured out how to reuse SSH tunnel opened by Terraform:我想出了如何重用由 Terraform 打开的 SSH 隧道:

resource "null_resource" "wait" {
provisioner "local-exec" {
  command = "kubectl wait --server=https://api.${k8s_host}:${data.ssh_tunnel.k8s.port} --for=condition=complete --timeout=3000s job/a-job"
  }
  triggers = {
    job_ids = join(", ", kubernetes_job.a-job.*.id)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM