Codifying Vault with Terraform

May 13, 2017
Terraform Vault

With the release of Terraform 0.9.5 you can now use Terraform to codify a large part of your Vault configuration. Combining together the vault_auth_backend, vault_policy and vault_generic_secret resources it is now possible to configure how users authenticate with Vault and the policies that control their access to resources, using Terraform.

First we’ll define GitHub as authentication backend, so that users in our organisation can authenticate with Vault.

resource "vault_auth_backend" "github" {
  type = "github"
}

As we haven’t defined a path attribute, Terraform will auto mount this auth backend at auth/github.

Next, We’ll define the organisation that we want to define by writing data to auth/<path>/config.

resource "vault_generic_secret" "github_org" {
  path = "auth/github/config"

  depends_on = ["vault_auth_backend.github"]

  data_json = <<EOT
    {
      "organization" : "FundingCircle"
    }
  EOT
}

You need the explicitly set the depends_on otherwise you’ll run into this error on the first run.

URL: PUT http://localhost:8200/v1/auth/github/config
Code: 404. Errors:

* no handler for route 'auth/github/config//'

After running a terraform apply we’ll be able to authenticate with Vault and get the default policy.

> vault auth -method=github token=**********************

Successfully authenticated! You are now logged in.
The token below is already saved in the session. You do not
need to "vault auth" again with the token.
token: abc123-48a2-3000-b11b-002f76339783
token_duration: 2764799
token_policies: [default]

Now we’ll setup a policy that allows people to read secrets from the secrets/my_app path, and assign that to the infrastructure github team.

resource "vault_policy" "app_secrets_read" {
  name = "app_read"

  policy = <<EOT
    path "secret/my_app" {
      policy = "read"
    }
  EOT
}
resource "vault_generic_secret" "github_infra_team" {
  path = "auth/github/map/teams/infrastructure"

  depends_on = ["vault_generic_secret.github_org"]

  data_json = <<EOT
    {
      "value": "app_read"
    }
  EOT
}

Now we’ll see that when we authenticate ( vault auth ) we have the app_read policy, and we can indeed read from that path.

vault auth -method=github token=********************************

Successfully authenticated! You are now logged in.
The token below is already saved in the session. You do not
need to "vault auth" again with the token.
token: abc215ac-d200-4950-3a56-89f5111e24c2
token_duration: 2764800
token_policies: [app_read default]
vault read secret/my_app
Key                     Value
---                     -----
refresh_interval        768h0m0s
hello                   world

C’est tout. Code is available here