How to encrypt Windows VM Disks if yours VM and keyvault resource group is different.

How to encrypt a VM if yours VM resource group and keyvault resource group is different


      VM Name :- rakdbserver01
       Resource Group :- web-rg

      KeyVault  Name : - hpvault01-rak
        Resource Group :- keyvaultrg

      key inside the keyvault name :- diskencryptionkey

By default  AZ CLI command  will not encrypt your VM if your VM Resource group is different from keyvault resource group until you do not give contributor access to the SPN on subscription and provide Resource ID of the Keyvault in az cli command.

and you will get an error like:-

The Resource 'Microsoft.KeyVault/vaults/XXXXX-ra' under resource group 'XX-rg' was not found.

PS C:\windows\system32> az vm encryption enable --disk-encryption-keyvault '/subscriptions/9239f519-8504-4e92-ae6f-c84d53ba3714/resourceGroups/keyvaultrg/providers/Microsoft.KeyVault/vaults/hpvault01-rak'  --key-encryption-key diskencryptionkey --key-encryption-keyvault hpvault01-ra --name rakdbserver01 --resource-group web-rg  --volume-type ALL
az : ERROR: The Resource 'Microsoft.KeyVault/vaults/hpvault01-rak' under resource group 'web-rg' was not found. For more details please go to https://aka.ms/ARMResourceNotFoundFix
At line:1 char:1
+ az vm encryption enable --disk-encryption-keyvault '/subscriptions/92 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (ERROR: The Reso...urceNotFoundFix:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

In my current situation the VM is in web-rg resource group and keyvault is in different resource group  keyvaultrg

Resolution:-

Now when i try to encrypt the VM, i get above error. 
In order to resolve this issue, we need to perform this operation through Terraform/ or ARM template.

I like to do it through Terraform, hence is scripts to do this.

Create a Variables.tf file
=====================

variable "encryption_algorithm" {
  description = "Algo for encryption"
  default     = "RSA-OAEP"
}

variable "volume_type" {
  default = "ALL"
}

variable "encrypt_operation" {
  default = "EnableEncryption"
}

variable "keyvaultname" {
  default ="hpvault01-rak"
   }


variable "type_handler_version" {
  description = "Type handler version of the VM extension to use. Defaults to 2.2 on Windows and 1.1 on Linux"
  default     = ""
}

~~~~~~~~~~~~~~~
2. Create a Datas_ource.tf
============

data "azurerm_key_vault" "hpvault01" {
  name                = "hpvault01-rak"
  resource_group_name = "keyvaultrg"
}
data "azurerm_key_vault_key" "diskencryptionkey" {
  name         = "diskencryptionkey"
  key_vault_id = "${data.azurerm_key_vault.hpvault01.id}"
}

output "keyvaultname" {
  value = "${data.azurerm_key_vault.hpvault01.name}"
}

output "keyvaultURL" {
  value = "${data.azurerm_key_vault.hpvault01.vault_uri}"
  }

output "KeyVaultResourceId" {
  value = "${data.azurerm_key_vault.hpvault01.id}"
}


3. Create a main.tf
==========

resource "azurerm_virtual_machine_extension" "vmextensionwindows" {
  name                       = "AzureDiskEncryption"
  location                   = "westus2"
  resource_group_name        = "web-rg"
  virtual_machine_name       = "rakdbserver01"
  publisher                  = "Microsoft.Azure.Security"
  type                       = "AzureDiskEncryption"
  type_handler_version       = "${var.type_handler_version == "" ? "2.2" : var.type_handler_version}"
 
  auto_upgrade_minor_version = true

  settings = <<SETTINGS
    {
        "EncryptionOperation": "${var.encrypt_operation}",
        "KeyVaultURL": "${data.azurerm_key_vault.hpvault01.vault_uri}",
        "KeyVaultResourceId": "${data.azurerm_key_vault.hpvault01.id}",
        "KeyEncryptionKeyURL": "${data.azurerm_key_vault_key.diskencryptionkey.id}",
        "KekVaultResourceId": "${data.azurerm_key_vault.hpvault01.id}",
        "KeyEncryptionAlgorithm": "${var.encryption_algorithm}",
        "SequenceVersion": "random_id.my_id.b64",
        "VolumeType": "${var.volume_type}"
    }
SETTINGS

}

put  these 3 files in one folder
add your backend.tf and version.tf

and run

terraform init
terraform plan
terraform apply

you will be able to encrypt the VM.

terraform apply

data.azurerm_key_vault.hpvault01: Refreshing state...
data.azurerm_key_vault_key.diskencryptionkey: Refreshing state...

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  + azurerm_virtual_machine_extension.vmextensionwindows
      id:                         <computed>
      auto_upgrade_minor_version: "true"
      location:                   "westus2"
      name:                       "AzureDiskEncryption"
      publisher:                  "Microsoft.Azure.Security"
      resource_group_name:        "web-rg"
      settings:                   "    {\n        \"EncryptionOperation\": \"EnableEncryption\",\n        \"KeyVaultURL\": \"https://hpvault01-rak.vault.azure.net/\",\n        \"KeyVaultResourceId\": \"/subscriptions/9239f519-8504-4e92-ae6f-c84d53ba3714/resourceGroups/keyvaultrg/providers/Microsoft.KeyVault/vaults/hpvault01-rak\",\t\t\t\t\t\n        \"KeyEncryptionKeyURL\": \"https://hpvault01-rak.vault.azure.net/keys/diskencryptionkey/6532a35ddb2c45c098d67a1340b305f4\",\n        \"KekVaultResourceId\": \"/subscriptions/9239f519-8504-4e92-ae6f-c84d53ba3714/resourceGroups/keyvaultrg/providers/Microsoft.KeyVault/vaults/hpvault01-rak\",\t\t\t\t\t\n        \"KeyEncryptionAlgorithm\": \"RSA-OAEP\",\n        \"SequenceVersion\": \"random_id.my_id.b64\",\n        \"VolumeType\": \"ALL\"\n    }\n"
      tags.%:                     <computed>
      type:                       "AzureDiskEncryption"
      type_handler_version:       "2.2"
      virtual_machine_name:       "rakdbserver01"


Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

azurerm_virtual_machine_extension.vmextensionwindows: Creating...
  auto_upgrade_minor_version: "" => "true"
  location:                   "" => "westus2"
  name:                       "" => "AzureDiskEncryption"
  publisher:                  "" => "Microsoft.Azure.Security"
  resource_group_name:        "" => "web-rg"
  settings:                   "" => "    {\n        \"EncryptionOperation\": \"EnableEncryption\",\n        \"KeyVaultURL\": \"https://hpvault01-rak.vault.azure.net/\",\n        \"KeyVaultResourceId\": \"/subscriptions/9239f519-8504-4e92-ae6f-c84d53ba3714/resourceGroups/keyvaultrg/providers/Microsoft.KeyVault/vaults/hpvault01-rak\",\t\t\t\t\t\n        \"KeyEncryptionKeyURL\": \"https://hpvault01-rak.vault.azure.net/keys/diskencryptionkey/6532a35ddb2c45c098d67a1340b305f4\",\n        \"KekVaultResourceId\": \"/subscriptions/9239f519-8504-4e92-ae6f-c84d53ba3714/resourceGroups/keyvaultrg/providers/Microsoft.KeyVault/vaults/hpvault01-rak\",\t\t\t\t\t\n        \"KeyEncryptionAlgorithm\": \"RSA-OAEP\",\n        \"SequenceVersion\": \"random_id.my_id.b64\",\n        \"VolumeType\": \"ALL\"\n    }\n"
  tags.%:                     "" => "<computed>"
  type:                       "" => "AzureDiskEncryption"
  type_handler_version:       "" => "2.2"
  virtual_machine_name:       "" => "rakdbserver01"
azurerm_virtual_machine_extension.vmextensionwindows: Still creating... (10s elapsed)
azurerm_virtual_machine_extension.vmextensionwindows: Still creating... (20s elapsed)
azurerm_virtual_machine_extension.vmextensionwindows: Still creating... (30s elapsed)
azurerm_virtual_machine_extension.vmextensionwindows: Still creating... (40s elapsed)
azurerm_virtual_machine_extension.vmextensionwindows: Still creating... (50s elapsed)
azurerm_virtual_machine_extension.vmextensionwindows: Still creating... (1m0s elapsed)
azurerm_virtual_machine_extension.vmextensionwindows: Creation complete after 1m1s (ID: /subscriptions/9239f519-8504-4e92-ae6f-...erver01/extensions/AzureDiskEncryption)

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

KekVaultResourceId = /subscriptions/9239f519-8504-4e92-ae6f-c84d53ba3714/resourceGroups/keyvaultrg/providers/Microsoft.KeyVault/vaults/hpvault01-rak
KeyVaultResourceId = /subscriptions/9239f519-8504-4e92-ae6f-c84d53ba3714/resourceGroups/keyvaultrg/providers/Microsoft.KeyVault/vaults/hpvault01-rak
keyvaultURL = https://hpvault01-rak.vault.azure.net/
keyvaultname = hpvault01-rak
PS C:\Rakesh>

output of manage-bde -status

BitLocker Drive Encryption: Configuration Tool version 10.0.17763
Copyright (C) 2013 Microsoft Corporation. All rights reserved.

Disk volumes that can be protected with
BitLocker Drive Encryption:
Volume D: [Temporary Storage]
[Data Volume]

    Size:                 32.00 GB
    BitLocker Version:    2.0
    Conversion Status:    Used Space Only Encrypted
    Percentage Encrypted: 100.0%
    Encryption Method:    XTS-AES 256
    Protection Status:    Protection On
    Lock Status:          Unlocked
    Identification Field: Unknown
    Automatic Unlock:     Enabled
    Key Protectors:
        External Key (Required for automatic unlock)
        Numerical Password

Volume \\?\Volume{5c300b95-0000-0000-0000-010000000000}\ [Bek Volume]
[Data Volume]

    Size:                 0.05 GB
    BitLocker Version:    None
    Conversion Status:    Fully Decrypted
    Percentage Encrypted: 0.0%
    Encryption Method:    None
    Protection Status:    Protection Off
    Lock Status:          Unlocked
    Identification Field: None
    Automatic Unlock:     Disabled
    Key Protectors:       None Found

Volume F: [New Volume]
[Data Volume]

    Size:                 16.00 GB
    BitLocker Version:    2.0
    Conversion Status:    Used Space Only Encrypted
    Percentage Encrypted: 100.0%
    Encryption Method:    XTS-AES 256
    Protection Status:    Protection On
    Lock Status:          Unlocked
    Identification Field: Unknown
    Automatic Unlock:     Enabled
    Key Protectors:
        External Key (Required for automatic unlock)
        Numerical Password

Volume C: [Windows]
[OS Volume]

    Size:                 126.51 GB
    BitLocker Version:    2.0
    Conversion Status:    Encryption in Progress
    Percentage Encrypted: 85.1%
    Encryption Method:    XTS-AES 256
    Protection Status:    Protection Off
    Lock Status:          Unlocked
    Identification Field: Unknown
    Key Protectors:
        External Key
        Numerical Password


output of  az vm encryption show --name rakdbserver01 --resource-group web-rg

az vm encryption show --name rakdbserver01 --resource-group web-rg
{
  "disks": [
    {
      "encryptionSettings": [
        {
          "diskEncryptionKey": {
            "secretUrl": "https://hpvault01-rak.vault.azure.net/secrets/86ABDA90-90D0-4FC7-BE2A-5282ADC6FA46/45a29e307675415588ccf6d90ac05033",
            "sourceVault": {
              "id": "/subscriptions/9239f519-8504-4e92-ae6f-c84d53ba3714/resourceGroups/keyvaultrg/providers/Microsoft.KeyVault/vaults/hpvault01-rak"
            }
          },
          "enabled": true,
          "keyEncryptionKey": {
            "keyUrl": "https://hpvault01-rak.vault.azure.net/keys/diskencryptionkey/42c62b79bc0b4e85a2a4a863dcf0ca38",
            "sourceVault": {
              "id": "/subscriptions/9239f519-8504-4e92-ae6f-c84d53ba3714/resourceGroups/keyvaultrg/providers/Microsoft.KeyVault/vaults/hpvault01-rak"
            }
          }
        }
      ],
      "name": "rakdbserver01-os",
      "statuses": [
        {
          "code": "EncryptionState/encrypted",
          "displayStatus": "Encryption is enabled on disk",
          "level": "Info",
          "message": null,
          "time": null
        }
      ]
    },
    {
      "encryptionSettings": [
        {
          "diskEncryptionKey": {
            "secretUrl": "https://hpvault01-rak.vault.azure.net/secrets/D8CC1081-C26A-4B7D-8884-A787FDA45A7E/4b3a83b74ecd499997446c19e653d701",
            "sourceVault": {
              "id": "/subscriptions/9239f519-8504-4e92-ae6f-c84d53ba3714/resourceGroups/keyvaultrg/providers/Microsoft.KeyVault/vaults/hpvault01-rak"
            }
          },
          "enabled": true,
          "keyEncryptionKey": {
            "keyUrl": "https://hpvault01-rak.vault.azure.net/keys/diskencryptionkey/42c62b79bc0b4e85a2a4a863dcf0ca38",
            "sourceVault": {
              "id": "/subscriptions/9239f519-8504-4e92-ae6f-c84d53ba3714/resourceGroups/keyvaultrg/providers/Microsoft.KeyVault/vaults/hpvault01-rak"
            }
          }
        }
      ],
      "name": "data-disk01",
      "statuses": [
        {
          "code": "EncryptionState/encrypted",
          "displayStatus": "Encryption is enabled on disk",
          "level": "Info",
          "message": null,
          "time": null
        }
      ]
    }
  ],
  "status": [
    {
      "code": "ProvisioningState/succeeded",
      "displayStatus": "Provisioning succeeded",
      "level": "Info",
      "message": "",
      "time": null
    }
  ],
  "substatus": null
}

PS C:\windows\system32>

  Thanks for Reading.


Comments

Popular posts from this blog

How to use Custom Script Extensions for windows using Azure PowerShell - AZ CLI and from Terraform

How to create a Resource group in Azure using Terraform Part -1

Error inspecting states in the "azurerm" backend: storage: service returned error: StatusCode=403, ErrorCode=AuthenticationFailed