Skip to content

Instantly share code, notes, and snippets.

@JPRuskin
Created July 13, 2021 10:06
Show Gist options
  • Save JPRuskin/a8e438c534a471749fe3c38c948882e8 to your computer and use it in GitHub Desktop.
Save JPRuskin/a8e438c534a471749fe3c38c948882e8 to your computer and use it in GitHub Desktop.
A function that returns a credential object, given a pair of secrets in a KeyVault
#requires -Modules Az.Accounts, Az.KeyVault
using namespace Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters
using namespace Microsoft.Azure.Commands.Common.Authentication.Abstractions
# function Get-AzLabCredential {
<#
.Synopsis
A function that returns a credential object, given a pair of secrets in a KeyVault
.Example
Get-AzLabCredential ADE-Test
# Returns the VM credentials for the resource group 'ADE-Test'
.Example
Get-AzLabCredential -VaultName "somevault" -SecretPrefix "sql"
# Returns the SQL credentials from the given vault
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidDefaultValueForMandatoryParameter", "VaultName")]
[OutputType([PSCredential])]
[CmdletBinding(DefaultParameterSetName="Group")]
param(
# The resource group to find the vault in. We assume there's one vault.
[Parameter(Mandatory, ParameterSetName="Group")]
[ResourceGroupCompleter()]
[string]$ResourceGroupName,
# The vault to pull secrets from
[ResourceNameCompleter("Microsoft.KeyVault/vaults", "ResourceGroupName")]
[Parameter(ParameterSetName="Group")]
[Parameter(Mandatory, ParameterSetName="Vault")]
[string]$VaultName = (Get-AzKeyVault -ResourceGroupName $ResourceGroupName)[0].VaultName,
# The prefix to the username and password secrets, e.g. vmUsername and vmPassword.
[string]$SecretPrefix = "vm"
)
end {
try {
$Username = Get-AzKeyVaultSecret -VaultName $VaultName -Name "$($SecretPrefix)Username" -AsPlainText -ErrorAction Stop
} catch [System.Net.Sockets.SocketException] {
Write-Error "No KeyVault named '$($VaultName)' was found."
} catch {
if ($_ -match "status code 'Forbidden'") {
$CurrentUserUpn = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext.Account.Id
if (($UserPermission = (Get-AzKeyVault -VaultName $VaultName).AccessPolicies.Where{
$_.DisplayName -like "*$($CurrentUserUpn)*" -and $_.PermissionsToSecrets -notcontains 'get'
}) -or -not $UserPermission) {
Write-Verbose "Required permissions missing on KeyVault '$($VaultName)' - adding 'get' permission for user '$($CurrentUserUpn)'."
$RequiredPermissions = @('Get') + @($UserPermission.PermissionsToSecrets)
try {
Set-AzKeyVaultAccessPolicy -VaultName $VaultName -UserPrincipalName $CurrentUserUpn -PermissionsToSecrets $RequiredPermissions.Where{$_} -ErrorAction Stop
} catch {
Write-Error -Message "You don't have access to this KeyVault`n$_" -ErrorAction Stop
}
}
$Username = Get-AzKeyVaultSecret -VaultName $VaultName -Name "$($SecretPrefix)Username" -AsPlainText
} else {
Write-Error -Exception $_.Exception
}
}
[PSCredential]::new(
$Username,
(Get-AzKeyVaultSecret -VaultName $VaultName -Name "$($SecretPrefix)Password").SecretValue
)
}
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment