<p>I have developed a terraform script to create a k8 cluster on GKE. </p>

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

<p>How can I invoke the below command in my terraform script? </p>

<pre><code>kubectl create &lt;.yaml&gt;
</code></pre>

<p>You can use the Terraform <code>kubectl</code> third party provider. Follow the installation instructions here: <a href="https://registry.terraform.io/providers/gavinbunney/kubectl/latest/docs#installation" rel="noreferrer">Kubectl Terraform Provider</a></p>
<p>Then simply define a <code>kubectl_manifest</code> pointing to your YAML file like:</p>
<pre><code># Get your cluster-info
data &quot;google_container_cluster&quot; &quot;my_cluster&quot; {
  name     = &quot;my-cluster&quot;
  location = &quot;us-east1-a&quot;
}

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

resource &quot;kubectl_manifest&quot; &quot;my_service&quot; {
    yaml_body = file(&quot;${path.module}/my_service.yaml&quot;)
}
</code></pre>
<p>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).</p>
<p><strong>Multi-object manifest files</strong></p>
<p>The <code>kubectl</code> provider also offers data sources that help to handle files with multiple objest very easily. From the docs <a href="https://registry.terraform.io/providers/gavinbunney/kubectl/latest/docs/data-sources/kubectl_filename_list" rel="noreferrer">kubectl_filename_list</a>:</p>
<pre><code>data &quot;kubectl_filename_list&quot; &quot;manifests&quot; {
    pattern = &quot;./manifests/*.yaml&quot;
}

resource &quot;kubectl_manifest&quot; &quot;test&quot; {
    count = length(data.kubectl_filename_list.manifests.matches)
    yaml_body = file(element(data.kubectl_filename_list.manifests.matches, count.index))
}
</code></pre>
<p><strong>Extra points</strong>: You can templatize your <code>yaml</code> files. I interpolate the cluster name in the multi-resource autoscaler yaml file as follows:</p>
<pre><code>resource &quot;kubectl_manifest&quot; &quot;autoscaler&quot; {
  yaml_body = templatefile(&quot;${path.module}/autoscaler.yaml&quot;, {cluster_name = var.cluster_name })
}
</code></pre>
