{% if vault_agent_nomad.vault_token.enabled %}
template {
  source          = "{{ vault_agent_root_dir }}/templates/nomad/vault.env.tpl"
  destination     = "/run/nomad/vault.env"
  left_delimiter  = "[["
  right_delimiter = "]]"
  perms           = 0640
  exec {
    # No need to restart Nomad as the previous token will be renewed by Nomad itself
    command = ["chown", ":{{ nomad_user }}", "/run/nomad/vault.env"]
  }
}
{% endif %}

{% if nomad_conf.server.enabled %}
template {
  source          = "{{ vault_agent_root_dir }}/templates/nomad/vault.env.tpl"
  destination     = "/run/nomad/vault_config.env"
  left_delimiter  = "[["
  right_delimiter = "]]"
  perms           = 0640
}
{% endif %}

{% if vault_agent_nomad.nomad_pki.enabled %}
template {
  source          = "{{ vault_agent_root_dir }}/templates/nomad/agent_bundle.pem.tpl"
  destination     = "{{ nomad_root_dir }}/tls/agent_bundle.pem"
  left_delimiter  = "[["
  right_delimiter = "]]"
  perms           = 0640
  exec {
    # Wait a few sec before reloading Nomad as it fails if reloaded while not fully initialized yet
    command = ["sh", "-c", "sleep 15 && systemctl reload nomad{% if nomad_conf.tls.http and nomad_conf.server.enabled %} nomad-jwks-proxy{% endif %} || true"]
  }
}

{% if nomad_conf.server.enabled %}
template {
  source          = "{{ vault_agent_root_dir }}/templates/nomad/cli_bundle.pem.tpl"
  destination     = "{{ nomad_root_dir }}/tls/cli_bundle.pem"
  left_delimiter  = "[["
  right_delimiter = "]]"
  perms           = 0640
{% if vault_agent_nomad.nomad_pki.cli.enabled and vault_agent_nomad.nomad_pki.cli.secret_path is defined %}
  exec {
    command = ["{{ vault_agent_root_dir }}/bin/update_nomad_cert.sh"]
  }
{% endif %}
}
{% endif %}
{% endif %}


{% if vault_agent_nomad.consul_pki.enabled and nomad_conf.consul.ssl %}
template {
  source          = "{{ vault_agent_root_dir }}/templates/nomad/consul_bundle.pem.tpl"
  destination     = "{{ nomad_root_dir }}/tls/consul_bundle.pem"
  left_delimiter  = "[["
  right_delimiter = "]]"
  perms           = 0640
  exec {
    command = ["sh", "-c", "chown :{{ nomad_user }} && sleep 15 && systemctl reload nomad || true"]
  }
}
{% endif %}

{% if vault_agent_nomad.consul_token.enabled %}
template {
  source          = "{{ vault_agent_root_dir }}/templates/nomad/consul.env.tpl"
  destination     = "/run/nomad/consul.env"
  left_delimiter  = "[["
  right_delimiter = "]]"
  perms           = 0640
  exec {
    command = ["sh", "-c", "chown :{{ nomad_user }} /run/nomad/consul.env && systemctl restart nomad"]
  }
}
{% endif %}
