Whenever I run terraform plan
command I have to put client id, secret id, tenant id and subscription id manually.
Here is my setup
I have set env variables in my .zprofile
export ARM_SUBSCRIPTION_ID=*********
export ARM_CLIENT_ID=*********
export ARM_CLIENT_SECRET=*********
export ARM_TENANT_ID=*********
if I want to see them echo $ARM_SUBSCRIPTION_ID it does print out its value
In my providers.tf file this is the code
# Configuration options
provider "azurerm" {
subscription_id = var.SUBSCRIPTION_ID
client_id = var.CLIENT_ID
client_secret = var.CLIENT_SECRET
tenant_id = var.TENANT_ID
features {
}
}
And in my variables.tf file the code looks like this
variable "SUBSCRIPTION_ID" {
}
variable "CLIENT_ID" {
}
variable "CLIENT_SECRET" {
}
variable "TENANT_ID" {
}
so when I run terraform plan
commands the terminal prompts me to put all ids manually.
2
Answers
So finally I have found the solution.
If you have multiple subscriptions of Azure (you are working for multiple clients) then the first thing is that you need to check which is your current subscription. Run this command to check all subscriptions
and run this command to change switch your subscription
and now you can run any Azure cli command and changes will be reflected on your current subscription
Authenticating to azure by service principal and client secret using terraform:
I tried to authenticate with
AzureAD service principal
in my environment after finding a workaround and was able to perform it successfully.I’ve setup env variables in
azCLI
as shown here:To authenticate service principal, we need to give some role permissions and API Permissions as well.
Required Permissions to enable:
Goto
Roles and Administrators
underAzure Active Directory
through portal. There are certain administrator positions that come with default configuration. Actively enable the roles of "Application Administrator, Global Administrator, and User Administrator".and
Goto
API permissions
under registeredApp registration
and add application permissions for microsoft graph as its the main source to authenticate to Portal and enable below given permissions by clicking onAdd permission
.App registration:
To check, I created a resource group and applying a dev tag for it after successful authentication.
Provider.tf
Executed
terraform init
:After setting up everything, I executed
terraform plan
, it is asking forclient_secret
only notclient_id
:Executed
Terraform apply
:Authenticated & deployed successfully in Portal:
Applied tags successfully for resourcegroup as given: