全部產品
Search
文件中心

Terraform:通過Terraform Module建立容器鏡像倉庫並授權

更新時間:Nov 01, 2025

模組(Modules)是 Terraform 中代碼複用的主要方法,關於更多Modules的資訊,請參見基本術語。本文介紹如何通過Terraform Module,快速建立Container Registry命名空間與容器鏡像倉庫,以及建立用於訪問鏡像倉庫的RAM使用者並授權。

背景資訊

阿里雲Container RegistryACR(Alibaba Cloud Container Registry)是面向容器鏡像、Helm Chart等符合OCI標準雲原生製品安全託管及高效分發平台,方便使用者進行鏡像全生命週期管理,瞭解更多ACR相關資訊,請參見什麼是Container RegistryACR。在我們的DevOps工具訪問位於阿里雲的容器鏡像倉庫時,必須使用已授權的阿里雲帳號。

前提條件

說明

本教程樣本包含的部分資源會產生一定費用,請在不需要時及時進行釋放或退訂。

使用的資源

操作步驟

  1. 建立一個工作目錄,並在該工作目錄中建立名為main.tf的設定檔。將代碼複製到main.tf中。

    provider "alicloud" {}
    
    resource "random_integer" "default" {
      min = 10000
      max = 99999
    }
    
    module "cr" {
      source       = "roura356a/cr/alicloud"
      version      = "1.3.1"
      # 命名空間名稱 
      namespace    = "cr_repo_namespace_auto-${random_integer.default.result}"
      # 建立並授權的倉庫列表
      repositories = ["one", "two", "three"]
      # RAM使用者登入密碼。您在使用此模板時,請修改為高安全性的密碼
      password     = "YourPassword@123"
    }
  2. 執行如下命令,初始化Terraform運行環境。

    terraform init

    返回資訊如下,則Terraform初始化成功。

    Terraform has been successfully initialized!
    
    You may now begin working with Terraform. Try running "terraform plan" to see
    any changes that are required for your infrastructure. All Terraform commands
    should 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, other
    commands will detect it and remind you to do so if necessary.
  3. 執行如下命令,開始執行代碼。

    terraform apply

    在執行過程中,根據提示輸入yes並按下Enter鍵,等待命令執行完成,若出現以下資訊,則表示代碼執行成功。

    重要

    代碼成功執行後目前的目錄下會產生儲存AccessKey的檔案,請妥善保管,避免資訊泄露。

    module.cr.data.alicloud_account.current: Reading...
    module.cr.data.alicloud_regions.current: Reading...
    module.cr.data.alicloud_account.current: Read complete after 0s [id=*******]
    module.cr.data.alicloud_regions.current: Read complete after 0s [id=******]
    
    Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
      + create
    ...
    
    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
    
    
    Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
  4. 驗證結果。

    執行terraform show命令

    您可以在工作目錄中,使用以下命令查詢Terraform已建立資源的詳細資料:

    terraform show

    image

    登入控制台查看

    1. 登入Container Registry (aliyun.com),進入執行個體列表頁面,單擊個人版執行個體,單擊倉庫管理 > 鏡像倉庫,查看已建立的倉庫。

      image

    2. 登入RAM 存取控制 (aliyun.com),進入身份管理 > 使用者,單擊已建立RAM使用者的使用者登入名稱稱/顯示名稱

      image

    3. 進入許可權管理頁簽,查看已擁有的許可權。

      image

清理資源

當您不再需要上述通過Terraform建立或管理的資源時,請運行以下命令以釋放資源。關於terraform destroy的更多資訊,請參見常用命令

terraform destroy

相關文檔