0
votes

I have a project that is running on Azure DevOps that requires creating a KeyVault and giving a series of managed AppService identities access to secrets in that vault.

Because of Terraform not being able to give its own service connection access to the key vault(this is a bug of some kind), I am forced to create ResourceGroup and Keyvault with SP access before Terraforming.

When running terraform import on resourcegroup and Keyvault through a PowerShell task:

terraform init
$state = terraform state list
if ($state -like '*azurerm_resource_group.instancerg*' -and '*azurerm_key_vault.instancekeyvault*') {
    Write-Host "Resources have already been imported!"
}
else {
    terraform import azurerm_resource_group.instancerg /subscriptions/$(subscriptionid)/resourceGroups/rgname
    terraform import azurerm_key_vault.instancekeyvault /subscriptions/$(subscriptionid)/resourceGroups/rgname/providers/Microsoft.KeyVault/vaults/keyvaultname
}

Failure happens on terraform import commands:

'Authenticate using a Service Principal' To authenticate to Azure using a Service Principal, you can use the separate auth method - instructions for which can be found here:'

My main.tf contains:

provider "azurerm" { 
  version = "=2.7.0"

  subscription_id = var.subscriptionid
  client_id       = var.devopsserviceconnectionaid
  client_secret   = var.devopsserviceconnectionpw
  tenant_id       = var.tennantid

  features {}
}

The variables are all linked to the proper credentials.

From what I understand Terraform should pick up on what authentication method that is being used based on the credentials that are in the block above or specific env variables (that are also present...) but somehow Terraform still thinks I'm trying to auth through Azure Cli and not Service principal.

1
Can you add your terraform steps from pipeline?Krzysztof Madej

1 Answers

0
votes

You can use manage identities in keyvault in terraform as shown below.

object_id = azurerm_app_service.app.identity.0.principal_id

enter image description here

Web app is as below creating managed identity

enter image description here

KV as below

enter image description here

The order should be create web app with managed identity, then the KV then the KV access policy.

For authenticate with Azure pipelines service connection below works fine but you need to pass the arguments via the pipeline. enter image description here

for further information check this blog here

Full PowerShell based implementation calling terraform with Azure DevOps pipelines is explained here. This implementation prevents any azure resources as prerequisite before terraforming. Only prerequisite is creating the SPN to enable authentication and authorization.