83 lines
2.5 KiB
PowerShell
83 lines
2.5 KiB
PowerShell
[CmdletBinding()]
|
|
Param(
|
|
[Parameter()]
|
|
[string]$VaultAPIAddress,
|
|
[Parameter()]
|
|
[string]$VaultToken,
|
|
[Parameter()]
|
|
[string]$VaultPwPolicy,
|
|
[Parameter(Mandatory)]
|
|
[string]$VaulSecret,
|
|
[Parameter(Mandatory)]
|
|
[string]$Username
|
|
)
|
|
|
|
# Generate new password
|
|
$InvokeWebRequestSplat = @{
|
|
Uri = "$($VaultAPIAddress)/sys/policies/password/$($VaultPasswordPolicy)/generate"
|
|
Headers = @{'X-Vault-Token'="$VaultToken"}
|
|
}
|
|
$NewPassword = (Invoke-WebRequest @InvokeWebRequestSplat | ConvertFrom-Json).data.password
|
|
|
|
# Check for existense of secret
|
|
$Response, $ErrResponse = $Null, $Null
|
|
Try {
|
|
$InvokeWebRequestSplat = @{
|
|
Uri = "$(VaultAPIAddress)/secret/metadata/$($VaultSecret)"
|
|
Headers = @{'X-Vault-Token' = "$VaultToken"}
|
|
UseBasicParsing = $True
|
|
}
|
|
$Response = Invoke-WebRequest @InvokeWebRequestSplat
|
|
}
|
|
Catch {
|
|
$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)"
|
|
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/$($VaulSecret)"
|
|
Method = 'POST'
|
|
Headers = @{'X-Vault-Token'="$VaultToken"}
|
|
Body = @{
|
|
data = $Secret.data
|
|
} | ConvertTo-Json
|
|
}
|
|
Invoke-WebRequest @InvokeWebRequestSplat
|
|
}
|
|
ElseIf ([boolean]$ErrResponse) {
|
|
# Secret did not exist yet, store as new secret
|
|
$InvokeWebRequestSplat = @{
|
|
Uri = "$($VaultAPIAddress)/secret/data/$($VaulSecret)"
|
|
Method = 'POST'
|
|
Headers = @{'X-Vault-Token'="$VaultToken"}
|
|
Body = @{
|
|
data = @{
|
|
"password.$($Username)" = $NewPassword
|
|
}
|
|
} | ConvertTo-Json
|
|
}
|
|
Invoke-WebRequest @InvokeWebRequestSplat
|
|
}
|
|
|
|
Return $NewPassword |