This is second part ofCreate 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 Vaultis a cloud service that provides a secure store for secrets. You can securely storekeys, 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
Firstcmdlet connects to azure using az moduleand creates a new key vault resource. Download this script here or available on github.com.
#Login to the Azure Account ❯ Connect-AzAccountAccount 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 group❯ New-AzKeyVault-NamevCloud01Vault-ResourceGroupNamevcloud-lab.com-Location'EastUS'-SkuStandardVault Name : vCloud01VaultResource Group Name : vcloud-lab.comLocation : East USResource ID : /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud01VaultVault URI : https://vcloud01vault.vault.azure.net/Tenant ID : 3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxSKU : StandardEnabled For Deployment? : FalseEnabled For Template Deployment? : FalseEnabled For Disk Encryption? : FalseEnabled For RBAC Authorization? : FalseSoft Delete Enabled? : TrueEnabled Purge Protection? :Soft Delete Retention Period (days) : 90Enabled 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, restoreNetwork Rule Set : Default Action : Allow Bypass : AzureServices IP Rules : Virtual Network Rules :Tags #View the information of installed KeyVault> Get-AzkeyVault-VaultNamevCloud01Vault :
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-Force❯ Set-AzKeyVaultSecret-VaultNamevCloud01Vault-NameRootSecret-SecretValue$secretValue-ContentType'ESXirootpassword'Vault Name : vcloud01vaultName : RootSecretVersion : a97eabdb6cd0499fb30721b0a4784a87Id : https://vcloud01vault.vault.azure.net:443/secrets/RootSecret/a97eabdb6cd0499fb30721b0a4784a87Enabled : TrueExpires :Not Before :Created : 06-04-2021 16:53:14Updated : 06-04-2021 16:53:14Content Type : ESXi root passwordTags :#Configure Access Policy for Azure key vault> Set-AzKeyVaultAccessPolicy-VaultNamevCloud01Vault-UserPrincipalNamevaultviewer@vcloud-lab.com-PermissionsToSecretsGet,List
I have already create a new user account vaultviewer on Azure Active directory for testingCreating 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 principalon the keyvault. (In my case user principal name is vaultviewer)
#Get information of Key Vault, and grab Resource ID.❯ $keyVault=Get-AzkeyVault-VaultNamevCloud01Vault❯ $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 vault❯ New-AzRoleAssignment-SignInNamevaultviewer@vcloud-lab.com-RoleDefinitionName'KeyVaultReader'-Scope$keyVault.ResourceIDRoleAssignmentId : /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud01Vault/providers/Microsoft.Authoriza tion/roleAssignments/a0930a57-59f4-4429-942a-23722cd25ec6Scope : /subscriptions/9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/vcloud-lab.com/providers/Microsoft.KeyVault/vaults/vCloud01VaultDisplayName : vault viewerSignInName : [emailprotected]RoleDefinitionName : Key Vault ReaderRoleDefinitionId : 21090545-7ca7-4776-b22c-e363652d74d2ObjectId : 8ab61685-c967-460d-8152-7d41b54449feObjectType : UserCanDelegate : FalseDescription :ConditionVersion :Condition :
Logout of Azure powershellaccount 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-VaultNamevCloud01Vault-NameRootSecret❯ $password=ConvertFrom-SecureString$keyVaultSecret.SecretValue-AsPlainText❯ $passwordT0p$ecret
AzureCLI example
Login to the AzureCLI, All the Az command generate output in JSON format.
❯ az loginThe 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 ObjectIdfrom the list.
❯ az ad user show --id [emailprotected]{ "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, "[emailprotected]": "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 secretaccess policy on the keyvault. In the Json output you can see the newlyprovided 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"}
Afterkey 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 [emailprotected] --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/Retrievesecret value from the azure key vault.
❯ az loginThe 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 thisscript hereor available ongithub.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