Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Working With Azure Key Vault Using Azure PowerShell and AzureCLI

This is second part of Create Key Vault and secrets with access policies in Microsoft Azure, In the this article I will use Powershell and Azure CLI to create and configure Azure Key Vault resource service. Azure Key Vault is a cloud service that provides a secure store for secrets. You can securely store keys, passwords, certificates, and other secrets. In the first example In the first example I am using Microsoft Powershell Az module to deploy and configure Key vault.

Connect-AzAccount The 'Connect-AzAccount' command was found in the module 'Az.Accounts', but the module could not be loaded
Powershell Azure Az module Install-Package cannot convert value 2.0.0-preview to type system.version

PowerShell Az module example
First cmdlet connects to azure using az module and creates a new key vault resource. Download this script here or available on github.com.

#Login to the Azure Account Connect-AzAccount

Account                SubscriptionName         TenantId                             Environment
-------                ----------------         --------                             -----------
janvi@vcloud-lab.com   Sponsership-by-Microsoft 3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx AzureCloud

#Create a new Azure Key vault resource, I have already created a Resource groupNew-AzKeyVault -Name vCloud01Vault -ResourceGroupName vcloud-lab.com -Location 'East US' -Sku Standard

Vault Name                          : vCloud01Vault
Resource Group Name                 : vcloud-lab.com
Location                            : East US
Resource ID                         : /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud01Vault
Vault URI                           : https://vcloud01vault.vault.azure.net/
Tenant ID                           : 3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
SKU                                 : Standard
Enabled For Deployment?             : False
Enabled For Template Deployment?    : False
Enabled For Disk Encryption?        : False
Enabled For RBAC Authorization?     : False
Soft Delete Enabled?                : True
Enabled Purge Protection?           :
Soft Delete Retention Period (days) : 90
Enabled Purge Protection?           :
Access Policies                     :
                                      Tenant ID                                  : 3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
                                      Object ID                                  : 3863xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
                                      Application ID                             :
                                      Display Name                               : Janvi (janvi@vcloud-lab.com)
                                      Permissions to Keys                        : get, create, delete, list, update, import, backup, restore, recover
                                      Permissions to Secrets                     : get, list, set, delete, backup, restore, recover
                                      Permissions to Certificates                : get, delete, list, create, import, update, deleteissuers, getissuers, listissuers, managecontacts, 
                                      manageissuers, setissuers, recover, backup, restore
                                      Permissions to (Key Vault Managed) Storage : delete, deletesas, get, getsas, list, listsas, regeneratekey, set, setsas, update, recover,        
                                      backup, restore


Network Rule Set                    :
                                      Default Action                             : Allow
                                      Bypass                                     : AzureServices
                                      IP Rules                                   :
                                      Virtual Network Rules                      :

Tags 

#View the information of installed KeyVault
> Get-AzkeyVault -VaultName vCloud01Vault                               :

Once Key vault is created in azure, generate a secret on it with encrypted password string, next configure Access policy to provide access on key vault secret to Azure AD user principal.

#Encrypt password string and create/genrate Key vault secret$secretValue = ConvertTo-SecureString -String 'T0p$ecret' -AsPlainText -ForceSet-AzKeyVaultSecret -VaultName vCloud01Vault -Name RootSecret -SecretValue $secretValue -ContentType 'ESXi root password'

Vault Name   : vcloud01vault
Name         : RootSecret
Version      : a97eabdb6cd0499fb30721b0a4784a87
Id           : https://vcloud01vault.vault.azure.net:443/secrets/RootSecret/a97eabdb6cd0499fb30721b0a4784a87
Enabled      : True
Expires      :
Not Before   :
Created      : 06-04-2021 16:53:14
Updated      : 06-04-2021 16:53:14
Content Type : ESXi root password
Tags         :

#Configure Access Policy for Azure key vault
> Set-AzKeyVaultAccessPolicy -VaultName vCloud01Vault -UserPrincipalName vaultviewer@vcloud-lab.com -PermissionsToSecrets Get,List

I have already create a new user account vaultviewer on Azure Active directory for testing Creating a new user in Azure AD using oneliner PowerShell and Azure CLI. Next get and store the key vault information in variable to know ResourceID which I will use when assinging role (Key Vault Reader) to user principal on the keyvault. (In my case user principal name is vaultviewer)

#Get information of Key Vault, and grab Resource ID.$keyVault = Get-AzkeyVault -VaultName vCloud01Vault$keyVault.ResourceID

/subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud01Vault
                                                                                                                                           [19:19]
#Add user role assignement to Key vaultNew-AzRoleAssignment -SignInName vaultviewer@vcloud-lab.com -RoleDefinitionName 'Key Vault Reader' -Scope $keyVault.ResourceID

RoleAssignmentId   : /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud01Vault/providers/Microsoft.Authoriza
                     tion/roleAssignments/a0930a57-59f4-4429-942a-23722cd25ec6
Scope              : /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud01Vault
DisplayName        : vault viewer
SignInName         : [email protected]
RoleDefinitionName : Key Vault Reader
RoleDefinitionId   : 21090545-7ca7-4776-b22c-e363652d74d2
ObjectId           : 8ab61685-c967-460d-8152-7d41b54449fe
ObjectType         : User
CanDelegate        : False
Description        :
ConditionVersion   :
Condition          : 

Logout of Azure powershell account with Disconnect-AzAccount and login with the user (in my case vaultviewer), Get the key vault secret and convert the secure string to readable plain text password with below commands.

#Login to the Azure with user principal (run Disconnect-AzAccount to log out from azure)Connect-AzAccount

#Get the azure key vault secret and convert the secure string to plaintext$keyVaultSecret = Get-AzKeyVaultSecret -VaultName vCloud01Vault -Name RootSecret
❯ $password = ConvertFrom-SecureString $keyVaultSecret.SecretValue -AsPlainText$password

T0p$ecret

AzureCLI example

Login to the AzureCLI, All the Az command generate output in JSON format.

az login

The default web browser has been opened at https://login.microsoftonline.com/common/oauth2/authorize. Please continue the login in the web browser. If no web browser is available or if the web browser fails to open, use device code flow with `az login --use-device-code`.
You have logged in. Now let us find all the subscriptions to which you have access...
The following tenants don't contain accessible subscriptions. Use 'az login --allow-no-subscriptions' to have tenant level access.
a59fb284-02ec-4a72-a79a-4a6b6105ab9d 'vcloud-lab.com'
[
  {
    "cloudName": "AzureCloud",
    "homeTenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "id": "9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "isDefault": true,
    "managedByTenants": [],
    "name": "Sponsership-by-Microsoft",
    "state": "Enabled",
    "tenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "user": {
      "name": "janvi@vcloud-lab.com",
      "type": "user"
    }
  }
]

Create a new Azure Key Vault resource, note down the resource ID I will use it later in the command.

az keyvault create --name vCloud02Vault --resource-group vcloud-lab.com --location 'East US' --sku Standard

{
  "id": "/subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud02Vault",
  "location": "eastus",
  "name": "vCloud02Vault",
  "properties": {
    "accessPolicies": [
      {
        "applicationId": null,
        "objectId": "38638e40-4971-4648-971d-2ee1f40724eb",
        "permissions": {
          "certificates": [
            "get",
            "list",
            "delete",
            "create",
            "import",
            "update",
            "managecontacts",
            "getissuers",
            "listissuers",
            "setissuers",
            "deleteissuers",
            "manageissuers",
            "recover"
          ],
          "keys": [
            "get",
            "create",
            "delete",
            "list",
            "update",
            "import",
            "backup",
            "restore",
            "recover"
          ],
          "secrets": [
            "get",
            "list",
            "set",
            "delete",
            "backup",
            "restore",
            "recover"
          ],
          "storage": [
            "get",
            "list",
            "delete",
            "set",
            "update",
            "regeneratekey",
            "setsas",
            "listsas",
            "getsas",
            "deletesas"
          ]
        },
        "tenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
      }
    ],
    "createMode": null,
    "enablePurgeProtection": null,
    "enableRbacAuthorization": null,
    "enableSoftDelete": true,
    "enabledForDeployment": false,
    "enabledForDiskEncryption": null,
    "enabledForTemplateDeployment": null,
    "networkAcls": null,
    "privateEndpointConnections": null,
    "provisioningState": "Succeeded",
    "sku": {
      "family": "A",
      "name": "Standard"
    },
    "softDeleteRetentionInDays": 90,
    "tenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "vaultUri": "https://vcloud02vault.vault.azure.net/"
  },
  "resourceGroup": "vcloud-lab.com",
  "tags": {},
  "type": "Microsoft.KeyVault/vaults"
}

Once key vault is created, setup a new secret and set attribute content type (description) on to it.

az keyvault secret set --name RootSecret --vault-name vCloud02Vault --value 'P@ssw0rd'

{
  "attributes": {
    "created": "2021-04-08T07:57:29+00:00",
    "enabled": true,
    "expires": null,
    "notBefore": null,
    "recoveryLevel": "Recoverable+Purgeable",
    "updated": "2021-04-08T07:57:29+00:00"
  },
  "contentType": null,
  "id": "https://vcloud02vault.vault.azure.net/secrets/RootSecret/03d6fd62056a4790a8982b1a75f320f8",
  "kid": null,
  "managed": null,
  "name": "RootSecret",
  "tags": {
    "file-encoding": "utf-8"
  },
  "value": "P@ssw0rd"
}
                                                                                                                                           [13:27]  
❯ az keyvault secret set-attributes --name RootSecret --vault-name vCloud02Vault --content-type 'Esxi Root Password'

{
  "attributes": {
    "created": "2021-04-08T07:57:29+00:00",
    "enabled": true,
    "expires": null,
    "notBefore": null,
    "recoveryLevel": "Recoverable+Purgeable",
    "updated": "2021-04-08T07:57:39+00:00"
  },
  "contentType": "Esxi Root Password",
  "id": "https://vcloud02vault.vault.azure.net/secrets/RootSecret/03d6fd62056a4790a8982b1a75f320f8",
  "kid": null,
  "managed": null,
  "name": "RootSecret",
  "tags": {
    "file-encoding": "utf-8"
  },
  "value": null
}

Next get the complete information of AzureAD user whom i will provide Key vault access policy and role, Grab ObjectId from the list.

az ad user show --id [email protected]

{
  "accountEnabled": true,
  "ageGroup": null,
  "assignedLicenses": [],
  "assignedPlans": [],
  "city": null,
  "companyName": null,
  "consentProvidedForMinor": null,
  "country": null,
  "createdDateTime": "2021-04-03T10:35:37Z",
  "creationType": null,
  "deletionTimestamp": null,
  "department": null,
  "dirSyncEnabled": null,
  "displayName": "vault viewer",
  "employeeId": null,
  "facsimileTelephoneNumber": null,
  "givenName": null,
  "immutableId": null,
  "isCompromised": null,
  "jobTitle": null,
  "lastDirSyncTime": null,
  "legalAgeGroupClassification": null,
  "mail": null,
  "mailNickname": "vaultviewer",
  "mobile": null,
  "objectId": "8ab61685-c967-460d-8152-7d41b54449fe",
  "objectType": "User",
  "odata.metadata": "https://graph.windows.net/3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/$metadata#directoryObjects/@Element",
  "odata.type": "Microsoft.DirectoryServices.User",
  "onPremisesDistinguishedName": null,
  "onPremisesSecurityIdentifier": null,
  "otherMails": [],
  "passwordPolicies": null,
  "passwordProfile": null,
  "physicalDeliveryOfficeName": null,
  "postalCode": null,
  "preferredLanguage": null,
  "provisionedPlans": [],
  "provisioningErrors": [],
  "proxyAddresses": [],
  "refreshTokensValidFromDateTime": "2021-04-03T12:10:20Z",
  "showInAddressList": null,
  "signInNames": [],
  "sipProxyAddress": null,
  "state": null,
  "streetAddress": null,
  "surname": null,
  "telephoneNumber": null,
  "[email protected]": "directoryObjects/8ab61685-c967-460d-8152-7d41b54449fe/Microsoft.DirectoryServices.User/thumbnailPhoto",
  "usageLocation": null,
  "userIdentities": [],
  "userPrincipalName": "vaultviewer@vcloud-lab.com",
  "userState": null,
  "userStateChangedOn": null,
  "userType": "Member"
}

Using the User Object ID and Key vault resource ID (earlier shown in the command) set a secret access policy on the keyvault. In the Json output you can see the newly provided access.

az keyvault set-policy --name vCloud02Vault --object-id 8ab61685-c967-460d-8152-7d41b54449fe --secret-permissions get list

{
  "id": "/subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud02Vault",
  "location": "eastus",
  "name": "vCloud02Vault",
  "properties": {
    "accessPolicies": [
      {
        "applicationId": null,
        "objectId": "38638e40-4971-4648-971d-2ee1f40724eb",
        "permissions": {
          "certificates": [
            "get",
            "list",
            "delete",
            "create",
            "import",
            "update",
            "managecontacts",
            "getissuers",
            "listissuers",
            "setissuers",
            "deleteissuers",
            "manageissuers",
            "recover"
          ],
          "keys": [
            "get",
            "create",
            "delete",
            "list",
            "update",
            "import",
            "backup",
            "restore",
            "recover"
          ],
          "secrets": [
            "get",
            "list",
            "set",
            "delete",
            "backup",
            "restore",
            "recover"
          ],
          "storage": [
            "get",
            "list",
            "delete",
            "set",
            "update",
            "regeneratekey",
            "setsas",
            "listsas",
            "getsas",
            "deletesas"
          ]
        },
        "tenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
      },
      {
        "applicationId": Null,
        "objectId": "8ab61685-c967-460d-8152-7d41b54449fe",
        "permissions": {
          "certificates": null,
          "keys": null,
          "secrets": [
            "list",
            "get"
          ],
          "storage": null
        },
        "tenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
      }
    ],
    "createMode": null,
    "enablePurgeProtection": null,
    "enableRbacAuthorization": null,
    "enableSoftDelete": true,
    "enabledForDeployment": false,
    "enabledForDiskEncryption": null,
    "enabledForTemplateDeployment": null,
    "networkAcls": null,
    "privateEndpointConnections": null,
    "provisioningState": "Succeeded",
    "sku": {
      "family": "A",
      "name": "Standard"
    },
    "softDeleteRetentionInDays": 90,
    "tenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "vaultUri": "https://vcloud02vault.vault.azure.net/"
  },
  "resourceGroup": "vcloud-lab.com",
  "tags": {},
  "type": "Microsoft.KeyVault/vaults"
}

After key vault access policy configuration, configure role (key vault reader) assignment access to the user on key vault ID got earlier.

az role assignment create --assignee [email protected] --role 'Key Vault Reader' --scope /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud02Vault

{
  "canDelegate": null,
  "condition": null,
  "conditionVersion": null,
  "description": null,
  "id": "/subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud02Vault/providers/Microsoft.Authorization/roleAssignments/5dd58787-27c1-4e91-939b-20ac020f5652",
  "name": "5dd58787-27c1-4e91-939b-20ac020f5652",
  "principalId": "8ab61685-c967-460d-8152-7d41b54449fe",
  "principalType": "User",
  "resourceGroup": "vcloud-lab.com",
  "roleDefinitionId": "/subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/providers/Microsoft.Authorization/roleDefinitions/21090545-7ca7-4776-b22c-e363652d74d2",
  "scope": "/subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud02Vault",
  "type": "Microsoft.Authorization/roleAssignments"
}

Re login to the azure with vaultviewer account to test if you can access and show/Retrieve secret value from the azure key vault.

az login
The default web browser has been opened at https://login.microsoftonline.com/common/oauth2/authorize. Please continue the login in the web browser. If no web browser is available or if the web browser fails to open, use device code flow with `az login --use-device-code`.
You have logged in. Now let us find all the subscriptions to which you have access...
[
  {
    "cloudName": "AzureCloud",
    "homeTenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "id": "9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "isDefault": true,
    "managedByTenants": [],
    "name": "Sponsership-by-Microsoft",
    "state": "Enabled",
    "tenantId": "3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "user": {
      "name": "vaultviewer@vcloud-lab.com",
      "type": "user"
    }
  }
]

❯ az keyvault secret show --name RootSecret --vault-name vCloud02Vault
{
  "attributes": {
    "created": "2021-04-08T07:57:29+00:00",
    "enabled": true,
    "expires": null,
    "notBefore": null,
    "recoveryLevel": "Recoverable+Purgeable",
    "updated": "2021-04-08T07:57:39+00:00"
  },
  "contentType": "Esxi Root Password",
  "id": "https://vcloud02vault.vault.azure.net/secrets/RootSecret/03d6fd62056a4790a8982b1a75f320f8",
  "kid": null,
  "managed": null,
  "name": "RootSecret",
  "tags": {
    "file-encoding": "utf-8"
  },
  "value": "P@ssw0rd"
}

Download this script here or available on github.com.

Useful Articles
CREATE NEW NSG (NETWORK SECURITY GROUP - VIRTUAL FIREWALL ACL) ON MICROSOFT AZURE  
POWERSHELL - EXPORT AZURE NSG (NETWORK SECURITY GROUP) RULES TO EXCEL
MICROSOFT AZURE POWERSHELL: CREATING NEW NSG (NETWORK SECURITY GROUP)
MICROSOFT AZURE POWERSHELL: CLONING (COPING) OR IMPORTING EXISTING NSG (NETWORK SECURITY GROUP) FROM EXCEL



This post first appeared on Tales From Real IT System Administrators World And Non-production Environment, please read the originial post: here

Share the post

Working With Azure Key Vault Using Azure PowerShell and AzureCLI

×

Subscribe to Tales From Real It System Administrators World And Non-production Environment

Get updates delivered right to your inbox!

Thank you for your subscription

×