通过Terraform Module创建容器镜像仓库并授权

更新时间:

模块(Modules)是 Terraform 中代码复用的主要方法,关于更多Modules的信息,请参见代码编写阶段的术语和概念。本文介绍如何通过Terraform Module,快速创建容器镜像服务命名空间与容器镜像仓库,以及创建用于访问镜像仓库的RAM用户并授权。

背景信息

阿里云容器镜像服务ACR(Alibaba Cloud Container Registry)是面向容器镜像、Helm Chart等符合OCI标准云原生制品安全托管及高效分发平台,方便用户进行镜像全生命周期管理,了解更多ACR相关信息,请参见什么是容器镜像服务ACR。在我们的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. 登录容器镜像服务 (aliyun.com),进入实例列表页面,单击个人实例,单击仓库管理 > 镜像仓库,查看已创建的仓库。

      image

    2. 登录RAM 访问控制 (aliyun.com),进入身份管理 > 用户,单击已创建RAM用户的用户登录名称/显示名称

      image

    3. 进入权限管理页签,查看已拥有的权限。

      image

清理资源

当您不再需要上述通过Terraform创建或管理的资源时,请运行以下命令以释放资源。关于terraform destroy的更多信息,请参见Terraform常用命令

terraform destroy

相关文档