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

Pavol Kutaj
2 min readOct 29, 2020

--

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

--

--

No responses yet