溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Terraform中Azure Provider配置的注意事項(xiàng)有哪些

發(fā)布時(shí)間:2021-12-07 14:44:41 來源:億速云 閱讀:173 作者:小新 欄目:云計(jì)算

這篇文章將為大家詳細(xì)講解有關(guān)Terraform中Azure Provider配置的注意事項(xiàng)有哪些,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

根據(jù)Terraform官方文檔關(guān)于Azure Provider的使用說明,首先你得先配置一下Azure相關(guān)的認(rèn)證信息。其實(shí)就跟你平時(shí)使用Azure一樣,你想使用Azure,那第一步就是你必須打開Azure portal進(jìn)行登錄,就是使用你的用戶名和密碼認(rèn)證登錄到Azure上去,然后開始干活?,F(xiàn)在你要用Terraform來操作Azure資源,那你得告訴Terraform怎么才能登錄到Azure,方便它替你干活。

那接下來,我們就一起看一下在使用Terraform的時(shí)候,怎么來配置Azure provider。關(guān)于Azure認(rèn)證方式,Terraform官方,其實(shí)應(yīng)該是微軟給出了四種認(rèn)證方式,你可以在terraform中配置,見下圖:

Terraform踩坑記之:Azure Provider配置 好久沒用Terraform管理Azure上面的資源了,這周有時(shí)間復(fù)習(xí)了一下,卻發(fā)現(xiàn)在使用Azure Provider的時(shí)候又出了幺蛾子。

根據(jù)Terraform官方文檔關(guān)于Azure Provider的使用說明,首先你得先配置一下Azure相關(guān)的認(rèn)證信息。其實(shí)就跟你平時(shí)使用Azure一樣,你想使用Azure,那第一步就是你必須打開Azure portal進(jìn)行登錄,就是使用你的用戶名和密碼認(rèn)證登錄到Azure上去,然后開始干活?,F(xiàn)在你要用Terraform來操作Azure資源,那你得告訴Terraform怎么才能登錄到Azure,方便它替你干活。

那接下來,我們就一起看一下在使用Terraform的時(shí)候,怎么來配置Azure provider。關(guān)于Azure認(rèn)證方式,Terraform官方,其實(shí)應(yīng)該是微軟給出了四種認(rèn)證方式,你可以在terraform中配置,見下圖: Terraform中Azure Provider配置的注意事項(xiàng)有哪些

詳細(xì)信息,請(qǐng)移步:

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

第一種方式:Azure Provider: Authenticating using the Azure CLI

這個(gè)比較直接,首先你需要安裝Azure CLI,然后運(yùn)行:

PS C:\lab> az login

然后會(huì)跳出來一個(gè)網(wǎng)頁,輸入你的用戶名密碼即可,然后你就可以愉快的使用Terraform和Azure了,你登錄Azure的相關(guān)信息以及緩存到你本地電腦上了。所以這種方式最簡單,也不用在Terraform的代碼里提及你的Azure認(rèn)證信息,但是你換一臺(tái)電腦,再跑一下你的代碼,是跑不通的,你必須先安裝Azure CLI,再執(zhí)行az login命令,然后跟著提示登錄Azure。

至于第二種和第三種方式這里先不介紹了,這次踩坑是用第四種方式:

Authenticating using a Service Principal with a Client Secret

所以這里詳細(xì)說明一下這一種方式。

這種方式有個(gè)前提,你必須先在Azure上面創(chuàng)建Service Principal,具體詳細(xì)步驟請(qǐng)參考這個(gè)鏈接:

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

Service Principal創(chuàng)建好之后,按照官網(wǎng)參考文檔,在provider.tf文件里,就可以配置provider azurerm的相關(guān)信息了,整個(gè)項(xiàng)目文件結(jié)構(gòu)如下:

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

provider.tf文件內(nèi)容格式如下:

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 {}
  }

說明一下:

  • subscription_id:你的Azure訂閱ID

  • client_id:創(chuàng)建Service Principal后的Application (client) ID

  • client_secret:創(chuàng)建Service Principal后,創(chuàng)建application secret

  • tenant_id:創(chuàng)建Service Principal后,application的Directory (tenant) ID

main.tf文件內(nèi)容如下:

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

隨后terraform init走起,初始化沒問題。

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.

接著執(zhí)行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" {

不好,飄紅了,認(rèn)證出問題了,說Tenant id找不到,這都是copy的,不可能出錯(cuò)。

接著往下看:error_uri":"https://login.microsoftonline.com

嗯,就是這里,我是在Azure中國版上面創(chuàng)建的Service Principal,terraform去登錄的時(shí)候用的是Azure海外版的URI,那問題就出在這里了。

再回去看看Terraform官網(wǎng)關(guān)于Azurerm Provider的介紹:

Terraform中Azure Provider配置的注意事項(xiàng)有哪些

這下明白了,environment雖然是optional的,但是默認(rèn)用的是public,也就是Azure海外版。問題根源找到了,改terraform代碼吧!添加environment參數(shù),值設(shè)為china即可。最終代碼如下:

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 {}
  }

再來一把 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.

嗯,沒報(bào)錯(cuò),提示會(huì)add 1個(gè)新resource,接著走一個(gè) 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.

登錄你的Azure中國portal,去resource group里看看,terraform-eval這個(gè)resource group被成功創(chuàng)建。搞定!

其實(shí),這個(gè)坑只有你使用Azure中國版/美國政府版/德國版的時(shí)候才會(huì)踩,使用Azure海外版就不用擔(dān)心這個(gè)問題。好了,此次踩坑記就寫到這里,希望能夠幫助大家。另外一點(diǎn)就是在閱讀相關(guān)技術(shù)文檔時(shí),大家需要認(rèn)真仔細(xì)一點(diǎn),以防采坑。

詳細(xì)信息,請(qǐng)移步:

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

第一種方式:Azure Provider: Authenticating using the Azure CLI

這個(gè)比較直接,首先你需要安裝Azure CLI,然后運(yùn)行:

PS C:\lab> az login

然后會(huì)跳出來一個(gè)網(wǎng)頁,輸入你的用戶名密碼即可,然后你就可以愉快的使用Terraform和Azure了,你登錄Azure的相關(guān)信息以及緩存到你本地電腦上了。所以這種方式最簡單,也不用在Terraform的代碼里提及你的Azure認(rèn)證信息,但是你換一臺(tái)電腦,再跑一下你的代碼,是跑不通的,你必須先安裝Azure CLI,再執(zhí)行az login命令,然后跟著提示登錄Azure。

至于第二種和第三種方式這里先不介紹了,這次踩坑是用第四種方式:

Authenticating using a Service Principal with a Client Secret

所以這里詳細(xì)說明一下這一種方式。

這種方式有個(gè)前提,你必須先在Azure上面創(chuàng)建Service Principal,具體詳細(xì)步驟請(qǐng)參考這個(gè)鏈接:

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

Service Principal創(chuàng)建好之后,按照官網(wǎng)參考文檔,在provider.tf文件里,就可以配置provider azurerm的相關(guān)信息了,整個(gè)項(xiàng)目文件結(jié)構(gòu)如下:

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

provider.tf文件內(nèi)容格式如下:

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 {} }

說明一下:

  • subscription_id:你的Azure訂閱ID

  • client_id:創(chuàng)建Service Principal后的Application (client) ID

  • client_secret:創(chuàng)建Service Principal后,創(chuàng)建application secret

  • tenant_id:創(chuàng)建Service Principal后,application的Directory (tenant) ID

main.tf文件內(nèi)容如下:

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

隨后terraform init走起,初始化沒問題。

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.

接著執(zhí)行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" {

不好,飄紅了,認(rèn)證出問題了,說Tenant id找不到,這都是copy的,不可能出錯(cuò)。

接著往下看:error_uri":"https://login.microsoftonline.com

嗯,就是這里,我是在Azure中國版上面創(chuàng)建的Service Principal,terraform去登錄的時(shí)候用的是Azure海外版的URI,那問題就出在這里了。

再回去看看Terraform官網(wǎng)關(guān)于Azurerm Provider的介紹:

這下明白了,environment雖然是optional的,但是默認(rèn)用的是public,也就是Azure海外版。問題根源找到了,改terraform代碼吧!添加environment參數(shù),值設(shè)為china即可。最終代碼如下:

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 {} }

再來一把 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.

嗯,沒報(bào)錯(cuò),提示會(huì)add 1個(gè)新resource,接著走一個(gè) 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.

登錄你的Azure中國portal,去resource group里看看,terraform-eval這個(gè)resource group被成功創(chuàng)建。搞定!

關(guān)于“Terraform中Azure Provider配置的注意事項(xiàng)有哪些”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI