Continuing on my journey to learn Terraform, I wanted to explore the idea of authenticating Terraform to Azure. Terraform, as we know, is an infrastructure automation tool, and this authentication technique allows us to create/manage resources on the Azure cloud platform. I came across two insightful articles on Azure Service Principals that helped me understand the how’s and what’s of the service principal. Here are the links to those –Ned Belavance’s Demystifying Azure AD Service Principals and Microsoft Docs
Following the instructions there, I identified three steps to the objective.
Step 1: Create a Service Principal
Here is code of the service principal provisioning command I ran on Azure portal command prompt:az ad sp create-for-rbac --name $(app-name) --role "Contributor" --scope "/subscriptions/$(your-subscription-id)" --years $(N)
Output received:
{
"appId": "$(appId)",
"displayName": "$(app-name)",
"name": "http://$(app-name)",
"password": "$(password)",
"tenant": "$(tenant)"
}
With these values in hand, it was now time to head over to Terraform and provide those credentials for Terraform to be able to access my Azure subscription.
Step 2: Update terraform configuration files
I followed the instructions here to create the Azure provider usage and authentication.
The documentation was precise on what values were required. I also know that these are secured credentials and that they need to be managed carefully. I came across an approach to declare variables in a variables.tf file and place actual values in a .tfvars file. This .tfvars file should not be added to the repository (update .gitignore accordingly).
Step 3: Execute terraform trio commands (init -> plan -> apply)
At the end of terraform apply
I was able to verify that a resource group was created under my subscription on the Azure portal.

Conclusion:
The purpose of this note was to authenticate Terraform, and we saw that with the creation of a resource group in Azure.
Other ideas to explore:
Is this the best method to be able to authenticate Terraform?
How to authenticate Terraform to AWS using an IAM user?
One thought on “Authenticating Terraform to Azure using Service Principal”