Rotate Azure storage account access keys using terraform - azure

I have below requirments.
Rotate Storage account access keys (primary_access_key and secondary_access_key both) via a terraform.
add the new regenerated keys as a new version to Secrets created in keyvault for both primary and secondary access keys.
resource "azurerm_storage_account" "example" {
name = "storageaccrotatekeys"
resource_group_name = "accessrotate"
location = "East US"
account_tier = "Standard"
account_replication_type = "LRS"
public_network_access_enabled = false
}
Below azure_storage_account resource only contains attributes for primary_access_key and secondary_access_key that too sensitive values.
I couldn't find any option to rotate keys. Please help
https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/storage_account#import

It may directly be not happening with terraform to rotate the access keys
AFAIK but
please check this customer_managed_key block that can be given in resource
azurerm_storage_account block where auto rotation can be enabled with keyvaultId and version.This customer_managed_key which contains the argument key_version which is Optional to mention the version of Key Vault Key. To enable Automatic Key Rotation you can avoid this option.
To manually rotate , give the version in the block key_version.
If separate block is created for customer_managed_key , you can provide required argument key_vault_key_id where in giving version-less key ID will enable auto-rotation of this key.
Note: customer_managed_key needs account_kind to be StorageV2 UserAssigned as the identity type.
Code: from azurerm_storage_account_customer_managed_key | Resources | hashicorp/azurerm | Terraform Registry
provider "azurerm" {
features {
resource_group {
prevent_deletion_if_contains_resources = false
}
}
}
resource "azurerm_resource_group" "example" {
name = "<resource group>"
location = "westus2"
}
provider "azurerm" {
features {}
alias = "cloud_operations"
}
data "azurerm_client_config" "current" {}
resource "azurerm_key_vault" "example" {
name = "ka-examplekv"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
tenant_id = data.azurerm_client_config.current.tenant_id
sku_name = "standard"
purge_protection_enabled = true
}
resource "azurerm_key_vault_access_policy" "storage" {
key_vault_id = azurerm_key_vault.example.id
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = azurerm_storage_account.example.identity.0.principal_id
key_permissions = ["Get", "Create", "List", "Restore", "Recover", "UnwrapKey", "WrapKey", "Purge", "Encrypt", "Decrypt", "Sign", "Verify"]
secret_permissions = ["Get"]
}
resource "azurerm_key_vault_access_policy" "client" {
key_vault_id = azurerm_key_vault.example.id
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azurerm_client_config.current.object_id
key_permissions = ["Get", "Create", "Delete", "List", "Restore", "Recover", "UnwrapKey", "WrapKey", "Purge", "Encrypt", "Decrypt", "Sign", "Verify"]
secret_permissions = ["Get","List"]
}
resource "azurerm_key_vault_key" "example" {
name = "ka-tfexkey"
key_vault_id = azurerm_key_vault.example.id
key_type = "RSA"
key_size = 2048
key_opts = ["decrypt", "encrypt", "sign", "unwrapKey", "verify", "wrapKey"]
depends_on = [
azurerm_key_vault_access_policy.client,
azurerm_key_vault_access_policy.storage,
]
}
resource "azurerm_storage_account" "example" {
name = "kaexamplestor"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
account_tier = "Standard"
account_replication_type = "GRS"
identity {
type = "SystemAssigned"
}
}
resource "azurerm_storage_account_customer_managed_key" "example" {
storage_account_id = azurerm_storage_account.example.id
key_vault_id = azurerm_key_vault.example.id
key_name = azurerm_key_vault_key.example.name
}
Also check this time rotaing resource which rotates UTC timestamp stored in the Terraform state and recreates resource when the current time in the locally stored source is beyond the rotation time. This occurs only when Terraform is executed
Reference:
customer_managed_key in azurerm_storage_account | Resources | hashicorp/azurerm | Terraform Registry

Related

Error when appending multiple key_vault_access_policy in a key_vault resource - resource needs to be imported into the State - Terraform / Azure

I'm trying to deploy a key_vault resource that contains two key_vault_access_policy using this code:
data "azurerm_client_config" "current" {}
module "agw_user_assigned_identity" {
source = "../modules/resources-blocks/user_assigned_identity"
user_assigned_identity_name = "agw-user-signed-id"
resource_group_name = module.resource_group.name
resource_group_location = module.resource_group.location
}
module "key_vault" {
source = "../modules/resources-hub/key_vault"
key_vault_name = local.key_vault_name
resource_group_location = module.resource_group.location
resource_group_name = module.resource_group.name
tenant_id = data.azurerm_client_config.current.tenant_id
soft_delete_retention_days = 90
}
module "key_vault_private_certificate" {
source = "../modules/resources-blocks/key_vault_certificate"
key_vault_id = module.key_vault.id
certificate_name = local.agw_certificate_name
certificate_path = var.SSL_CERTIFICATE_PATH
certificate_password = var.SSL_CERTIFICATE_PASSWORD
depends_on = [module.key_vault_access_policy_agw]
}
module "key_vault_access_policy_users" {
source = "../modules/resources-blocks/key_vault_access_policy"
key_vault_id = module.key_vault.id
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azurerm_client_config.current.object_id
certificate_permissions = ["Backup", "Create", "Delete", "DeleteIssuers", "Get", "GetIssuers", "Import", "List", "ListIssuers", "ManageContacts", "ManageIssuers", "Purge", "Recover", "Restore", "SetIssuers", "Update"]
key_permissions = ["Backup", "Create", "Decrypt", "Delete", "Encrypt", "Get", "Import", "List", "Purge", "Recover", "Restore", "Sign", "UnwrapKey", "Update", "Verify", "WrapKey"]
secret_permissions = ["Backup", "Delete", "Get", "List", "Purge", "Recover", "Restore", "Set"]
storage_permissions = ["Backup", "Delete", "DeleteSAS", "Get", "GetSAS", "List", "ListSAS", "Purge", "Recover", "RegenerateKey", "Restore", "Set", "SetSAS", "Update"]
depends_on = [module.key_vault]
}
module "key_vault_access_policy_agw" {
source = "../modules/resources-blocks/key_vault_access_policy"
key_vault_id = module.key_vault.id
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = module.agw_user_assigned_identity.principal_id
secret_permissions = ["Get"]
depends_on = [module.key_vault_access_policy_users]
}
With the resources created in another file:
resource "azurerm_key_vault" "kv" {
name = var.key_vault_name
location = var.resource_group_location
resource_group_name = var.resource_group_name
enabled_for_disk_encryption = true
tenant_id = var.tenant_id
soft_delete_retention_days = var.soft_delete_retention_days
purge_protection_enabled = false
sku_name = "standard"
}
locals {
get_only_access = ["Get", "List"]
}
resource "azurerm_key_vault_access_policy" "acess_policy" {
key_vault_id = var.key_vault_id
tenant_id = var.tenant_id
object_id = var.object_id
key_permissions = var.get_only_access ? local.get_only_access : var.key_permissions
secret_permissions = var.get_only_access ? local.get_only_access : var.secret_permissions
storage_permissions = var.get_only_access ? local.get_only_access : var.storage_permissions
certificate_permissions = var.get_only_access ? local.get_only_access : var.certificate_permissions
}
The error that I get with the command "terraform apply -var-file="variables.tfvars"" is the following:
Error: A resource with the ID "/subscriptions/xxxxxxxxxxx/resourceGroups/xxxxxxxxxx/providers/Microsoft.KeyVault/vaults/xxxxxxxx/objectId/xxxxxxxxxxxx" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_key_vault_access_policy" for more information.
│
│ with module.key_vault_access_policy_users.azurerm_key_vault_access_policy.acess_policy,
│ on ..\modules\resources-blocks\key_vault_access_policy\main.tf line 5, in resource "azurerm_key_vault_access_policy" "acess_policy":
│ 5: resource "azurerm_key_vault_access_policy" "acess_policy" {
Could you please help me to solve this issue?
Just to give you a more general overview, the reason I'm trying to deploy this resources is because I'm creating an Application Gateway and I need to store the SSL certificate in the key_vault resource.
Error: A resource with the ID "/subscriptions/xxxxxxxxxxx/resourceGroups/xxxxxxxxxx/providers/Microsoft.KeyVault/vaults/xxxxxxxx/objectId/xxxxxxxxxxxx" already exists - to be managed via Terraform this resource needs to be imported into the State.
It commonly happens when the terraform state file (running locally) does not match the resources in the Portal terraform state file.
As #Marcin said, you should import the resource with the resourceID and add the respective objectID of keyvault.
Goto keyvault in the portal & get the "resourceID, objectID" as shown here:
Use
terraform import azurerm_key_vault_access_policy.xxxxx ResourceID
to fix this issue.
terraform import azurerm_key_vault_access_policy.example /subscriptions/<suscriptionID>/resourceGroups/<resourcegroupName>/providers/Microsoft.KeyVault/vaults/examples-keyvault/objectId/<ObjectID of Keyvault>
Refer terraform registry & SO worked by me for more information- regarding it.
Output:

Azure terraform application gateway does not have secrets get permission on key vault

I am trying to provision an azure application gateway with terraform. And I have a key vault which has a self signed certificate referenced by the application gateway, but I am getting the below error:
Error: waiting for create/update of Application Gateway: (Name "ssi-test-public-appgateway" / Resource Group "ssi-test"): Code="ApplicationGatewayKeyVaultSecretException" Message="Problem occured while accessing and validating KeyVault Secrets associated with Application Gateway '/subscriptions/XXX/resourceGroups/ssi-test/providers/Microsoft.Network/applicationGateways/ssi-test-public-appgateway'. See details below:" Details=[{"code":"0","message":"The user, group or application 'name=Microsoft.Network/applicationGateways;appid=XXX;oid=XXX;iss=https://sts.windows.net/XXX/' does not have secrets get permission on key vault 'ssi-app-gw-kv;location=westeurope'. For help resolving this issue, please see https://go.microsoft.com/fwlink/?linkid=2125287"}]
And here's my terraform code:
identity.tf
data "azurerm_client_config" "current" {}
resource "azurerm_key_vault" "front_end_key_vault_cert" {
name = var.key_vault_name
location = var.location
resource_group_name = var.resource_group_name
enabled_for_disk_encryption = true
tenant_id = data.azurerm_client_config.current.tenant_id
soft_delete_retention_days = 7
purge_protection_enabled = false
sku_name = "standard"
access_policy {
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azurerm_client_config.current.object_id
certificate_permissions = [
"Backup",
"Create",
"Delete",
"DeleteIssuers",
"Get",
"Import",
"List",
"ListIssuers",
"ManageContacts",
"ManageIssuers",
"Purge",
"Recover",
"Restore",
"SetIssuers",
"Update"
]
key_permissions = [
"Backup",
"Create",
"Decrypt",
"Delete",
"Encrypt",
"Get",
"Import",
"List",
"Purge",
"Recover",
"Restore",
"Sign",
"UnwrapKey",
"Update",
"Verify",
"WrapKey",
]
secret_permissions = [
"Backup",
"Delete",
"Get",
"List",
"Purge",
"Recover",
"Restore",
"Set",
]
}
}
resource "azurerm_key_vault_certificate" "https_cert" {
name = "ssi-self-signed-cert"
key_vault_id = azurerm_key_vault.front_end_key_vault_cert.id
certificate_policy {
issuer_parameters {
name = "Self"
}
key_properties {
exportable = true
key_size = 2048
key_type = "RSA"
reuse_key = true
}
lifetime_action {
action {
action_type = "AutoRenew"
}
trigger {
days_before_expiry = 30
}
}
secret_properties {
content_type = "application/x-pkcs12"
}
x509_certificate_properties {
# Server Authentication = 1.3.6.1.5.5.7.3.1
# Client Authentication = 1.3.6.1.5.5.7.3.2
extended_key_usage = ["1.3.6.1.5.5.7.3.1"]
key_usage = [
"cRLSign",
"dataEncipherment",
"digitalSignature",
"keyAgreement",
"keyCertSign",
"keyEncipherment",
]
subject_alternative_names {
dns_names = ["*.ssi.com"]
}
subject = "CN=*.ssi.com"
validity_in_months = 12
}
}
depends_on = [
azurerm_key_vault.front_end_key_vault_cert
]
}
resource "azurerm_user_assigned_identity" "key_vault_read" {
resource_group_name = var.resource_group_name
location = var.location
name = join("-", [var.project, var.environment, "key_vault_read_permission"])
}
resource "azurerm_role_assignment" "key_vault_role" {
scope = azurerm_key_vault.front_end_key_vault_cert.id
role_definition_name = "Reader"
principal_id = azurerm_user_assigned_identity.key_vault_read.principal_id
depends_on = [
azurerm_key_vault.front_end_key_vault_cert,
azurerm_user_assigned_identity.key_vault_read,
azurerm_key_vault_certificate.https_cert
]
app-gateway.tf
resource "azurerm_application_gateway" "public_app_gateway" {
name = join("-", [var.project, var.environment, "public-appgateway"])
location = var.location
resource_group_name = var.resource_group_name
sku {
name = "Standard_V2"
tier = "Standard_v2"
}
.
.
.
dynamic "ssl_certificate" {
for_each = var.ssl_certificates_configs
content {
name = lookup(ssl_certificate.value, "name")
key_vault_secret_id = azurerm_key_vault_certificate.https_cert.secret_id
}
}
identity {
type = "UserAssigned"
identity_ids = [azurerm_user_assigned_identity.key_vault_read.id]
}
dynamic "request_routing_rule" {
for_each = var.appgw_routings
content {
name = lookup(request_routing_rule.value, "name", local.pb_request_routing_rule_name)
rule_type = lookup(request_routing_rule.value, "rule_type", "Basic")
http_listener_name = lookup(request_routing_rule.value, "http_listener_name", local.pb_listener_name)
backend_address_pool_name = lookup(request_routing_rule.value, "backend_address_pool_name", null)
backend_http_settings_name = lookup(request_routing_rule.value, "backend_http_settings_name", null)
url_path_map_name = lookup(request_routing_rule.value, "url_path_map_name", null)
# redirect_configuration_name = lookup(request_routing_rule.value, "redirect_configuration_name", null)
# rewrite_rule_set_name = lookup(request_routing_rule.value, "rewrite_rule_set_name", null)
}
}
depends_on = [azurerm_role_assignment.key_vault_role]
}
Can someone help me on this?
This role assignment is wrong (i.e. not doing what you want to do): resource "azurerm_role_assignment" "key_vault_role"
What you want do add is a Key Vault access policy: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/key_vault_access_policy
Beware: You need to remove the one access policy that you already have defined in your Key Vault resource and make this a distinct key_vault_access_policy resource, too. You can't mix those two ways to create access policies.
See for instance here for a complete example. Make sure to add an explicit dependency on our resource "azurerm_key_vault_certificate" "https_cert" for the first access policy (example).

In terraform, what is the azurerm cosmosdb default_identity_type setting?

What is the default identity type in CosmosDB in Azure?
https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/cosmosdb_account#default_identity_type
When I run my Terraform plan, the default_identity_type is getting updated, but I don't know what that is. Is there a place where I can see this value in the CLI, resource manager or the portal? What property in Azure does this setting correspond to?
Here is what the azurerm doc says:
default_identity_type - (Optional) The default identity for accessing Key Vault. Possible values are FirstPartyIdentity, SystemAssignedIdentity or start with UserAssignedIdentity. Defaults to FirstPartyIdentity.
There is an identity block, but that seems to be a different thing from default_identity_type.
The documentation says it is for using CosmosDB with key vault, but as far as I know, there are no special settings in the CosmosDB resource for using key vault.
The identity block defines the managed identity for cosmosdb account which currently can only be System Assigned and default_identity_type is for using one managed identity to access the key vault from the cosmosdb account for encyprtion purpose.
The default_identity_type defaults to FirstPartyIdentity which means there is a default Identity with name Azure Cosmos DB which is used by all the cosmosdb resources in Azure and use it to access the keyvault like below example 1. If you are using the identity block with SystemAssigned then you can mention SystemAssignedIdentity in the default_identity_type parameter as shown in the below example 2.
Example 1:
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "example" {
name = "ansumantest-resources"
location = "eastus"
}
## firstparty identity which is provided by Microsoft
data "azuread_service_principal" "cosmosdb" {
display_name = "Azure Cosmos DB"
}
data "azurerm_client_config" "current" {}
resource "azurerm_key_vault" "example" {
name = "ansumantestkv12"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
tenant_id = data.azurerm_client_config.current.tenant_id
sku_name = "premium"
purge_protection_enabled = true
access_policy {
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azurerm_client_config.current.object_id
key_permissions = [
"list",
"create",
"delete",
"get",
"update",
]
}
# identity added in access policy
access_policy {
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azuread_service_principal.cosmosdb.id
key_permissions = [
"get",
"unwrapKey",
"wrapKey",
]
}
}
resource "azurerm_key_vault_key" "example" {
name = "ansumantestkey1"
key_vault_id = azurerm_key_vault.example.id
key_type = "RSA"
key_size = 3072
key_opts = [
"decrypt",
"encrypt",
"wrapKey",
"unwrapKey",
]
}
resource "azurerm_cosmosdb_account" "example" {
name = "ansumantest-cosmosdb"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
offer_type = "Standard"
kind = "MongoDB"
key_vault_key_id = azurerm_key_vault_key.example.versionless_id
default_identity_type = "FirstPartyIdentity"
consistency_policy {
consistency_level = "Strong"
}
geo_location {
location = azurerm_resource_group.example.location
failover_priority = 0
}
}
In this method the Identity that is used to access is the Default Azure Cosmos DB Service Principal, so there won't be any details in the identity blade. Only in Data Encryption Blade you can see the key vault details.
Example 2:
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "example" {
name = "ansumantest-resources"
location = "eastus"
}
data "azurerm_client_config" "current" {}
resource "azurerm_key_vault" "example" {
name = "ansumantestkv12"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
tenant_id = data.azurerm_client_config.current.tenant_id
sku_name = "premium"
purge_protection_enabled = true
access_policy {
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azurerm_client_config.current.object_id
key_permissions = [
"list",
"create",
"delete",
"get",
"update",
]
}
}
resource "azurerm_key_vault_key" "example" {
name = "ansumantestkey2"
key_vault_id = azurerm_key_vault.example.id
key_type = "RSA"
key_size = 3072
key_opts = [
"decrypt",
"encrypt",
"wrapKey",
"unwrapKey",
]
}
resource "azurerm_cosmosdb_account" "example" {
name = "ansumantest-cosmosdb"
location = azurerm_resource_group.example.location
resource_group_name = azurerm_resource_group.example.name
offer_type = "Standard"
kind = "MongoDB"
key_vault_key_id = azurerm_key_vault_key.example.versionless_id
default_identity_type = "FirstPartyIdentity"
#after deployment change to below
#default_identity_type = "SystemAssignedIdentity"
consistency_policy {
consistency_level = "Strong"
}
##system managed identity for this cosmosdb resource
identity {
type="SystemAssigned"
}
geo_location {
location = azurerm_resource_group.example.location
failover_priority = 0
}
}
#providing access to the system managed identity of cosmosdb to keyvault
resource "azurerm_key_vault_access_policy" "example" {
key_vault_id = azurerm_key_vault.example.id
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = azurerm_cosmosdb_account.example.identity.0.principal_id
key_permissions = [
"get",
"unwrapKey",
"wrapKey",
]
}
In this example you cannot set default_identity_type = SystemAssignedIdentity while provisioning the cosmosdb account . Once the cosmos db is deployed with default identity type as firstPartyIdentity then you can modify it to SystemAssignedIdentity and then apply update on the cosmosdb block by using below command :
terraform apply -target="azurerm_cosmosdb_account.example" -auto-approve
Outputs :

Terraform Azure data factory creation

I'm trying to deploy Azure data factory along with customer managed key and identity but after terraform apply customer managed key is not showing in the data factory.
When I try to add the customer managed key manually in data factory it is giving below error.
Operation failed. Managed identity used in CMK not found.
data "azurerm_client_config" "main" {}
resource "azurerm_resource_group" "main" {
name = "rgsupports01"
location = "East US 2"
}
resource "azurerm_user_assigned_identity" "main" {
depends_on = [azurerm_resource_group.main]
name = "supports01-mid"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
}
resource "azurerm_key_vault" "main" {
name = "supportskv01"
location = azurerm_resource_group.main.location
resource_group_name = azurerm_resource_group.main.name
enabled_for_disk_encryption = true
tenant_id = data.azurerm_client_config.main.tenant_id
soft_delete_retention_days = 7
purge_protection_enabled = false
sku_name = "standard"
access_policy {
tenant_id = data.azurerm_client_config.main.tenant_id
object_id = data.azurerm_client_config.main.object_id
key_permissions = [
"Get",
"Unwrapkey",
"Wrapkey",
"Create",
"Delete",
]
secret_permissions = [
"Get",
]
storage_permissions = [
"Get",
]
}
}
resource "azurerm_key_vault_access_policy" "main" {
key_vault_id = azurerm_key_vault.main.id
tenant_id = data.azurerm_client_config.main.tenant_id
object_id = azurerm_user_assigned_identity.main.client_id
key_permissions = [
"Get","List","Unwrapkey","Wrapkey"
]
secret_permissions = [
"Get","List",
]
}
resource "azurerm_key_vault_key" "main" {
depends_on = [azurerm_key_vault_access_policy.main]
name = "supportrsakeys01"
key_vault_id = azurerm_key_vault.main.id
key_type = "RSA"
key_size = 2048
key_opts = [
"decrypt",
"encrypt",
"sign",
"unwrapKey",
"verify",
"wrapKey",
]
}
resource "azurerm_data_factory" "adf" {
#depends_on = [azurerm_key_vault_key.main]
name = "supportdfs01"
resource_group_name = azurerm_resource_group.main.name
location = azurerm_resource_group.main.location
public_network_enabled = false
customer_managed_key_id = resource.azurerm_key_vault_key.main.id
identity {
type = "UserAssigned"
identity_ids = [resource.azurerm_user_assigned_identity.main.id]
}
}
resource "azurerm_key_vault_access_policy" "new" {
depends_on = [azurerm_data_factory.adf]
key_vault_id = azurerm_key_vault.main.id
tenant_id = data.azurerm_client_config.main.tenant_id
object_id = azurerm_user_assigned_identity.main.principal_id
key_permissions = [
"Get","List","Unwrapkey","Wrapkey"
]
secret_permissions = [
"Get","List",
]
}
Do not specific access_policy within the Key Vault resource, only use azurerm_key_vault_access_policy resources. The way you have specified it, will bring conflicts and probably mess up access policies. See here.

Terraform Azure provider - VM encryption at rest

I'm getting an error while trying to set up a VM with a Key vault. This is part of the code I think is relevant.
resource "azurerm_key_vault_key" "example" {
name = "TF-key-example"
key_vault_id = "${azurerm_key_vault.example.id}"
key_type = "RSA"
key_size = 2048
key_opts = [
"decrypt",
"encrypt",
"sign",
"unwrapKey",
"verify",
"wrapKey",
]
}
resource "azurerm_disk_encryption_set" "example" {
name = "example-set"
resource_group_name = "${azurerm_resource_group.example.name}"
location = "${azurerm_resource_group.example.location}"
key_vault_key_id = "${azurerm_key_vault_key.example.id}"
identity {
type = "SystemAssigned"
}
}
resource "azurerm_key_vault_access_policy" "disk-encryption" {
key_vault_id = "${azurerm_key_vault.example.id}"
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azurerm_client_config.current.object_id
key_permissions = [
"create",
"get",
"list",
"wrapkey",
"unwrapkey",
]
secret_permissions = [
"get",
"list",
]
}
resource "azurerm_role_assignment" "disk-encryption-read-keyvault" {
scope = "${azurerm_key_vault.example.id}"
role_definition_name = "Reader"
principal_id = "${azurerm_disk_encryption_set.example.identity.0.principal_id}"
}
This is the error I'm getting:
Error: Error creating Linux Virtual Machine "example-vm" (Resource
Group "Encrypt-resources"):
compute.VirtualMachinesClient#CreateOrUpdate: Failure sending request:
StatusCode=400 -- Original Error: Code="KeyVaultAccessForbidden"
Message="Unable to access key vault resource
'https://tf-keyvault-example.vault.azure.net/keys/TF-key-example/*****'
to enable encryption at rest. Please grant get, wrap and unwrap key
permissions to disk encryption set 'example-set'. Please visit
https://aka.ms/keyvaultaccessssecmk for more information."
Where and how should I add the permissions?
As the error print - Please grant get, wrap and unwrap key permissions to disk encryption set 'example-set'.
Add the following block:
# grant the Managed Identity of the Disk Encryption Set access to Read Data from Key Vault
resource "azurerm_key_vault_access_policy" "disk-encryption" {
key_vault_id = azurerm_key_vault.example.id
key_permissions = [
"get",
"wrapkey",
"unwrapkey",
]
tenant_id = azurerm_disk_encryption_set.example.identity.0.tenant_id
object_id = azurerm_disk_encryption_set.example.identity.0.principal_id
}
# grant the Managed Identity of the Disk Encryption Set "Reader" access to the Key Vault
resource "azurerm_role_assignment" "disk-encryption-read-keyvault" {
scope = azurerm_key_vault.example.id
role_definition_name = "Reader"
principal_id = azurerm_disk_encryption_set.example.identity.0.principal_id
}
More about azurerm_key_vault_access_policy and azurerm_role_assignment.
Update-
The issue was related to not specifying the correct object_id.
Later on, The Machine that builds the Terraform missed the SSH file path(e.g -"~/.ssh/id_rsa.pub") .
Fixed by running this command:
ssh-keygen -t rsa -b 4096 -C "your_email#example.com"
After that, the key vault permission was missing access policy to terraform user.
Besides all that, the sequence of the resources was mixed. fixed that to a more logical sequence.
The full and working code can be found here.
As Amit Baranes pointed out, you need to set the access policy for your encryption set.
In your above example you grant your data source client ID access to the key vault by way of access policy. The identity of your encryption set however only gets read to the vault by way of role.
Tucked away here the AzureRM VM resource documentation states:
NOTE: The Disk Encryption Set must have the Reader Role Assignment
scoped on the Key Vault - in addition to an Access Policy to the Key
Vault
You need to make sure you grant the encryption ID both the read role and an access policy.
A possible resulting full block looks like this, where we give your service principal and the identity access to the vault by way of an access policy. We also retain the read role
resource "azurerm_key_vault_key" "example" {
name = "TF-key-example"
key_vault_id = "${azurerm_key_vault.example.id}"
key_type = "RSA"
key_size = 2048
key_opts = [
"decrypt",
"encrypt",
"sign",
"unwrapKey",
"verify",
"wrapKey",
]
}
resource "azurerm_disk_encryption_set" "example" {
name = "example-set"
resource_group_name = "${azurerm_resource_group.example.name}"
location = "${azurerm_resource_group.example.location}"
key_vault_key_id = "${azurerm_key_vault_key.example.id}"
identity {
type = "SystemAssigned"
}
}
resource "azurerm_key_vault_access_policy" "service-principal" {
key_vault_id = "${azurerm_key_vault.example.id}"
tenant_id = data.azurerm_client_config.current.tenant_id
object_id = data.azurerm_client_config.current.object_id
key_permissions = [
"create",
"get",
"list",
"wrapkey",
"unwrapkey",
]
secret_permissions = [
"get",
"list",
]
}
resource "azurerm_key_vault_access_policy" "encryption-set" {
key_vault_id = "${azurerm_key_vault.example.id}"
tenant_id = azurerm_disk_encryption_set.example.identity.0.tenant_id
object_id = azurerm_disk_encryption_set.example.identity.0.principal_id
key_permissions = [
"create",
"get",
"list",
"wrapkey",
"unwrapkey",
]
secret_permissions = [
"get",
"list",
]
}
resource "azurerm_role_assignment" "disk-encryption-read-keyvault" {
scope = "${azurerm_key_vault.example.id}"
role_definition_name = "Reader"
principal_id = "${azurerm_disk_encryption_set.example.identity.0.principal_id}"
}
You would probably want to reduce the access for the service principal, however i left it as is for now.
I just noticed Reader role is not fit anymore, you now need to use Key Vault Crypto Service Encryption User.
resource "azurerm_role_assignment" "disk-encryption-read-keyvault" {
scope = "${azurerm_key_vault.example.id}"
role_definition_name = "Key Vault Crypto Service Encryption User"
principal_id = ${azurerm_disk_encryption_set.example.identity.0.principal_id}"
}

Resources