How to retrieve the null_resource returned value?

Hi All,

I have the below null_resource to retrieve the prometheus cluster IP:

 resource "null_resource" "get_prometheus_ip" {
  provisioner "local-exec" {
    command = "kubectl get svc prometheus-server -n monitoring | awk -F' ' '{print $3}' | tail -1"
  }
}

I want to use its returned result in another place:

resource "helm_release" "prometheus-adapter" {
  name = "prometheus-adapter"
  chart = "${path.module}/helm/charts/stable/prometheus-adapter/"
  namespace = "default"

  // prometheus URL
  set {
    name = "prometheus.url"
    value = "http://${returnedValueHere}"
  }

is this doable or not and is there also a better way to do this?

Thanks :slight_smile:

The local-exec provisioner doesn’t directly support output. The example at https://www.terraform.io/docs/provisioners/local-exec.html demonstrates using redirection to a file, which can later be read using the file() function, or https://www.terraform.io/docs/providers/local/d/file.html.

Use of depends_on may be necessary to ensure correct ordering.

1 Like

Thank you very much for your answer, this works and I will publish the solution :slight_smile:

The solution as @jeremykatz suggested is as below:

resource "null_resource" "get_prometheus_ip" {
  triggers  =  { always_run = "${timestamp()}" }
  provisioner "local-exec" {
    command = "kubectl get svc prometheus-server -n monitoring | awk -F' ' '{print $3}' | tail -1 | tr -d '\n' >> ${path.module}/prometheus_private_ips.txt"
  }
  depends_on = ["helm_release.prometheus"]
}

data "local_file" "prometheus-ip" {
    filename = "${path.module}/prometheus_private_ips.txt"
  depends_on = ["null_resource.get_prometheus_ip"]
}

resource "helm_release" "prometheus-adapter" {
  name = "prometheus-adapter"
  chart = "${path.module}/helm/charts/stable/prometheus-adapter/"
  namespace = "default"

  // prometheus URL
  set {
    name = "prometheus.url"
    value = "http://${data.local_file.prometheus-ip.content}"
  }

I realize I’m late to this topic, but I just wanted to note that because the command you are running seems to be a read-only command gathering data another option is to use the external data source to run a wrapper script to gather the data and return it in JSON format, which can then avoid creating temporary files on disk and reading them back in.

Provisioners are intended for operations whose value comes from their side-effects, like starting up services or similar. While we can use them to read data by exploiting the side-effect of creating a temporary file on disk, the external data source more directly represents the intent to gather some data without side-effects.

With that said, if what you did with the local_file data source is meeting your needs then that’s fine! I’m just sharing the above in case it’s useful to you or to others.

1 Like