Packer.Images/scripts/ADDS/payload/Provision-VaultPassword.ps1

86 lines
2.7 KiB
PowerShell
Raw Normal View History

[CmdletBinding()]
Param(
[Parameter()]
[string]$VaultAPIAddress,
[Parameter()]
[string]$VaultToken,
[Parameter()]
[string]$VaultPwPolicy,
[Parameter(Mandatory)]
[string]$VaultSecret,
[Parameter(Mandatory)]
[string]$Username
)
2021-03-10 10:32:53 +00:00
# Generate new password
$InvokeWebRequestSplat = @{
Uri = "$($VaultAPIAddress)/sys/policies/password/$($VaultPwPolicy)/generate"
Headers = @{'X-Vault-Token'="$VaultToken"}
UseBasicParsing = $True
}
$NewPassword = (Invoke-WebRequest @InvokeWebRequestSplat | ConvertFrom-Json).data.password
2021-03-10 10:32:53 +00:00
# Check for existense of secret
$Response, $ErrResponse = $Null, $Null
Try {
$InvokeWebRequestSplat = @{
Uri = "$($VaultAPIAddress)/secret/metadata/$($VaultSecret)"
2021-03-10 10:32:53 +00:00
Headers = @{'X-Vault-Token' = "$VaultToken"}
UseBasicParsing = $True
}
$Response = Invoke-WebRequest @InvokeWebRequestSplat
}
Catch [System.Net.WebException] {
2021-03-10 10:32:53 +00:00
$StreamReader = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream())
$StreamReader.BaseStream.Position = 0
$ErrResponse = $StreamReader.ReadToEnd()
$StreamReader.Close()
}
If ([boolean]$Response) {
# Secret already exists; retrieve existing key/value pairs
$InvokeWebRequestSplat = @{
Uri = "$($VaultAPIAddress)/secret/data/$($VaultSecret)"
2021-03-10 10:32:53 +00:00
Headers = @{'X-Vault-Token' = "$VaultToken"}
UseBasicParsing = $True
}
$Secret = (Invoke-WebRequest @InvokeWebRequestSplat | ConvertFrom-Json).data
# Merge new password into dictionary
$AddMemberSplat = @{
MemberType = 'NoteProperty'
Name = "password.$($Username)"
Value = $NewPassword
Force = $True
}
$Secret.data | Add-Member @AddMemberSplat
# Store as new version
$InvokeWebRequestSplat = @{
Uri = "$($VaultAPIAddress)/secret/data/$($VaultSecret)"
Method = 'POST'
UseBasicParsing = $True
Headers = @{'X-Vault-Token'="$VaultToken"}
Body = @{
2021-03-10 10:32:53 +00:00
data = $Secret.data
} | ConvertTo-Json
}
Invoke-WebRequest @InvokeWebRequestSplat | Out-Null
2021-03-10 10:32:53 +00:00
}
ElseIf ([boolean]$ErrResponse) {
# Secret did not exist yet, store as new secret
$InvokeWebRequestSplat = @{
Uri = "$($VaultAPIAddress)/secret/data/$($VaultSecret)"
Method = 'POST'
UseBasicParsing = $True
Headers = @{'X-Vault-Token'="$VaultToken"}
Body = @{
2021-03-10 10:32:53 +00:00
data = @{
"password.$($Username)" = $NewPassword
}
} | ConvertTo-Json
}
Invoke-WebRequest @InvokeWebRequestSplat | Out-Null
}
Return $NewPassword