Skip to content

Instantly share code, notes, and snippets.

@Vertiwell
Last active September 14, 2021 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vertiwell/da5d685c069cc4189117e8e592610b60 to your computer and use it in GitHub Desktop.
Save Vertiwell/da5d685c069cc4189117e8e592610b60 to your computer and use it in GitHub Desktop.
### Vault Agent on Windows - https://learn.hashicorp.com/tutorials/vault/agent-windows-service?in=vault/app-integration
## Run Powershell as administrator
$amiadmin = [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
If ($amiadmin -ne 'True') {"This script needs to be run as Administrator, exiting.."; Start-Sleep -s 5; exit}
Else {"Script running as Administrator, continuing..."; Start-Sleep -s 5}
## Check if vault-agent path exists, if not create it
New-Item -ItemType Directory -Force -Path c:\vault-agent
## Check if vault program exits, if not create it: Download Vault: https://www.vaultproject.io/downloads
$testpath = Test-Path C:\vault-agent\vault.exe
If ($testpath -ne 'True') {[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest https://releases.hashicorp.com/vault/1.8.2/vault_1.8.2_windows_amd64.zip -OutFile c:\vault-agent\vault_1.8.2_windows_amd64.zip; Expand-Archive -LiteralPath c:\vault-agent\vault_1.8.2_windows_amd64.zip -DestinationPath c:\vault-agent\}
Else {"Vault is Installed"}
## Add c:\vault-agent to the system path: https://stackoverflow.com/questions/1618280/where-can-i-set-path-to-make-exe-on-windows
$addPath = "C:\vault-agent"
If (Test-Path $addPath){
$regexAddPath = [regex]::Escape($addPath)
$arrPath = $env:Path -split ';' | Where-Object {$_ -notMatch "^$regexAddPath\\?"}
$env:Path = ($arrPath + $addPath) -join ';'
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $env:Path
} Else {
Throw "'$addPath' is not a valid path."
}
## Test Vault is working
$testvault = vault -v
if(-not($testvault)){
Write-Output "Vault is not working!"
exit
}
else{
Write-Output "Vault is working!"
}
## Install Chocolatey
if(test-path "C:\ProgramData\chocolatey\choco.exe"){
Write-Output "Chocolatey Version $testchoco is already installed"
}
else{
Write-Output "Seems Chocolatey is not installed, installing now"
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
}
## Add C:\ProgramData\chocolatey\bin to the system path
$addPath = "C:\ProgramData\chocolatey\bin"
If (Test-Path $addPath){
$regexAddPath = [regex]::Escape($addPath)
$arrPath = $env:Path -split ';' | Where-Object {$_ -notMatch "^$regexAddPath\\?"}
$env:Path = ($arrPath + $addPath) -join ';'
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $env:Path
} Else {
Throw "'$addPath' is not a valid path."
}
## Install JQ (Json tool)
choco install jq
## Install NSSM (Simple windows service creation)
choco install nssm
Do {
$env:VAULT_TOKEN = Read-Host 'Please enter an admin vault token'
$env:VAULT_ADDR = Read-Host 'Please enter the URL of the Vault Server (https://vault.example.com:8200)'
## Test the Vault Connection
$testvaultserver = vault status -format=json | jq -r '.initialized'
if(-not($testvaultserver)){
Write-Output "Vault is not working or is sealed, please try again"
}
else{
Write-Output "Vault is working!"
}
}Until ($testvaultserver)
$cname = $env:computername
$AgentConfiguration = @"
pid_file = "./pidfile"
vault {
address = "$env:VAULT_ADDR"
}
auto_auth {
method "approle" {
mount_path = "auth/approle"
config = {
role_id_file_path = "/vault-agent/webblog_role_id"
secret_id_file_path = "/vault-agent/webblog_wrapped_secret_id"
remove_secret_id_file_after_reading = true
secret_id_response_wrapping_path = "auth/approle/role/agent-$cname/secret-id"
}
}
sink "file" {
config = {
path = "/vault-agent/agent-token"
}
}
}
listener "tcp" {
address = "127.0.0.1:8100"
tls_disable = true
}
cache {
use_auto_auth_token = true
}
"@; Set-Content C:\vault-agent\vault-agent.hcl $AgentConfiguration
$AgentPolicyConfiguration = @"
path "secret/*" {
capabilities = [ "read", "update" ]
}
"@; Set-Content C:\vault-agent\agent-policy.hcl $AgentPolicyConfiguration
$RestartAgentPolicyConfiguration = @"
path "auth/approle/role/+/secret*" {
capabilities = [ "create", "read", "update" ]
min_wrapping_ttl = "100s"
max_wrapping_ttl = "300s"
}
"@
Set-Content C:\vault-agent\restart-agent-policy.hcl $RestartAgentPolicyConfiguration
vault policy write agent-$cname C:\vault-agent\agent-policy.hcl
vault policy write restart-agent-$cname C:\vault-agent\restart-agent-policy.hcl
vault write auth/approle/role/agent-$cname secret_id_ttl=10m token_num_uses=100 token_ttl=20m token_max_ttl=30m secret_id_num_uses=150 token_policies="agent-$cname"
vault write -force auth/approle/role/restart-agent-$cname secret_id_num_uses=0 token_policies="restart-agent-$cname"
vault read auth/approle/role/agent-$cname/role-id -format=json | jq -r '.data.role_id' | Out-File -encoding ascii C:\vault-agent\webblog_role_id -NoNewline
vault write -field=wrapping_token -wrap-ttl=200s -f auth/approle/role/agent-$cname/secret-id | Out-File -encoding ascii C:\vault-agent\webblog_wrapped_secret_id -NoNewline
vault read auth/approle/role/restart-agent-$cname/role-id -format=json | jq -r '.data.role_id' | Out-File -encoding ascii C:\vault-agent\restart_role_id -NoNewline
vault write -field=secret_id -f auth/approle/role/restart-agent-$cname/secret-id | Out-File -encoding ascii C:\vault-agent\restart_secret_id -NoNewline
$RestartWindowsService = @"
`$ROLEID = Get-Content C:\vault-agent\restart_role_id -Raw; `$SECRET = Get-Content C:\vault-agent\restart_secret_id -Raw; `$env:VAULT_ADDR = "$env:VAULT_ADDR"; `$env:VAULT_TOKEN = vault write -field=token auth/approle/login role_id="`$ROLEID" secret_id="`$SECRET"
vault write -field=wrapping_token -wrap-ttl=200s -f auth/approle/role/agent-$cname/secret-id | Out-File -encoding ascii C:\vault-agent\webblog_wrapped_secret_id -NoNewline
vault agent -config C:\vault-agent\vault-agent.hcl
"@; Set-Content C:\vault-agent\restart-vault-agent.ps1 $RestartWindowsService
$nssm = (Get-Command nssm).Source; $serviceName = 'Vault Agent'; $powershell = (Get-Command powershell).Source; $scriptPath = 'C:\vault-agent\restart-vault-agent.ps1'; $arguments = '-ExecutionPolicy Bypass -NoProfile -File "{0}"' -f $scriptPath; & $nssm install $serviceName $powershell $arguments; & $nssm status $serviceName; Start-Service $serviceName; Get-Service $serviceName
Write-Output "Starting Service..."; Start-Sleep -s 10;$env:VAULT_TOKEN = Get-Content C:\vault-agent\agent-token -Raw; vault token lookup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment