kubernetesterraformkubectlazure-aks

How to execute kubectl commands in HCP?


I have very simple use case that I am trying to run kubectl command using terraform's HCP

resource "null_resource" "meta_create_namespace_and_secret" {
  provisioner "local-exec" {
    command = "kubectl create namespace meta && kubectl create secret generic minio -n meta --from-literal=rootUser=ck_infra_admin --from-literal=rootPassword=f23ff2#DcejC:d"
  }

  # adding static trigger to run this only once 
  triggers = {
    always_run = "true"
  }
}

I get the following errors

Executing: ["/bin/sh" "-c" "kubectl create namespace meta && kubectl create secret generic minio -n meta --from-literal=rootUser=ck_infra_admin --from-literal=rootPassword=f23ff2#DcejC:d"]
  /bin/sh: 1: kubectl: not found

I know I can do it using kubectl manifest provider but is there a way to do it using just commands ?


Solution

  • kubectl is not installed on HashiCorp Cloud Platform by default and it can be added by terraform with the help of null_resource or terraform_data which the later one is preferred.

    resource "terraform_data" "meta_create_namespace_and_secret" {
    
      # trigger each time
      triggers_replace = [
        "${timestamp()}"
      ]
    
      # download kubectl
      provisioner "local-exec" {
        command = "curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl && chmod +x kubectl"
      }
    
      provisioner "local-exec" {
        command = "kubectl create namespace meta && kubectl create secret generic minio -n meta --from-literal=rootUser=ck_infra_admin --from-literal=rootPassword=f23ff2#DcejC:d"
      }
    
    }
    

    or

    resource "null_resource" "meta_create_namespace_and_secret" {
    
      # download kubectl
      provisioner "local-exec" {
        command = "curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl && chmod +x kubectl"
      }
    
      provisioner "local-exec" {
        command = "kubectl create namespace meta && kubectl create secret generic minio -n meta --from-literal=rootUser=ck_infra_admin --from-literal=rootPassword=f23ff2#DcejC:d"
      }
    
      # adding static trigger to run this only once 
      triggers = {
        always_run = "true"
      }
    }