azureterraformazure-rm

Terraform - force refresh of credentials?


As a part of my Terraform I'm attempting to execute following flow:

  1. Create Azure Key Vault with RBAC Security enabled (enable_rbac_authorization = true)
  2. 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
  3. Create a resource that includes generating a random password (ex. password for Virtual Machine admin account)
  4. 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


Solution

  • Creating a VM using random password that was stored in keyvault in terraform.

    This requirement doesn't force to run the deployment command twice as it occurs due to permission issue of the user or SP to assign the role in the first place.

    I know the key vault administrator alone will create the privilege to the user or SP but the assigning that role you need user access administrator role. The role will provide the access to assign role across different scopes.

    My privileges to achieve this requirement in one go

    enter image description here

    The way you're referring the VM password to while creating the secret also needs to be modified.

    Configuration:

    variable "vm_admin_password" {
      description = "The admin password for the VM."
      type        = string
      sensitive   = true
    }
    data "azurerm_client_config" "current" {}
    
    resource "azurerm_resource_group" "rg" {
      name     = "testvk-resources"
      location = "East US"
    }
    
    resource "azurerm_key_vault" "kv" {
      name                            = "testtvskkv12345"
      location                        = azurerm_resource_group.rg.location
      resource_group_name             = azurerm_resource_group.rg.name
      sku_name                        = "standard"
      tenant_id                       = data.azurerm_client_config.current.tenant_id
      soft_delete_retention_days      = 7
      purge_protection_enabled        = true
      enable_rbac_authorization       = true
      public_network_access_enabled   = true
      enabled_for_disk_encryption     = true
      enabled_for_template_deployment = true
     
      
    }
    
    resource "azurerm_role_assignment" "kv_admin" {
      scope                = azurerm_key_vault.kv.id
      role_definition_name = "Key Vault Administrator"
      principal_id         = data.azurerm_client_config.current.object_id
    }
    
    resource "azurerm_windows_virtual_machine" "vm" {
      name                  = "testvkvm"
      location              = azurerm_resource_group.rg.location
      resource_group_name   = azurerm_resource_group.rg.name
      network_interface_ids = [azurerm_network_interface.nic.id]
      size                  = "Standard_D2_v2"
    
      os_disk {
        caching              = "ReadWrite"
        storage_account_type = "Standard_LRS"
      }
    
      source_image_reference {
        publisher = "MicrosoftWindowsServer"
        offer     = "WindowsServer"
        sku       = "2016-Datacenter"
        version   = "latest"
      }
    
      computer_name  = "hostname"
      admin_username = "adminuser"
      admin_password = var.vm_admin_password
    
      depends_on = [ azurerm_role_assignment.kv_admin ]
    }
    
    resource "azurerm_network_interface" "nic" {
      name                = "testvk-nic"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
    
      ip_configuration {
        name                          = "internal"
        subnet_id                     = azurerm_subnet.subnet.id
        private_ip_address_allocation = "Dynamic"
      }
    }
    
    resource "azurerm_subnet" "subnet" {
      name                 = "subnet1"
      resource_group_name  = azurerm_resource_group.rg.name
      virtual_network_name = azurerm_virtual_network.vnet.name
      address_prefixes     = ["10.0.2.0/24"]
    }
    
    resource "azurerm_virtual_network" "vnet" {
      name                = "testvk-vnet"
      resource_group_name = azurerm_resource_group.rg.name
      location            = azurerm_resource_group.rg.location
      address_space       = ["10.0.0.0/16"]
    }
    
    resource "azurerm_key_vault_secret" "admin_password_secret" {
      name         = "admin-password"
      key_vault_id = azurerm_key_vault.kv.id
      value        = var.vm_admin_password
      depends_on   = [azurerm_role_assignment.kv_admin]
    }
    

    Deployement:

    enter image description here

    enter image description here

    Refer:

    azurerm_key_vault_secret | Resources | hashicorp/azurerm | Terraform | Terraform Registry

    azurerm_windows_virtual_machine | Resources | hashicorp/azurerm | Terraform | Terraform Registry