全部產品
Search
文件中心

Terraform:Terraform Init 加速方案配置

更新時間:Jul 01, 2024

當您遇到由於網路延遲等原因造成的 terraform init 逾時,導致無法正常下載 Provider 等情況時,可通過配置阿里雲鏡像站解決。

問題描述

阿里雲 Provider 提供兩個下載源:source = hashicorp/alicloudsource = aliyun/alicloud。國內使用者在下載 Provider 時可能會遇到下載緩慢甚至下載失敗的問題:

- Finding aliyun/alicloud versions matching "1.191.0"...
╷
│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider aliyun/alicloud: could not query provider registry for registry.terraform.io/aliyun/alicloud: the request
│ failed after 2 attempts, please try again later: Get "https://registry.terraform.io/v1/providers/aliyun/alicloud/versions": net/http: request canceled (Client.Timeout
│ exceeded while awaiting headers)
╵

- Finding hashicorp/alicloud versions matching "1.191.0"...
╷
│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider hashicorp/alicloud: could not query provider registry for registry.terraform.io/hashicorp/alicloud: the
│ request failed after 2 attempts, please try again later: Get "https://registry.terraform.io/v1/providers/hashicorp/alicloud/versions": context deadline exceeded
│ (Client.Timeout exceeded while awaiting headers)
╵

解決方案

Terraform CLI 自 0.13.2 版本起提供了設定網路鏡像的功能。為解決以上問題,阿里雲 Provider 提供了鏡像服務以協助國內使用者快速下載。

配置方案

建立.terraformrcterraform.rc設定檔,檔案位置取決於主機的作業系統。

  • 在 Windows 環境上,檔案必須命名為terraform.rc,並放置在相關使用者的%APPDATA%目錄中。這個目錄的物理位置取決於Windows 版本和系統配置;在 PowerShell 中使用 $env:APPDATA 可以找到其在系統上的位置。

  • 在所有其他系統上,必須將該檔案命名為.terraformrc,並直接放在相關使用者的主目錄中。

也可以使用TF_CLI_CONFIG_FILE環境變數指定 Terraform CLI 設定檔的位置,任何此類檔案都應遵循命名模式*.tfrc

以 macOS 為例,在home目錄下建立.terraformrc檔案,內容如下:

provider_installation {
  network_mirror {
    url = "https://mirrors.aliyun.com/terraform/"
    // 限制只有阿里雲相關 Provider 從國內鏡像源下載
    include = ["registry.terraform.io/aliyun/alicloud", 
               "registry.terraform.io/hashicorp/alicloud",
              ]   
  }
  direct {
    // 聲明除了阿里雲相關Provider, 其它Provider保持原有的下載鏈路
    exclude = ["registry.terraform.io/aliyun/alicloud", 
               "registry.terraform.io/hashicorp/alicloud",
              ]  
  }
}