Todos os produtos
Search
Central de documentação

Container Service for Kubernetes:Create an ACK Edge cluster using Terraform

Última atualização: Sep 16, 2026

O Terraform é uma ferramenta de código aberto de Infraestrutura como Código (IaC) que permite visualizar, provisionar e gerenciar infraestrutura e recursos na cloud de forma segura e eficiente. Este tópico descreve como usar o Terraform para criar um cluster ACK Edge.

Nota

O código de exemplo neste tópico oferece suporte à implantação com um clique. Execute o código no Terraform Explorer.

Pré-requisitos

  • Ative o ACK Edge.

  • Sua conta Alibaba Cloud deve ter permissões totais sobre todos os recursos. Se as credenciais da sua conta forem comprometidas, você poderá enfrentar riscos significativos de segurança. Recomendamos o uso de um usuário do Resource Access Management (RAM) e a criação de um AccessKey para esse usuário. Para mais informações, consulte Create a RAM user e Create an AccessKey.

  • Anexe a seguinte política de privilégio mínimo ao usuário RAM utilizado para executar comandos do Terraform. Essa política concede ao usuário RAM permissões para gerenciar os recursos deste exemplo. Para mais informações, consulte Manage RAM user permissions.

    Esta política permite que o usuário RAM crie, visualize e exclua VPCs, vSwitches e clusters ACK.

    {
        "Version": "1",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "vpc:CreateVpc",
                    "vpc:CreateVSwitch",
                    "cs:CreateCluster",
                    "vpc:DescribeVpcAttribute",
                    "vpc:DescribeVSwitchAttributes",
                    "vpc:DescribeRouteTableList",
                    "vpc:DescribeNatGateways",
                    "cs:DescribeTaskInfo",
                    "cs:DescribeClusterDetail",
                    "cs:GetClusterCerts",
                    "cs:CheckControlPlaneLogEnable",
                    "cs:CreateClusterNodePool",
                    "cs:DescribeClusterNodePoolDetail",
                    "cs:DescribeClusterNodePools",
                    "cs:ScaleOutCluster",
                    "cs:DescribeClusterNodes",
                    "vpc:DeleteVpc",
                    "vpc:DeleteVSwitch",
                    "cs:DeleteCluster",
                    "cs:DeleteClusterNodepool"
                ],
                "Resource": "*"
            }
        ]
    }
  • Prepare um ambiente Terraform. Utilize um dos métodos abaixo para executar o Terraform.

    • Terraform Explorer: A Alibaba Cloud fornece um ambiente online para execução do Terraform, eliminando a necessidade de instalação local. Faça login para utilizar e testar o Terraform diretamente no navegador. Esta opção é ideal para testes rápidos e depuração sem custos.

    • Create resources with Terraform: O Cloud Shell da Alibaba Cloud já possui componentes do Terraform pré-instalados e credenciais de identidade configuradas. Execute comandos do Terraform diretamente no Cloud Shell. Recomendado para acesso rápido e prático com baixo custo operacional.

    • Install and configure Terraform: Indicado para cenários com conectividade de rede limitada ou quando um ambiente de desenvolvimento personalizado for necessário.

    Importante

    Certifique-se de que sua versão do Terraform seja v0.12.28 ou superior. Execute o comando terraform --version para verificar a versão.

Recursos

Nota

Alguns recursos criados neste tópico são cobrados no modelo de pagamento conforme o uso. Libere os recursos quando não forem mais necessários para evitar cobranças inesperadas.

Criar um cluster ACK Edge

  1. Crie um diretório de trabalho e um arquivo de configuração chamado main.tf dentro desse diretório.

    O arquivo main.tf define a seguinte configuração do Terraform:

    • Cria uma VPC e um vSwitch dentro dela.

    • Provisiona um cluster ACK Edge.

    • Configura um pool de nós contendo dois nós.

    provider "alicloud" {
      region = var.region_id
    }
    variable "region_id" {
      default = "cn-hangzhou"
    }
    variable "k8s_name_edge" {
      type        = string
      description = "The name used to create edge kubernetes cluster."
      default     = "edge-example"
    }
    variable "new_vpc_name" {
      type        = string
      description = "The name used to create vpc."
      default     = "tf-vpc-172-16"
    }
    variable "new_vsw_name" {
      type        = string
      description = "The name used to create vSwitch."
      default     = "tf-vswitch-172-16-0"
    }
    variable "nodepool_name" {
      type        = string
      description = "The name used to create node pool."
      default     = "edge-nodepool-1"
    }
    variable "k8s_login_password" {
      type    = string
      default = "Test123456"
    }
    variable "k8s_version" {
      type        = string
      description = "Kubernetes version"
      default     = "1.28.9-aliyun.1"
    }
    variable "containerd_runtime_version" {
      type    = string
      default = "1.6.34"
    }
    variable "cluster_spec" {
      type        = string
      description = "The cluster specifications of kubernetes cluster,which can be empty. Valid values:ack.standard : Standard managed clusters; ack.pro.small : Professional managed clusters."
      default     = "ack.pro.small"
    }
    data "alicloud_zones" "default" {
      available_resource_creation = "VSwitch"
      available_disk_category     = "cloud_efficiency"
    }
    data "alicloud_instance_types" "default" {
      availability_zone    = data.alicloud_zones.default.zones.0.id
      cpu_core_count       = 4
      memory_size          = 8
      kubernetes_node_role = "Worker"
    }
    resource "alicloud_vpc" "vpc" {
      vpc_name   = var.new_vpc_name
      cidr_block = "172.16.0.0/12"
    }
    resource "alicloud_vswitch" "vsw" {
      vswitch_name = var.new_vsw_name
      vpc_id       = alicloud_vpc.vpc.id
      cidr_block   = cidrsubnet(alicloud_vpc.vpc.cidr_block, 8, 8)
      zone_id      = data.alicloud_zones.default.zones.0.id
    }
    resource "alicloud_cs_edge_kubernetes" "edge" {
      name                  = var.k8s_name_edge
      version               = var.k8s_version
      cluster_spec          = var.cluster_spec
      worker_vswitch_ids    = split(",", join(",", alicloud_vswitch.vsw.*.id))
      worker_instance_types = [data.alicloud_instance_types.default.instance_types.0.id]
      password              = var.k8s_login_password
      new_nat_gateway       = true
      pod_cidr              = "10.10.0.0/16"
      service_cidr          = "10.12.0.0/16"
      load_balancer_spec    = "slb.s2.small"
      worker_number         = 1
      node_cidr_mask        = 24
      # The container runtime.
      runtime = {
        name    = "containerd"
        version = var.containerd_runtime_version
      }
    }
    # The node pool.
    resource "alicloud_cs_kubernetes_node_pool" "nodepool" {
      # The ID of the Kubernetes cluster.
      cluster_id = alicloud_cs_edge_kubernetes.edge.id
      # The name of the node pool.
      node_pool_name = var.nodepool_name
      # The vSwitches for the new Kubernetes cluster. Specify the IDs of one or more vSwitches. The vSwitches must be in the zone specified by availability_zone.
      vswitch_ids = split(",", join(",", alicloud_vswitch.vsw.*.id))
      # The ECS instance types and billing method.
      instance_types       = [data.alicloud_instance_types.default.instance_types.0.id]
      instance_charge_type = "PostPaid"
      # Optional. A custom instance name.
      # node_name_mode      = "customized,edge-shenzhen,ip,default"
      # The container runtime.
      runtime_name    = "containerd"
      runtime_version = var.containerd_runtime_version
      # The expected number of nodes in the node pool.
      desired_size = 2
      # The password used to log on to the cluster nodes by using SSH.
      password = var.k8s_login_password
      # Specifies whether to install CloudMonitor on the Kubernetes nodes.
      install_cloud_monitor = true
      # The category of the system disk for nodes. Valid values: cloud_ssd and cloud_efficiency. Default value: cloud_efficiency.
      system_disk_category = "cloud_efficiency"
      system_disk_size     = 100
      # The OS type.
      image_type = "AliyunLinux"
      # The data disk configurations of nodes.
      data_disks {
        # The category of the data disk.
        category = "cloud_efficiency"
        # The size of the data disk.
        size = 120
      }
      lifecycle {
        ignore_changes = [
          labels
        ]
      }
    }
  2. Execute o comando abaixo para inicializar o diretório de trabalho do Terraform.

    terraform init

    Uma inicialização bem-sucedida gera a seguinte saída:

    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. Execute o comando a seguir para criar um plano de execução e visualizar as alterações.

    terraform plan

    A saída abaixo indica que o plano de execução foi criado com sucesso.

    Refreshing Terraform state in-memory prior to plan...
    The refreshed state will be used to calculate this plan, but will not be
    persisted to local or remote state storage.
    ...
    Plan: 4 to add, 0 to change, 0 to destroy.
    ...
  4. Execute o comando abaixo para aplicar a configuração e criar o cluster ACK Edge.

    terraform apply

    Quando solicitado, insira yes e pressione Enter. Aguarde a conclusão do comando. O cluster será criado com sucesso quando a seguinte saída aparecer:

    ...
    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
    ...
    alicloud_cs_edge_kubernetes.edge: Creation complete after 8m26s [id=************]
    Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
  5. Verifique o resultado

    Terraform show

    Execute o comando abaixo para visualizar detalhes sobre os recursos criados pelo Terraform.

    terraform show

    O comando retorna uma saída semelhante à seguinte:

    # alicloud_cs_edge_kubernetes.edge:
    resource "alicloud_cs_edge_kubernetes" "edge" {
        certificate_authority = {}
        cluster_spec          = "ack.pro.small"
        connections           = {
            "api_server_internet" = "https://121.43.xxx.xxx:6443"
            "api_server_intranet" = "https://172.16.xxx.xxx:6443"
            "master_public_ip"    = "12xxx5"
        }
        deletion_protection   = false
        force_update          = false
        id                    = "c8cfixxx691"
        install_cloud_monitor = true
        load_balancer_spec    = "slb.s2.small"
        name                  = "edge-example-edge"
        name_prefix           = "Terraform-Creation"
        nat_gateway_id        = "ngw-bp1xxxoy"
        new_nat_gateway       = true
        node_cidr_mask        = 24
        password              = (sensitive value)
        pod_cidr              = "10.10.0.0/16"
        proxy_mode            = "ipvs"
        resource_group_id     = "rg-aekzxxxxxxxx"
        runtime               = {
            "name"    = "containerd"
            "version" = "1.6.28"
        }
    }

    ACK console

    Faça login no ACK console para visualizar o cluster criado. Na página de detalhes do cluster, clique em Basic Information para ver suas informações básicas e configurações de rede. As informações básicas incluem detalhes como nome do cluster (edge-example), região (China (Hangzhou)), status do cluster (Running), tipo de cluster (ACK Edge Pro), versão do Kubernetes (1.28.9-aliyun.1) e proteção contra exclusão (Disabled). As configurações de rede abrangem o plug-in de rede (Flannel), modo de proxy de serviço (IPVS), endpoints internos e públicos do servidor de API, além do Service CIDR (10.12.0.0/16).

Limpar recursos

Para liberar os recursos criados neste tópico, execute o comando terraform destroy. Para mais informações sobre o terraform destroy, consulte Common commands.

terraform destroy

Exemplo completo

Nota

O código de exemplo neste tópico oferece suporte à implantação com um clique. Execute o código no Terraform Explorer.

Código de exemplo

provider "alicloud" {
  region = var.region_id
}
variable "region_id" {
  default = "cn-hangzhou"
}
variable "k8s_name_edge" {
  type        = string
  description = "The name used to create edge kubernetes cluster."
  default     = "edge-example"
}
variable "new_vpc_name" {
  type        = string
  description = "The name used to create vpc."
  default     = "tf-vpc-172-16"
}
variable "new_vsw_name" {
  type        = string
  description = "The name used to create vSwitch."
  default     = "tf-vswitch-172-16-0"
}
variable "nodepool_name" {
  type        = string
  description = "The name used to create node pool."
  default     = "edge-nodepool-1"
}
variable "k8s_login_password" {
  type    = string
  default = "Test123456"
}
variable "k8s_version" {
  type        = string
  description = "Kubernetes version"
  default     = "1.28.9-aliyun.1"
}
variable "containerd_runtime_version" {
  type    = string
  default = "1.6.34"
}
variable "cluster_spec" {
  type        = string
  description = "The cluster specifications of kubernetes cluster,which can be empty. Valid values:ack.standard : Standard managed clusters; ack.pro.small : Professional managed clusters."
  default     = "ack.pro.small"
}
data "alicloud_zones" "default" {
  available_resource_creation = "VSwitch"
  available_disk_category     = "cloud_efficiency"
}
data "alicloud_instance_types" "default" {
  availability_zone    = data.alicloud_zones.default.zones.0.id
  cpu_core_count       = 4
  memory_size          = 8
  kubernetes_node_role = "Worker"
}
resource "alicloud_vpc" "vpc" {
  vpc_name   = var.new_vpc_name
  cidr_block = "172.16.0.0/12"
}
resource "alicloud_vswitch" "vsw" {
  vswitch_name = var.new_vsw_name
  vpc_id       = alicloud_vpc.vpc.id
  cidr_block   = cidrsubnet(alicloud_vpc.vpc.cidr_block, 8, 8)
  zone_id      = data.alicloud_zones.default.zones.0.id
}
resource "alicloud_cs_edge_kubernetes" "edge" {
  name                  = var.k8s_name_edge
  version               = var.k8s_version
  cluster_spec          = var.cluster_spec
  worker_vswitch_ids    = split(",", join(",", alicloud_vswitch.vsw.*.id))
  worker_instance_types = [data.alicloud_instance_types.default.instance_types.0.id]
  password              = var.k8s_login_password
  new_nat_gateway       = true
  pod_cidr              = "10.10.0.0/16"
  service_cidr          = "10.12.0.0/16"
  load_balancer_spec    = "slb.s2.small"
  worker_number         = 1
  node_cidr_mask        = 24
  # The container runtime.
  runtime = {
    name    = "containerd"
    version = var.containerd_runtime_version
  }
}
# The node pool.
resource "alicloud_cs_kubernetes_node_pool" "nodepool" {
  # The ID of the Kubernetes cluster.
  cluster_id = alicloud_cs_edge_kubernetes.edge.id
  # The name of the node pool.
  node_pool_name = var.nodepool_name
  # The vSwitches for the new Kubernetes cluster. Specify the IDs of one or more vSwitches. The vSwitches must be in the zone specified by availability_zone.
  vswitch_ids = split(",", join(",", alicloud_vswitch.vsw.*.id))
  # The ECS instance types and billing method.
  instance_types       = [data.alicloud_instance_types.default.instance_types.0.id]
  instance_charge_type = "PostPaid"
  # Optional. A custom instance name.
  # node_name_mode      = "customized,edge-shenzhen,ip,default"
  # The container runtime.
  runtime_name    = "containerd"
  runtime_version = var.containerd_runtime_version
  # The expected number of nodes in the node pool.
  desired_size = 2
  # The password used to log on to the cluster nodes by using SSH.
  password = var.k8s_login_password
  # Specifies whether to install CloudMonitor on the Kubernetes nodes.
  install_cloud_monitor = true
  # The category of the system disk for nodes. Valid values: cloud_ssd and cloud_efficiency. Default value: cloud_efficiency.
  system_disk_category = "cloud_efficiency"
  system_disk_size     = 100
  # The OS type.
  image_type = "AliyunLinux"
  # The data disk configurations of nodes.
  data_disks {
    # The category of the data disk.
    category = "cloud_efficiency"
    # The size of the data disk.
    size = 120
  }
  lifecycle {
    ignore_changes = [
      labels
    ]
  }
}