terraformhclvault

Using terraform variable in hcl extention ( vault )


I'am tring to do automation for path and policies creation in vault. Do you know how I can proceed please ? variables declared in terraform are not reconized in .hcl file. I tried to rename my file client-ro-policy.hcl to client-ro-policy.tf but I have same issue Varibales is recognized in file with .tf extention

Thanks

main.tf

# Use Vault provider
provider "vault" {



# It is strongly recommended to configure this provider through the
  # environment variables:
  #    - VAULT_ADDR
  #    - VAULT_TOKEN
  #    - VAULT_CACERT
  #    - VAULT_CAPATH
  #    - etc.  

}

acl-ro-policy.hcl

    path "${var.client[0]}/k8s/preprod/*" {
  capabilities = ["read"]
}

policies.tf

    #---------------------
# Create policies
#---------------------

# Create 'client' policy
resource "vault_policy" "ro-client" {
  name   = "${var.client[0]}_k8s_preprod_ro"
  policy = file("./hcl-ro-policy.tf")
}

variables.tf

    variable "client" {
      type    = list(string)

}

variables.tfvars

client = ["titi", "toto","itutu"]

Result in vault:

vault acl policies

vault path


Solution

  • Even though Terraform and Vault both use HCL as the underlying syntax of their respective configuration languages, their language interpreters are totally separate and so the Vault policy language implementation cannot make direct use of any values defined in the Terraform language.

    Instead, you'll need to use the Terraform language to construct a suitable configuration for Vault. Vault supports a JSON variant of its policy language in order to make it easier to programmatically generate it, and so you can use Terraform's jsonencode function to build a JSON-based policy from the result of a Terraform expression, which may itself include references to values elsewhere in Terraform.

    For example:

    locals {
      vault_ro_policy = {
        path = {
          "${var.client[0]}/k8s/preprod/*" = {
            capabilities = ["read"]
          }
        }
      }
    }
    
    resource "vault_policy" "ro-client" {
      name   = "${var.client[0]}_k8s_preprod_ro"
      policy = jsonencode(local.var_ro_policy)
    }
    

    The value of local.vault_ro_policy should encode to JSON as follows, assuming that var.client[0] has the value "example":

    {
      "path": {
        "example/k8s/preprod/*": {
          "capabilities": ["read"]
        }
      }
    }
    

    Assuming that this is valid Vault JSON policy syntax (which I've not verified), this should be accepted by Vault as a valid policy. If I didn't get the JSON policy syntax exactly right then hopefully you can see how to adjust it to be valid; my expertise is with Terraform, so I focused on the Terraform language part here.