############################# UPDATE 1/16/2025 ####################################################
UPDATE: If your Terraform version is >= 1.10, you may encounter errors when implementing this solution.
Terraform 1.10 introduces the ephemeral concept, making it more efficient and clearer what can change between a plan and an apply. At the end of this article, you will find the updates related to this change.
UPDATE: if your powershell version is >=12.
Microsoft introduced a breaking change in the Get-AzAccessToken PowerShell cmdlet. The token is now managed as a SecureString (object) rather than a String (primitive type).
########################################################################################
Intro
Managing an infrastructure with IaC can be very convenient.
IaC can enhance your productivity through automation, reduce manual errors, eliminate configuration drift and have many more benefits.
In some cases, it can be hard to automate certain tasks, and we prefer to make a mnemonic effort rather than automating every single step.
A good example can be: run a query with terraform.
Yes, it’s possible to run a query in terraform and in some scenarios it’s not only a devops duty but it’s required!
If your security requirements mandate integrating managed identities on your Azure resources with a SQL Server, achieving this with Terraform can be challenging due to limitations reported in the Microsoft’s documentation https://learn.microsoft.com/en-us/sql/relational-databases/security/authentication-access/azure-ad-authentication-sql-server-overview?view=sql-server-ver16#azure-active-directory-managed-identity .
In this tutorial we will use the following technologies:
- Terraform
- Azure DevOps Pipelines
- Powershell
Some context: Our target is to allow a resource (an azure function app) to query our sql server database in a complex security scenario, in which the authentication between our client and the database is only allowed via managed identity.
Prerequisites:
- For this tutorial, I already created the “sql-admin” Entra ID Group: this group contains who I want to be the Sql Server Administrator. You must add your Service Connection’s Service Principal ID to this group, to enable launching a CREATE USER/LOGIN queries from your Azure DevOps pipelines. In Short: if your sqlServer is setted with the Ms Entra Administrator , only an Admin can add users to dbs then this step it’s required in this article. After the terraform apply you’ll see the Entra group in your sql server in portal configurations like the below image.
- I also created the “sql-reader” Group, with Directory Reader role. You should add to this group all the Azure SQL Server resources that need to use the external Entra ID identity provider. (https://learn.microsoft.com/en-us/azure/azure-sql/database/authentication-aad-directory-readers-role?view=azuresql#assigning-the-directory-readers-role ). In short: A “FROM EXTERNAL PROVIDER” query indicates to SQL Server it must search the user’s identity in the Microsoft Entra directories. But your Sql Server need reader privilege on Entra Directory.
Let’s start coding!
We are going to use Terraform to provision a function app with system assigned managed identity:
| |
Now, let’s provision SQL Server and a SQL Database
| |
At this point, we will try to assign a role to our function app to the Sql Server… but without success.
| |
That’s it! Unfortunately, assigning the role to our Function App towards a SQL Server is not enough to allow the Function App to be able to authenticate to our SQL Server. See MSFT’s documentation for more information: https://learn.microsoft.com/en-us/azure/azure-sql/database/authentication-azure-ad-logins-tutorial?view=azuresql#create-microsoft-entra-login .
The right way to achieve this is to launch a query in our database as follows:
CREATE LOGIN [myfunctionapp] FROM EXTERNAL PROVIDER;`
ALTER ROLE db_datareader ADD MEMBER [myfunctionapp];`
ALTER ROLE db_datawriter ADD MEMBER [myfunctionapp];`
It’s annoying to manually launch this query every time we need to allow managed identity authentication towards a SQL Server.
Let’s automate this with Terraform and Azure DevOps Pipelines!
Create a task like the following one on your DevOps Pipeline:
- task: AzurePowerShell@5
displayName: Get Access Token
inputs:
azureSubscription: $(SERVICE_CONNECTION_NAME)
ScriptType: 'InlineScript'
azurePowerShellVersion: 'LatestVersion'
preferredAzurePowerShellVersion: '3.1.0'
Inline: |
$VerbosePreference = 'SilentlyContinue'
$DebugPreference = 'SilentlyContinue'
$ErrorActionPreference = 'Stop'
$requiredModules = 'Az'
foreach ($module in $requiredModules) {
if (-not (Get-Module -ListAvailable -Name $module -ErrorAction Stop)) {
Install-Module -Name $module -Repository PSGallery -Force -AllowClobber -ErrorAction Stop
}
else
{
Write-Output "Module $module already installed..."
}
Import-Module $module -ErrorAction Stop
$modulePath = (Get-Module -Name $module -ErrorAction Stop).ModuleBase
$env:PSModulePath = $env:PSModulePath + ":$modulePath"
}
$access_token = (Get-AzAccessToken -ResourceUrl https://database.windows.net -ErrorAction Stop).Token
Write-Host "##vso[task.setvariable variable=TF_VAR_ACCESS_TOKEN]$access_token"
This script allows you to get the Access token with SQL Database scope using our Service Connection’s Principal Id. The access token will be saved in a TF_VAR_ACCESS_TOKEN pipeline variable.
Pass the value to the terraform apply DevOps pipeline task like a TF_VAR environment variable:
- task: TerraformTaskV3@3
displayName: Terraform APPLY
inputs:
provider: 'azurerm'
command: 'apply'
workingDirectory: $(working_dir)
commandOptions: "planfile"
environmentServiceNameAzureRM: $(SERVICE_CONNECTION_NAME)
env:
TF_VAR_ACCESS_TOKEN: $(TF_VAR_ACCESS_TOKEN)
On your terraform code, you must expose the ACCESS_TOKEN variables and will automatically filled at runtime when you run your pipeline with the TF_VAR_ACCESS_TOKEN value.
variable "ACCESS_TOKEN" {
type = string
}
Now we can create a reusable Terraform module (run_sql_query) to run sql queries, and a powershell script.
*terraform\run_sql_query\powershell_templates\ sqlcmd.ps1: *
param([String]$AccessToken = "AccessToken")
try{
$requiredModules = 'Az.Accounts', 'SqlServer'
foreach ($module in $requiredModules) {
if (-not (Get-Module -ListAvailable -Name $module)) {
Write-Output "Installing module $module ..."
Install-Module -Name $module -Force -AllowClobber
Write-Output "Module $module installed correctly..."
}
else
{
Write-Output "Module $module already installed..."
}
Import-Module $module
$modulePath = (Get-Module -Name $module).ModuleBase
$env:PSModulePath = $env:PSModulePath + ":$modulePath"
}
$serverName = '${serverName}'
$databaseName = '${databaseName}'
$query = '${query}'
Write-Host "${serverName} - ${databaseName}: Executing '${query}'"
Invoke-Sqlcmd -ServerInstance "${serverName}.database.windows.net" -Database $databaseName -AccessToken $Access_token -Query $query -IncludeSqlUserErrors
exit 0
}
catch {
Write-Error $_
exit 1
}
Yeah! Terraform can’t launch queries but PowerShell can do it with the Invoke-Sqlcmd cmdlet.
The trick is to add a PowerShell script to your Terraform code and run it using a local-exec provider!
terraform\run_sql_query\ main.tf
| |
terraform\run_sql_query\ variables.tf
| |
Now invoke your module from your terraform main.tf file.
terraform\main.tf
| |
The code I used in the article can be found here: https://github.com/pieroci/devopsncode/tree/main/azure_run_sql_query_man_identity
This code could be improved, and has some Open Points and limitations due to the use of Terraform local_file resources, which have some quirks.
Notably, local_file resources produce noise in subsequent terraform runs, as described in the official local provider’s documentation here: https://registry.terraform.io/providers/hashicorp/local/latest/docs/resources/file
This brings a little chain problem:
On your next terraform pipeline run, for the problem i mentioned above , Terraform logs show you a message: Hey! This resource already exists ( Don’t worry , the terraform apply doesn’t fail as well!).
Another security improvement could be treating the “AccessToken” variable as a secret in Azure DevOps, and using the sensitive flag in Terraform to avoid it being output in your apply log (beware though, depending on your usage it may remain visible in your agent’s pipeline logs).
Maybe I’ll make these improvements and search for a new strategy in a future article…
#UPDATE WITH TERRAFORM >= 1.10#
With the introduction of the “ephemeral” concept in Terraform 1.10, there is a breaking change in this solution. Your ACCESS_TOKEN variable needs to be declared as ephemeral in your entire workflow:
| |
With the “ephemeral” setting, the token is not saved to the Terraform state, which is a security improvement for your solution.
#UPDATE WITH AZURE POWERSHELL >= 12
Microsoft introduced a breaking change in the Get-AzAccessToken function: the token is now returned as a SecureString instead of a regular string.
If your Azure PowerShell version is 12 or above, you will need to modify the PowerShell task in your YAML pipeline as follows:
Update your task in the DevOps pipeline as shown below.
What’s the difference? The secure string token will be “decrypted” and passed as an environment variable. Although this is not an ideal security practice, keep in mind that you cannot pass an object (in this case, the SecureString token) directly into the TF_VAR_ACCESS_TOKEN variable.
Also, remember you can set your pipeline variable with secret=true to prevent the token value from being exposed to anyone with access to the pipeline.
- task: AzurePowerShell@5
displayName: Get Access Token
inputs:
azureSubscription: ${{ parameters.serviceconnectionName }}
ScriptType: 'InlineScript'
azurePowerShellVersion: 'LatestVersion'
Inline: |
$VerbosePreference = 'SilentlyContinue'
$DebugPreference = 'SilentlyContinue'
$ErrorActionPreference = 'Stop'
$requiredModules = 'Az'
foreach ($module in $requiredModules) {
if (-not (Get-Module -ListAvailable -Name $module -ErrorAction Stop)) {
Install-Module -Name $module -Repository PSGallery -Force -AllowClobber -ErrorAction Stop
}
else
{
Write-Output "Module $module already installed..."
}
Import-Module $module -ErrorAction Stop
$modulePath = (Get-Module -Name $module -ErrorAction Stop).ModuleBase
$env:PSModulePath = $env:PSModulePath + ":$modulePath"
}
try {
$accessTokenSecureStringObj = ( Get-AzAccessToken -AsSecureString -ResourceUrl https://database.windows.net ).Token
$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($accessTokenSecureStringObj)
try{
$plaintextat = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr)
Write-Host "##vso[task.setvariable variable=TF_VAR_ACCESS_TOKEN;]$plaintextat"
} finally
{
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)
}
} catch {
Write-Host "Error while retrieving the access token: $_"
throw
}
Enjoy automation and use your laziness to better automate your solutions and avoid tedious tasks!
