Kubernetes terraform, use EOF for apply inside null_resource

2/19/2019

Terraform Kubernetes doesn't allow use of anything other than apiVersion: v1. However I wanted to work around that by using the null_resource provisioner to run kubectl apply -f ... and kubectl delete -f ... (with when = "destroy").

I've attempted to get this to work using the kubernetes apply EOF pattern, but haven't managed it just yet.

Here is where I've gotten to but it seems the | is an illegal char.

Also hoping I could pull the yaml string out into a multiline variable so I don't have to repeat it in the null resource.

resource "null_resource" "res_name" {
  provisioner {
    command = <<EOF | kubectl apply -f -
      apiVersion: extensions/v1beta1
      kind: Ingress
      metadata:
        name: some-ingress-name
        annotations:  
          kubernetes.io/ingress.class: nginx
      spec:
        rules:
        - host: subdomain.example.com
          http:
            paths:
            - backend:
                serviceName: some-cluster-ip-service
                servicePort: 80
  }

  provisioner {
    when = "destroy"

    command = <<EOF | kubectl delete -f -
      apiVersion: extensions/v1beta1
      kind: Ingress
      metadata:
        name: some-ingress-name
        annotations:  
          kubernetes.io/ingress.class: nginx
      spec:
        rules:
        - host: subdomain.example.com
          http:
            paths:
            - backend:
                serviceName: some-cluster-ip-service
                servicePort: 80
  }
}
-- denski
kubernetes
terraform

1 Answer

2/19/2019

There were some bugs in your code.

That code works on my side:

resource "null_resource" "res_name" {
  provisioner "local-exec" {
    command = "kubectl apply -f - <<EOF\n${var.ingress_yaml}\nEOF"
  }

  provisioner "local-exec" {
    when = "destroy"
    command = "kubectl delete -f - <<EOF\n${var.ingress_yaml}\nEOF"
  }
}

variable "ingress_yaml" {
  default = <<EOF
    apiVersion: extensions/v1beta1
    kind: Ingress
    metadata:
      name: some-ingress-name
      annotations:
        kubernetes.io/ingress.class: nginx
    spec:
      rules:
      - host: subdomain.example.com
        http:
          paths:
          - backend:
              serviceName: some-cluster-ip-service
              servicePort: 80
    EOF
}

I suggest to read in the YAML configuration from a file, instead. Then you can get YAML syntax highlighting and errors shown in your IDE. Use either

-- Dominik
Source: StackOverflow