编程知识 cdmana.com

Terraform: azure provider configuration

Long time no use Terraform management Azure The resources on the top , I have time to review this week , But I found that I was using Azure Provider There was another moth when I was young .

according to Terraform Official documents about Azure Provider Instructions for use , First of all, you have to configure Azure Related certification information . In fact, it's just like you usually use it Azure equally , You want to use Azure, The first step is that you have to open Azure portal Log in , Is to use your user name and password authentication login to Azure Up , And start working . Now you're going to use Terraform To operate Azure resources , Then you have to tell me Terraform How can I log in to Azure, It can work for you .

then , Let's take a look at the use of Terraform When , How to configure Azure provider. About Azure authentication ,Terraform official , In fact, Microsoft should have given four authentication methods , You can terraform Middle configuration , See the picture below :

Terraform Stepping on the pit :Azure Provider To configure Long time no use Terraform management Azure The resources on the top , I have time to review this week , But I found that I was using Azure Provider There was another moth when I was young .

according to Terraform Official documents about Azure Provider Instructions for use , First of all, you have to configure Azure Related certification information . In fact, it's just like you usually use it Azure equally , You want to use Azure, The first step is that you have to open Azure portal Log in , Is to use your user name and password authentication login to Azure Up , And start working . Now you're going to use Terraform To operate Azure resources , Then you have to tell me Terraform How can I log in to Azure, It can work for you .

then , Let's take a look at the use of Terraform When , How to configure Azure provider. About Azure authentication ,Terraform official , In fact, Microsoft should have given four authentication methods , You can terraform Middle configuration , See the picture below :  Insert picture description here

Details , Please move :

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 direct , First you need to install Azure CLI, And then run :

PS C:\lab> az login

And then a web page will pop up , Enter your user name and password , Then you can use it happily Terraform and Azure 了 , Your login Azure The relevant information and cache to your local computer . So this is the easiest way , And not in Terraform Your... Is mentioned in your code Azure Authentication information , But you change a computer , Run your code again , It won't work , You have to install Azure CLI, Re execution az login command , Then follow the prompts to log in Azure.

As for the second and third methods, I won't introduce them here , The fourth way is to step on the pit this time :

Authenticating using a Service Principal with a Client Secret

So here's a detailed description of this approach .

There's a premise to this approach , You have to be there first Azure Create above Service Principal, Please refer to this link for detailed steps :

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

Service Principal Once you've created it , According to the official website reference document , stay provider.tf In the document , You can configure provider azurerm The information about , The whole project document structure is as follows :

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

provider.tf The file format 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: Yours Azure subscribe ID

  • client_id: establish Service Principal After Application (client) ID

  • client_secret: establish Service Principal after , establish application secret

  • tenant_id: establish Service Principal after ,application Of Directory (tenant) ID

main.tf The contents of the document are as follows :

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

And then terraform init Walk up , Initialization is OK .

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 perform 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" {

Not good. , It's red , There's something wrong with the certification , say Tenant id Can't find , This is all copy Of , There can be no mistake .

So let's look down :error_uri":"https://login.microsoftonline.com

Um. , This is it , I was in Azure Created on the Chinese version Service Principal,terraform When I log in, I use Azure Overseas version of URI, That's the problem .

Go back and see Terraform Official website Azurerm Provider Introduction to :

 Insert picture description here

Now I understand ,environment Although it is optional Of , But the default is public, That is to say Azure The overseas edition of . The root cause of the problem has been found , Change terraform Code it ! add to environment Parameters , Value to china that will do . 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.

Um. , No mistake , The hint will be add 1 A new resource, And then one 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 resource group Look at the ,terraform-eval This resource group Successfully created . Get it done !

Actually , Only you use this pit Azure China Version / US government Edition / It's the German version , Use Azure The overseas version doesn't have to worry about this . Okay , Here's the record of stepping on the pit , I hope I can help you . Another point is when reading the relevant technical documents , You need to be more careful , In order to prevent mining pit .

Details , Please move :

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 direct , First you need to install Azure CLI, And then run :

PS C:\lab> az login

And then a web page will pop up , Enter your user name and password , Then you can use it happily Terraform and Azure 了 , Your login Azure The relevant information and cache to your local computer . So this is the easiest way , And not in Terraform Your... Is mentioned in your code Azure Authentication information , But you change a computer , Run your code again , It won't work , You have to install Azure CLI, Re execution az login command , Then follow the prompts to log in Azure.

As for the second and third methods, I won't introduce them here , The fourth way is to step on the pit this time :

Authenticating using a Service Principal with a Client Secret

So here's a detailed description of this approach .

There's a premise to this approach , You have to be there first Azure Create above Service Principal, Please refer to this link for detailed steps :

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

Service Principal Once you've created it , According to the official website reference document , stay provider.tf In the document , You can configure provider azurerm The information about , The whole project document structure is as follows :

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

provider.tf The file format 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: Yours Azure subscribe ID

  • client_id: establish Service Principal After Application (client) ID

  • client_secret: establish Service Principal after , establish application secret

  • tenant_id: establish Service Principal after ,application Of Directory (tenant) ID

main.tf The contents of the document are as follows :

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

And then terraform init Walk up , Initialization is OK .

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 perform 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" {

Not good. , It's red , There's something wrong with the certification , say Tenant id Can't find , This is all copy Of , There can be no mistake .

So let's look down :error_uri":"https://login.microsoftonline.com

Um. , This is it , I was in Azure Created on the Chinese version Service Principal,terraform When I log in, I use Azure Overseas version of URI, That's the problem .

Go back and see Terraform Official website Azurerm Provider Introduction to :

Now I understand ,environment Although it is optional Of , But the default is public, That is to say Azure The overseas edition of . The root cause of the problem has been found , Change terraform Code it ! add to environment Parameters , Value to china that will do . 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.

Um. , No mistake , The hint will be add 1 A new resource, And then one 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 resource group Look at the ,terraform-eval This resource group Successfully created . Get it done !

Actually , Only you use this pit Azure China Version / US government Edition / It's the German version , Use Azure The overseas version doesn't have to worry about this . Okay , Here's the record of stepping on the pit , I hope I can help you . Another point is when reading the relevant technical documents , You need to be more careful , In order to prevent mining pit .

※ Part of the article comes from the Internet , If there is infringement, please contact to delete ; More articles and materials | Click on the text directly after ↓↓↓ A collection of free resources 100GPython Self study Kit Alibaba cloud K8s Actual combat manual [ Alibaba cloud CDN Pit guide ]CDN ECS Operation and maintenance guide DevOps Practice Manual Hadoop Big data combat manual Knative Cloud native application development guide OSS Operation and maintenance manual White paper on cloud native architecture Zabbix Enterprise level distributed monitoring system source document Nginx Detailed explanation , Ten minutes before going to bed ! Nginx Module development and Architecture comprehensive depth analysis

版权声明
本文为[Programmer interview]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225142030510M.html

Scroll to Top