forked from jseerden/SLAPS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Set-KeyVaultSecret.ps1
66 lines (53 loc) · 2.08 KB
/
Set-KeyVaultSecret.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using namespace System.Net
param(
[Parameter(Mandatory = $true)]
$Request
)
$keyVaultName = "srdnkeyvault01"
# Azure Key Vault resource to obtain access token
$vaultTokenUri = 'https://vault.azure.net'
$apiVersion = '2017-09-01'
# Get Azure Key Vault Access Token using the Function's Managed Service Identity
$authToken = Invoke-RestMethod -Method Get -Headers @{ 'Secret' = $env:MSI_SECRET } -Uri "$($env:MSI_ENDPOINT)?resource=$vaultTokenUri&api-version=$apiVersion"
# Use Azure Key Vault Access Token to create Authentication Header
$authHeader = @{ Authorization = "Bearer $($authToken.access_token)" }
# Generate a random password
function New-Password {
$alphabets = 'a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,t,u,v,w,x,y,z'
$numbers = 2..9
$specialCharacters = '!,@,#,$,%,&,*,?,+'
$array = @()
$array += $alphabets.Split(',') | Get-Random -Count 20
$array[0] = $array[0].ToUpper()
$array[-1] = $array[-1].ToUpper()
$array += $numbers | Get-Random -Count 3
$array += $specialCharacters.Split(',') | Get-Random -Count 3
($array | Get-Random -Count $array.Count) -join ""
}
$password = New-Password
# Generate a new body to set a secret in the Azure Key Vault
$body = $request.body | Select-Object -Property * -ExcludeProperty keyName
# Append the random password to the new body
$body | Add-Member -NotePropertyName value -NotePropertyValue "$password"
# Convert the body to JSON
$body = $body | ConvertTo-Json
$vaultSecretUri = "https://$keyVaultName.vault.azure.net/secrets/$($request.Body.keyName)/?api-version=2016-10-01"
# Azure Key Vault Uri to set a secret
try
{
$res = Invoke-RestMethod -Method PUT -Body $body -Uri $vaultSecretUri -ContentType 'application/json' -Headers $authHeader -ErrorAction Stop
}
catch
{
Push-OutputBinding -Name response -Value ([HttpResponseContext]@{
StatusCode = [System.Net.HttpStatusCode]::InternalServerError
Body = "Failed to record new password"
})
}
if($res)
{
# Return the password in the response
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
Body = $password
})
}