DEV Community

Frederick Ollinger
Frederick Ollinger

Posted on

Terraform Connect to Vault and Use Approle Auth Method to Set a KV Secret

Introduction

This article assumes you have set up an on prem Vault Server and are logged in with a root token (for configuring Vault).

Set Up Vault with Approle

First, we need to configure Vault for Approle, and create a user, user-id, and secret-id.

NOTE: For simplicity sake, we'll create a highly privileged admin user.

Create Admin Policy

Save the following in a file called admin.hcl:

path "*" {
    capabilities = ["create", "read", "update", "delete", "list", "sudo"]
}
Enter fullscreen mode Exit fullscreen mode

Notify Vault of Our Policy

vault policy write admin-policy admin.hcl
Enter fullscreen mode Exit fullscreen mode

Turn on Approle

vault auth enable approle
Enter fullscreen mode Exit fullscreen mode

Create Admin User

When we create the admin user, we set the admin user with the admin-policy.

vault write auth/approle/role/admin policies=admin-policy
Enter fullscreen mode Exit fullscreen mode

Note that while the rest of the path is important, there's nothing specifically magical about the "admin" user.

We could replace admin everywhere with "poppinsm".

vault write auth/approle/role/poppinsm policies=admin-policy
Enter fullscreen mode Exit fullscreen mode

This will create a poppinsm user who is also super powerful like the real world Marry Poppins.

Create Authentication Credentials

Take a note of the output for the following commands:

vault read auth/approle/role/admin/role-id
vault write -f auth/approle/role/admin/secret-id
Enter fullscreen mode Exit fullscreen mode

Now we have role_id and secret_id.

Turn on KV Secrets Engine

vault secrets enable -path=kv-v1 kv
Enter fullscreen mode Exit fullscreen mode

Create Terraform File

mkdir vault
cd vault
touch main.tf
Enter fullscreen mode Exit fullscreen mode

Paste the following into main.tf.

Note: We replace ROLE_ID and SECRET_ID with the strings of the same name that we created above when we created the user credentials.

terraform {
  required_providers {
    vault = {
      source = "hashicorp/vault"
      version = "3.5.0"
    }
  }
}

provider "vault" {
  auth_login {
    path = "auth/approle/login"

    parameters = {
      role_id   = "ROLE_ID"
      secret_id = "SECRET_ID"
    }
  }
}

resource "vault_generic_secret" "example" {
  path = "kv-v1/secret/foo"

  data_json = <<EOT
{
  "foo":   "bar",
  "pizza": "cheese"
}
EOT
}
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)