Terraform stepping on the pit: Azure Provider configuration

Terraform stepping on the pit: Azure Provider configuration

I haven't used Terraform to manage the resources on Azure for a long time. I had time to review this week, but I found that when I used Azure Provider, there was another moth.

According to the instructions on Azure Provider in Terraform official documentation, first you have to configure Azure-related authentication information. In fact, just like you usually use Azure, if you want to use Azure, the first step is to open the Azure portal to log in, which is to log in to Azure with your username and password authentication, and then start to work. Now you want to use Terraform to operate Azure resources, then you have to tell Terraform how to log in to Azure so that it can do the work for you.

Then, let's take a look at how to configure Azure provider when using Terraform. Regarding the Azure authentication method, Terraform official, in fact, Microsoft should give four authentication methods, you can configure them in terraform, as shown in the figure below:

Terraform stepping on the pit: Azure Provider configuration

For more information, please go to:

https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs#authenticating-to-azure

The first way: Azure Provider: Authenticating using the Azure CLI

This is more straightforward, first you need to install Azure CLI, and then run:

PS C:\lab> az login

Then a webpage will pop up, just enter your username and password, and then you can use Terraform and Azure happily, and the relevant information about your login to Azure will be cached on your local computer. So this method is the easiest, and there is no need to mention your Azure certification information in the Terraform code, but if you change a computer and run your code again, it will not work. You must install Azure CLI first, and then execute az login command, and then follow the prompts to log in to Azure.

As for the second and third methods, I won’t introduce them here. This time I use the fourth method to step on the pit:

Authenticating using a Service Principal with a Client Secret

So here is a detailed description of this method.

There is a prerequisite for this method. You must first create a Service Principal on Azure. For detailed steps, please refer to this link:

https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/guides/service_principal_client_secret#creating-a-service-principal-in-the-azure-portal

After the Service Principal is created, according to the official website reference document, in the provider.tf file, you can configure the relevant information of the provider azurerm. The entire project file structure is as follows:

PS C:\lab\dev>tree
     ───dev
         │───main.tf
         │───provider.tf

The content format of provider.tf is as follows:

provider "azurerm" {  
# Whilst version is optional, we /strongly recommend/ using it to pin the version of the Provider being used  
    version         = "=2.4.0"
    subscription_id = "00000000-0000-0000-0000-000000000000"  
    client_id       = "00000000-0000-0000-0000-000000000000"  
    client_secret   = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  
    tenant_id       = "00000000-0000-0000-0000-000000000000"
    features {}
  }

Explain:

-subscription_id: your Azure subscription ID

-client_id: Application (client) ID after the Service Principal is created

-client_secret: After creating the Service Principal, create an application secret

-tenant_id: After the Service Principal is created, the Directory (tenant) ID of the application

The content of the main.tf file is as follows:

resource "azurerm_resource_group" "azure-tf-rg" {    
    name = "terraform-eval"    
    location = "chinaeast2"    
    tags = {      
        "env" = "dev"      
        "location" = "China East2"    
        }
}

Then terraform init walked up and the initialization was fine.

PS C:\lab\dev> terraform init

Initializing the backend...
Initializing provider plugins...
- Using previously-installed hashicorp/azurerm v2.40.0

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to seeany changes that are required for your infrastructure. All Terraform commandsshould now work.

If you ever set or change modules or backend configuration for Terraform,rerun this command to reinitialize your working directory. If you forget, othercommands will detect it and remind you to do so if necessary.

Then execute terraform plan

PS C:\lab\dev> terraform plan

Refreshing Terraform state in-memory prior to plan...

The refreshed state will be used to calculate this plan, but will not bepersisted to local or remote state storage.
------------------------------------------------------------------------
Error: Error building account: 
Error getting authenticated object ID: 
Error listing Service Principals: autorest.DetailedError{
Original:adal.tokenRefreshError{
message:"adal: Refresh request failed. 
Status Code = '400'. 
Response body: {
\"error\":\"invalid_request\",\"
error_description\":\"AADSTS90002: 
Tenant '00000000-0000-0000-0000-000000000000' not found. 
This may happen if there are no active subscriptions for the tenant. Check to make sure you have the correct tenant ID. Check with your subscription administrator.\\r\\n
Trace ID: xxxx-1fxxx95-xxx6-xxx4-xxxxxx00\\r\\n
Correlation ID: xxxxxxx-xxx-xxxxx\\r\\n
Timestamp: 2020-12-11 07:02:40Z\",\"
error_codes\":[90002],\"
timestamp\":\"2020-12-11 07:02:40Z\",\"
trace_id\":\"xxxx-1fxxx95-xxx6-xxx4-xxxxxx00\",\"
correlation_id\":\"xxxx-1fxxx95-xxx6-xxx4xxxxxx00\",\"
error_uri\":\"https://login.microsoftonline.com/error?code=90002\"}", 
resp:(*http.Response)(0xc0011c4b40)},  PackageType:"azure.BearerAuthorizer",  Method:"WithAuthorization",  StatusCode:400,  Message:"Failed to refresh the Token for request to  https://graph.windows.net/xxxx/servicePrincipals?%24filter=appId+eq+%xxxxxx00&api-version=1.6",  ServiceError:[]uint8(nil),  Response:(*http.Response)(0xc0011c4b40)}

  on provider.tf line 1, in provider "azurerm":   
  1: provider "azurerm" {

No, it's red, there is a problem with the authentication, and it says that the tenant id cannot be found. This is all copied, and it is impossible to go wrong.

Then look down: error_uri\":\" https://login.microsoftonline.com

Well, that's it. I created the Service Principal on the Azure China version. When terraform logged in, I used the URI of the Azure overseas version. That's the problem.

Go back and see the introduction of Azurerm Provider on Terraform's official website:

Terraform stepping on the pit: Azure Provider configuration

Now I understand. Although environment is optional, public is used by default, which is the overseas version of Azure. The source of the problem has been found, let's change the terraform code! Add the environment parameter and set the value to china. The final code is as follows:

provider "azurerm" {  
# Whilst version is optional, we /strongly recommend/ using it to pin the version of the Provider being used  
    version         = "=2.4.0"
    environment     = "china"
    subscription_id = "00000000-0000-0000-0000-000000000000"  
    client_id       = "00000000-0000-0000-0000-000000000000"  
    client_secret   = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  
    tenant_id       = "00000000-0000-0000-0000-000000000000"
    features {}
  } 

One more terraform plan

PS C:\lab\dev> terraform plan

Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
------------------------------------------------------------------------
An execution plan has been generated and is shown below.Resource actions are indicated with the following symbols:  
+ create
Terraform will perform the following actions:  
# azurerm_resource_group.azure-tf-rg will be created  
+ resource "azurerm_resource_group" "azure-tf-rg" {      
    + id       = (known after apply)      
    + location = "chinaeast2"      
    + name     = "terraform-eval"      
    + tags     = {          
    + "env"      = "dev"          
    + "location" = "China East2"        
    }    
}
Plan: 1 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraformcan't guarantee that exactly these actions will be performed if"terraform apply" is subsequently run.

Well, no error was reported, the prompt will add a new resource, and then a terraform apply

PS C:\lab\dev> terraform apply

An execution plan has been generated and is shown below.Resource actions are indicated with the following symbols:  
+ create
Terraform will perform the following actions:  
# azurerm_resource_group.azure-tf-rg will be created  
+ resource "azurerm_resource_group" "azure-tf-rg" {      
    + id       = (known after apply)      
    + location = "chinaeast2"      
    + name     = "terraform-eval"      
    + tags     = {          
    + "env"      = "dev"          
    + "location" = "China East2"        
    }    
}

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?  Terraform will perform the actions described above.  Only 'yes' will be accepted to approve.  

Enter a value: yes

azurerm_resource_group.azure-tf-rg: Creating...
azurerm_resource_group.azure-tf-rg: Creation complete after 5s [id=/subscriptions/0000000-0000-0000-0000-0000000000/resourceGroups/terraform-eval]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Log in to your Azure China portal, go to the resource group to see, the resource group terraform-eval was successfully created. Get it done!

In fact, this pit can only be stepped on when you use the Azure China Edition/US Government Edition/German Edition, and you don’t have to worry about this problem when using Azure Overseas Edition. Well, this time I’m going to write down the pit record, I hope it can help everyone. Another point is that when reading related technical documents, you need to be careful to prevent mining pits.

Guess you like

Origin blog.51cto.com/mageedu/2586941