How to Run PowerShell Commands Using Terraform Configuration

How to Run PowerShell Commands Using Terraform Configuration header image

Have you ever wanted to automate the process of running PowerShell scripts from your Terraform configuration? If so, then this blog post is for you! In this post, we’ll show you how to use Terraform to run PowerShell commands to manage your infrastructure. We’ll walk you through the steps you need to take to set up your environment, and then how to use Terraform to run PowerShell scripts. When venturing in to the world of Terraform I figured this shouldn’t be to hard ofa task. but I ended up spending a bit more time then expected. So if you are looking for a way to quickly and efficiently manage and configure your Azure environment? And Terraform is not providing everything you need, then you have come to the right place. In this blog post, we will show you how to use Terraform to run PowerShell commands in your Azure environment.

Overview of Terraform and PowerShell integration

Terraform is a popular infrastructure as code tool used to provision, configure, and manage infrastructure resources in various cloud platforms. On the other hand, PowerShell is a powerful automation framework from Microsoft, mainly used for managing Windows-based environments. With the integration of Terraform and PowerShell, users can easily manage their infrastructure resources on various cloud platforms and automate their Windows-based environments. Our main goal was to have everything we build deployed as code (infrastructure as code). Yet when we started working with Azure Data Factory we found that to give permissions to the Data Factory on a SQL database (as a managed identity in our case) it was a scenario that was not supported by Terraform. So we figured the quickest way was run PowerShell or CLI commands from Terraform.

Prerequisites for running PowerShell scripts in Terraform

Before you can start running PowerShell scripts from your Terraform templates, there are a few prerequisites that you need to take care of. First, you’ll need to have the appropriate permissions. In our scenario we ran the Terraform from an Azure DevOps pipeline and thus had to make sure our pipeline managed identity had the correct permissions. This will depend on the scenario you are looking for. In our scenario we needed to add the following permissions to the service principal, Directory Readers for the Managed Identity of the SQL Server to execute and add additional users to the SQL Server. And since ware running from a pipeline we will need to make sure the modules required in our script are installed, this can be a slow process so the less modules the better.

Adding a provider block for PowerShell in Terraform

To be able to use PowerShell scripts in Terraform configuration, you need to add a provider block for PowerShell. You can do this using the null_resource. Using the triggers combined with the sha256 function you can make sure that the script gets executed every time you change the contents of the script. The whole provider block looks something like this:

resource "null_resource" "run_permission_script" {
  triggers = {
     script_hash = sha256("./scripts/Set-DbPermissionsReporting.ps1")
  }

  provisioner "local-exec" {
    command = "./scripts/Set-DbPermissionsReporting.ps1 -SomeParameter ${var.settings.someparameter}"
    interpreter = ["pwsh", "-Command"]
  }
}

Running a PowerShell script from Terraform configuration

Once you have added the provider block for PowerShell in Terraform, you can create your PowerShell script file. This can be done using any text editor such as Notepad, Visual Studio Code or PowerShell ISE, as long as the location matches the provider called file. In the script it self you can easily authenticate using the global environment variables that are available from the context of the Azure DevOps pipeline. The script will look something like this:

  $tenantId = $env:ARM_TENANT_ID;
  $clientId = $env:ARM_CLIENT_ID;
  $secret = $env:ARM_CLIENT_SECRET;

  Write-Host 'Interactive signing in to Azure due to MFA requirements'\

  az login --service-principal --username $clientId --password $secret --tenant $tenantId --output none

This ensures that you have a valid Access Token. Next up in our case we wanted to run a SQL command so we install the SqlServer module and get an access token to execute SQL commands. With that module and token you can build a SqlConnection and execute any command you like.

  Install-Module -Name "SqlServer" -Repository PSGallery -Force -AllowClobber -Scope CurrentUser -ErrorAction Stop

   $dexResourceUrl = 'https://database.windows.net/'
  $token = az account get-access-token --resource $dexResourceUrl | ConvertFrom-Json

  $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
  Write-Host "Execute SQL command against database $SqlDatabaseName on resource group $resourceGroupName"
  $sqlConnection.ConnectionString = CreateSqlAzureConnectionString -SqlDatabaseName $SqlDatabaseName -StageName $StageName
  Write-Host $sqlConnection.ConnectionString
  $sqlConnection.AccessToken = $token
  $sqlConnection.Open()

Conclusion

Terraform is a great way to deploy the whole infrastructure over multiple environments. However there are edge cases where things are not supported yet. If you want to make sure your managed identities created by Terraform have the correct permissions PowerShell scripts can provide an easy way to add the correct permissions. In this blog post, we showed you how to use Terraform to run PowerShell commands in your Azure environment. We hope this post has been helpful for you! If you have any questions or comments, please leave them below.

Loading comments…