As a part of my Terraform I’m attempting to execute following flow:
- Create Azure Key Vault with RBAC Security enabled (enable_rbac_authorization = true)
- Grant Service Principal that is running the script “Key Vault Administrator” or any other Key Vault RBAC related role that let’s it write secrets to Key Vault on KV created in step 1
- Create a resource that includes generating a random password (ex. password for Virtual Machine admin account)
- Write that random password to secret created in step 1.
Code looks as follows:
data "azurerm_client_config" "current" {}
resource "azurerm_key_vault" "kv" {
name = var.name
location = var.location
resource_group_name = var.resource_group_name
sku_name = var.sku_name
enabled_for_disk_encryption = true
enabled_for_template_deployment = true
tenant_id = data.azurerm_client_config.current.tenant_id
soft_delete_retention_days = var.soft_delete_retention_days
purge_protection_enabled = true
enable_rbac_authorization = var.enable_rbac_authorization
public_network_access_enabled = var.public_network_access_enabled
tags = merge({ StartDate = formatdate("DD-MM-YYYY", time_static.time.rfc3339) }, var.env_tags)
lifecycle {
ignore_changes = [tags]
}
}
resource "azurerm_role_assignment" "kv_admin" {
count = var.vars_dataintelligence.dwh-keyvault.enable_rbac_authorization ? 1 : 0
scope = module.kv-dataintelligence.id
role_definition_name = "Key Vault Administrator"
principal_id = data.azurerm_client_config.current.object_id
}
... long code that creates VM here ....
resource "azurerm_key_vault_secret" "admin_password_secret" {
name = format("%s-%s", azurerm_windows_virtual_machine.name, "admin-pswd")
key_vault_id = azurerm_key_vault.id
value = azurerm_windows_virtual_machine.admin_password
depends_on = [azurerm_role_assignment.kv_admin]
}
Unfortunately, due to how Azure credentials work, I’m getting an error that Service Principal doesn’t have an access to said Key Vault to be able to add that credential and “if access was recently granted refresh your credentials”.
If I re-run the flow secrets get added correctly (since Service Principal now refreshes its credentials), but that’s not a perfect state since on execution 1 I will always get error.
One workaround that comes to mind is preemptively granting Service Principal needed access on a higher scope (Resource Group/Subscription) prior to running TF, but that also doesn’t sound like ideal scenario, but slowly starting to think that this might be the only play I have.
Alternatively, could try to implement logic of single restart in case pipeline that runs the script fails on first time (GitHub Actions in our case).
Any suggestions/help as always appreciated