如何运行kubectl在Terraform中应用命令

如何运行kubectl在Terraform中应用命令

本文介绍了如何运行kubectl在Terraform中应用命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了一个Terraform脚本来在GKE上创建一个k8集群.

I have developed a terraform script to create a k8 cluster on GKE.

在成功创建集群之后,我已经设置了要在k8集群上应用的yaml文件.

Post successful creation of cluster, I have set of yaml files to be applied on k8 cluster.

如何在terraform脚本中调用以下命令?

How can I invoke the below command in my terraform script?

kubectl create <.yaml>

推荐答案

您可以使用Terraform kubectl第三方提供程序.请按照此处的安装说明进行操作: Kubectl Terraform Provider

You can use the Terraform kubectl third party provider. Follow the installation instructions here: Kubectl Terraform Provider

然后只需定义一个kubectl_manifest即可指向您的YAML文件,例如:

Then simply define a kubectl_manifest pointing to your YAML file like:

# Get your cluster-info
data "google_container_cluster" "my_cluster" {
  name     = "my-cluster"
  location = "us-east1-a"
}

# Same parameters as kubernetes provider
provider "kubectl" {
  load_config_file       = false
  host                   = "https://${data.google_container_cluster.my_cluster.endpoint}"
  token                  = "${data.google_container_cluster.my_cluster.access_token}"
  cluster_ca_certificate = "${base64decode(data.google_container_cluster.my_cluster.master_auth.0.cluster_ca_certificate)}"
}

resource "kubectl_manifest" "my_service" {
    yaml_body = file("${path.module}/my_service.yaml")
}

此方法的一大优势是,所有内容都是动态获取的,并且不依赖任何本地配置文件(如果您在CI/CD服务器中运行Terraform或管理多集群环境,则非常重要).

This approach has the big advantage that everything is obtained dynamically and does not rely on any local config file (very important if you run Terraform in a CI/CD server or to manage a multicluster environment).

kubectl提供程序还提供了有助于非常轻松地处理多个文件的数据源.从文档 kubectl_filename_list :

The kubectl provider also offers data sources that help to handle multiple files very easily. From the docs kubectl_filename_list:

data "kubectl_filename_list" "manifests" {
    pattern = "./manifests/*.yaml"
}

resource "kubectl_manifest" "test" {
    count = length(data.kubectl_filename_list.manifests.matches)
    yaml_body = file(element(data.kubectl_filename_list.manifests.matches, count.index))
}

加分:您可以对yaml文件进行模板化.我将群集名称插值到多资源自动缩放器yaml文件中,如下所示:

Extra points: You can templatize your yaml files. I interpolate the cluster name in the multi-resource autoscaler yaml file as follows:

resource "kubectl_manifest" "autoscaler" {
  yaml_body = templatefile("${path.module}/autoscaler.yaml", {cluster_name = var.cluster_name })
}

这篇关于如何运行kubectl在Terraform中应用命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:13