<p>I am using Terraform with Kubernetes Provider.
Now when creating <em>ConfigMap</em>s, I want their names to have a content suffix. 
Usually it is a hash of the content.</p>

<p>This way, it should enforce a Deployment, where used.</p>

<p>So I would like it to work similar to:</p>

<pre><code>resource "kubernetes_config_map" "prometheus_config" {
  metadata {
    name      = "prometheus-" + computeHash(file("${path.module}/alerts.yml"), file("${path.module}/recordings.yml"), "abcd")
  }

  data = {
    "foo" = file("${path.module}/alerts.yml")
    "bar" = file("${path.module}/recordings.yml")
    "txt" = "abcd"
  }
}
</code></pre>

<p>Is there any way of implementing a custom function like <code>computeHash</code>?
Or to achieve this another way?</p>

abergmeier
<p>There is no way to implement a <em>custom</em> hash function in Terraform, but Terraform has a number of built-in functions that implement different standard hash functions.</p>

<p>For example, to use a base64-encoded SHA256 hash you could write something like the following using the function <a href="https://www.terraform.io/docs/configuration/functions/base64sha256.html" rel="nofollow noreferrer"><code>base64sha256</code></a>:</p>

<pre><code>  name = "prometheus-" + base64sha256(join("\n", [
    file("${path.module}/alerts.yml"),
    file("${path.module}/recordings.yml"),
    "abcd",
  ])
</code></pre>

<p>Because the <code>file</code> function returns a string, all of the referenced files must contain valid UTF-8 text. The hash will then be of the UTF-8 encoding of the unicode characters in the files.</p>

<p>The documentation page for <code>base64sha256</code> includes navigation links to various other "Hash and Crypto Functions", some of which implement other hashing algorithms.</p>

<p>If your goal is to just include everything in the <code>data</code> map, you could avoid the duplication by factoring that out into a <a href="https://www.terraform.io/docs/configuration/locals.html" rel="nofollow noreferrer">Local Value</a> and then hash a string representation of the map, such as a JSON serialization:</p>

<pre><code>locals {
  prometheus_config = {
    "foo" = file("${path.module}/alerts.yml")
    "bar" = file("${path.module}/recordings.yml")
    "txt" = "abcd"
  }
}

resource "kubernetes_config_map" "prometheus_config" {
  metadata {
    name = "prometheus-" + base64sha256(jsonencode(local.prometheus_config))
  }

  data = local.prometheus_config
}
</code></pre>
