Capture tokens and secret id from Hashicorp Vault and assign it to Windows Env Variables: Combining regex and Select-String cmdlet

usecase

  • The concern is documenting capturing the token from hashicorp vault and passing it to the Windows Environment Variables
  • that I need to re-issue every 12 hours in order to work with the stack.
  • The aim is to get both consul and nomad CLI to work properly and to use the same keys for the WEBUI
▶ vault read consul/creds/support
Key Value
--- -----
lease_id consul/creds/support/1111111111
lease_duration 12h
lease_renewable true
accessor 1111-1111-1111-1111-1111
local false
token 1111-1111-1111-1111-1111 <--- NEED TO ASSIGN THIS TO THE ENV VAR FOR CLI TO WORK
  • nomad output:
▶ vault read nomad/creds/nomad-viewer
Key Value
--- -----
lease_id nomad/creds/nomad-viewer/1111-1111-1111-1111-1111
lease_duration 12h
lease_renewable true
accessor_id 1111-1111-1111-1111-1111
secret_id 1111-1111-1111-1111-1111

1. cmdlet: Select-String

  • I can use Select-String aka sls to grab the line
vault read consul/creds/support | sls token -Pattern token.*token              1111-1111-1111-1111-1111

2. regex: lookaheads and lookbehinds

  • concepts to define patterns that only match they they
  • are / are not followed by a certain pattern → lookahead (positive / negative)
  • are / are not preceded by a certain pattern → lookbehind (positive / negative)

2.1. testing lookbehind with regex

  • if I want to capture a name that is after mr + an empty string (whitespace \s)
  • I need to use lookbehind syntax
[regex]::matches(‘mr paul’,’(?<=mr\s).*’).value
→→→ paul

4. final regex with vault

vault read consul/creds/support |  #01
sls -pattern ’(?<=token\s+)\S+’ | #02-05
% {$keys = $_.Matches.Value} #07

5. assign the binding to the env var

$env:CONSUL_HTTP_TOKEN=$keys

6. CODE

function get-vaultKeys {
$consulRegex = "(?<=token\s+)\S+"
$nomadRegex = "(?<=secret_id\s+)\S+"
$consulURL = "https://consul.foo.net/ui"
$nomadURL = "https://nomad.foo.net/ui"
vault read consul/creds/support |
sls -pattern $consulRegex |
% {$consulKey = $_.Matches.Value}
vault read nomad/creds/nomad-viewer |
sls -pattern $nomadRegex |
% {$nomadKey = $_.Matches.Value}
$env:CONSUL_HTTP_TOKEN=$consulKey
$env:NOMAD_TOKEN=$nomadKey

write-host "~~~~~~" -ForegroundColor Cyan
write-host "Consul: $consulKey" -ForegroundColor Cyan
write-host "Nomad: $nomadKey" -ForegroundColor Cyan
write-host "~~~~~~" -ForegroundColor Cyan
start chrome $consulURL
start chrome $nomadURL
}

7. sources

Written by

today I learnt… | as a support eng of the wonderful Snowplow Analytics, expect everything around modern (postmodern?) business intelligence

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store