Todos os produtos
Search
Central de documentação

Container Service for Kubernetes:Create an ACK dedicated cluster with Terraform

Última atualização: Aug 31, 2026

Implante um cluster dedicado do ACK baseado em Terway com VPC, vSwitches e add-ons provisionados automaticamente.

Execute este código no navegador pelo OpenAPI Portal .
Importante

A criação de clusters dedicados do ACK é restrita. Para solicitar acesso, envie um ticket.

Pré-requisitos

Verifique os seguintes requisitos:

  • ACK ativado (activate ACK by using Terraform).

  • Par de AccessKey criado para o usuário RAM que executará o Terraform (Criar um par de AccessKey, Usuários RAM).

    Use um usuário RAM em vez da conta raiz da Alibaba Cloud. Permissões limitadas reduzem riscos caso as credenciais sejam comprometidas.
  • Política de permissões mínimas abaixo anexada ao usuário RAM. Ela abrange criação, visualização e exclusão de Virtual Private Clouds (VPCs), vSwitches e clusters ACK (conceder permissões).

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "vpc:CreateVpc",
            "vpc:CreateVSwitch",
            "vpc:DescribeRouteTableList",
            "vpc:DescribeVpcAttribute",
            "vpc:ListEnhancedNatGatewayAvailableZones",
            "vpc:DescribeVSwitchAttributes",
            "vpc:DescribeNatGateways",
            "cs:CreateCluster",
            "cs:DescribeTaskInfo",
            "cs:DescribeClusterDetail",
            "cs:DescribeClusterCerts",
            "cs:CheckControlPlaneLogEnable",
            "vpc:DeleteVpc",
            "vpc:DeleteVSwitch",
            "cs:DeleteCluster"
          ],
          "Resource": "*"
        }
      ]
    }
  • Terraform v0.12.28 ou posterior. Verifique a versão com terraform --version.

    Opção

    Ideal para

    Terraform Explorer — online, sem instalação

    Testes rápidos e depuração sem custo

    Cloud Shell — pré-instalado e configurado com suas credenciais

    Execuções rápidas sem configuração local

    Resource Orchestration Service (ROS) — Terraform gerenciado

    Modelos que definem recursos da Alibaba Cloud, AWS ou Azure com ciclo de vida gerenciado

    Instalação local

    Ambientes de desenvolvimento personalizados ou redes com acesso restrito

Recursos do Terraform

Esta configuração usa os recursos listados abaixo. Como há cobrança de taxas, libere-os quando não forem mais necessários.

Recurso

Finalidade

alicloud_instance_types

Consultar tipos de instância do Elastic Compute Service (ECS) que atendem a condições específicas

alicloud_vpc

Criar uma VPC

alicloud_vswitch

Criar vSwitches (sub-redes) na VPC

alicloud_resource_manager_resource_groups

Consultar o grupo de recursos gerenciado pelo usuário RAM

alicloud_cs_kubernetes

Criar um cluster dedicado do ACK

A configuração seleciona tipos de instância disponíveis nas três zonas para garantir o agendamento dos nós do plano de controle em qualquer zona.

Gere parâmetros do Terraform pelo console

Se o exemplo não atender aos seus requisitos, gere os parâmetros diretamente no console do ACK:

  1. Faça login no console do ACK. No painel de navegação à esquerda, clique em Clusters.

  2. Na página Clusters, clique em Cluster Templates.

  3. Selecione um tipo de cluster, clique em Create e configure o cluster na página Cluster Configurations.

  4. Na página Confirm, clique em Console-to-Code.

  5. Na barra lateral, clique na aba Terraform e copie os parâmetros gerados.

Crie um cluster dedicado do ACK com Terway

Este procedimento cria um cluster dedicado do ACK com Terway. A configuração provisiona uma VPC, três vSwitches de plano de controle, três vSwitches de pod do Terway e o cluster, totalizando 8 recursos.

Etapa 1: Crie o arquivo de configuração

Crie um diretório de trabalho e um arquivo main.tf com o seguinte conteúdo:

provider "alicloud" {
  region = var.region_id
}

variable "region_id" {
  type    = string
  default = "cn-hangzhou"
}

variable "zone_ids" {
  type    = list(string)
  default = ["cn-hangzhou-i","cn-hangzhou-j","cn-hangzhou-k"]
}

# Specify the resource name or label.
variable "name" {
  default = "tf-example"
}

# Specify the ID of an existing VPC. If you leave this variable blank, a new VPC is created.
variable "vpc_id" {
  description = "Existing vpc id used to create several vswitches and other resources."
  default     = ""
}

# Specify the CIDR block of the new VPC. This variable takes effect if you leave the vpc_id variable blank.
variable "vpc_cidr" {
  description = "The cidr block used to launch a new vpc when 'vpc_id' is not specified."
  default     = "10.0.0.0/8"
}

# Specify the IDs of existing vSwitches.
variable "vswitch_ids" {
  description = "List of existing vswitch id."
  type        = list(string)
  default     = []
}

# If vswitch_ids is not specified, you must specify three CIDR blocks to create vSwitches. The CIDR blocks cannot overlap with each other.
variable "vswitch_cidrs" {
  description = "List of cidr blocks used to create several new vswitches when 'vswitch_ids' is not specified."
  type        = list(string)
  default     = ["10.1.0.0/16", "10.2.0.0/16", "10.3.0.0/16"]
}

# Specify the Terway configurations.
variable "terway_vswitch_ids" {
  description = "List of existing vswitch ids for terway."
  type        = list(string)
  default     = []
}

# This variable specifies the CIDR blocks in which Terway vSwitches are created if you leave the terway_vswitch_ids variable blank.
variable "terway_vswitch_cidrs" {
  description = "List of cidr blocks used to create several new vswitches when 'terway_vswitch_cidrs' is not specified."
  type        = list(string)
  default     = ["10.4.0.0/16", "10.5.0.0/16", "10.6.0.0/16"]
}

# Specify the components that you want to install in the ACK cluster. You must specify the name and configuration of each component that you want to install.
variable "cluster_addons" {
  type = list(object({
    name   = string
    config = string
  }))

  default = [
    {
      "name"   = "terway-eniip",
      "config" = "",
    },
    {
      "name"   = "csi-plugin",
      "config" = "",
    },
    {
      "name"   = "csi-provisioner",
      "config" = "",
    },
    {
      "name"   = "logtail-ds",
      "config" = "{\"IngressDashboardEnabled\":\"true\"}",
    },
    {
      "name"   = "nginx-ingress-controller",
      "config" = "{\"IngressSlbNetworkType\":\"internet\"}",
    },
    {
      "name"   = "arms-prometheus",
      "config" = "",
    },
    {
      "name"   = "ack-node-problem-detector",
      "config" = "{\"sls_project_name\":\"\"}",
    }
  ]
}

locals {
  all_zone_ids = [for zones in data.alicloud_enhanced_nat_available_zones.enhanced.zones : zones.zone_id]
  common_zone_ids = setintersection(toset(var.zone_ids),toset(local.all_zone_ids))

  # Obtain the instance types available in each zone.
  instance_types_per_az = { for az, types in data.alicloud_instance_types.default : az => [for t in types.instance_types : t.id] }

  # Obtain the list of instance types in all listed zones
  all_instance_types_in_zones = [for zone in local.common_zone_ids : local.instance_types_per_az[zone]]

  # Convert each list into a collection
  sets = [for s in local.all_instance_types_in_zones : toset(s)]

  # Calculate the instance types that are common to all zones.
  common_instance_types = [for element in local.sets[0]: element if length([for set in local.sets: set if contains(set, element)]) == length(local.sets)]
}

# Query the zones that support enhanced NAT gateways.
data "alicloud_enhanced_nat_available_zones" "enhanced" {
}

# If you do not specify the vpc_id variable, this Terraform resource creates a VPC. The CIDR block of the VPC is specified by the vpc_cidr variable.
resource "alicloud_vpc" "vpc" {
  count      = var.vpc_id == "" ?  1 : 0
  cidr_block = var.vpc_cidr
}

# If you do not specify the vswitch_ids variable, a new vSwitch is created based on the vswitch_cidrs.
resource "alicloud_vswitch" "vswitches" {
  count      = length(var.vswitch_ids) > 0 ?  0 : length(var.vswitch_cidrs)
  vpc_id     = var.vpc_id == "" ?  join("", alicloud_vpc.vpc.*.id) : var.vpc_id
  cidr_block = element(var.vswitch_cidrs, count.index)
  zone_id    = tolist(local.common_zone_ids)[count.index]
}

# If you do not specify the terway_vswitch_ids variable, the vSwitch used by Terway is created based on the vswitch_cidrs parameter.
resource "alicloud_vswitch" "terway_vswitches" {
  count      = length(var.terway_vswitch_ids) > 0 ?  0 : length(var.terway_vswitch_cidrs)
  vpc_id     = var.vpc_id == "" ?  join("", alicloud_vpc.vpc.*.id) : var.vpc_id
  cidr_block = element(var.terway_vswitch_cidrs, count.index)
  zone_id    = tolist(local.common_zone_ids)[count.index]
}

# Query the resource group managed by the RAM user.
data "alicloud_resource_manager_resource_groups" "default" {
  status = "OK"
}

# Query ECS instance types.
data "alicloud_instance_types" "default" {
  for_each            = toset(local.common_zone_ids )
  availability_zone   = each.key
  cpu_core_count      = 8
  memory_size         = 16
  kubernetes_node_role = "Master"
  system_disk_category = "cloud_essd"
}

# Create an ACK dedicated cluster and configure control plane vSwitches, pod vSwitches, instance types, disks, the password used to log on to nodes, and the Service CIDR block.
resource "alicloud_cs_kubernetes" "default" {
  master_vswitch_ids    = length(var.vswitch_ids) > 0 ?  split(",", join(",", var.vswitch_ids)) : length(var.vswitch_cidrs) < 1 ?  [] : split(",", join(",", alicloud_vswitch.vswitches.*.id)) # Query the zones that support enhanced NAT gateways.
  pod_vswitch_ids       = length(var.terway_vswitch_ids) > 0 ?  split(",", join(",", var.terway_vswitch_ids)) : length(var.terway_vswitch_cidrs) < 1 ?  [] : split(",", join(",", alicloud_vswitch.terway_vswitches.*.id)) # The CIDR blocks of pod vSwitches if you use Terway as the network component.
  master_instance_types = [local.common_instance_types[0],local.common_instance_types[0],local.common_instance_types[0]] # The instance type of the control planes.
  master_disk_category  = "cloud_essd"            # The system disk type of the control plane.
  password              = "Yourpassword1234"     # The password used for SSH logon.
  service_cidr          = "172.18.0.0/16"        # The Service CIDR block.
  load_balancer_spec    = "slb.s1.small"         # The Server Load Balancer (SLB) instance type.
  install_cloud_monitor = "true"                 # Enable CloudMonitor.
  resource_group_id     = data.alicloud_resource_manager_resource_groups.default.groups.0.id # The ID of the resource group to which the cluster belongs. Resource groups are used to isolate resources.
  deletion_protection   = "false"                # Deletion protection can prevent clusters from being accidentally deleted in the console or by calling API operations.
  timezone              = "Asia/Shanghai"        # The time zone of the cluster.
  os_type               = "Linux"                # The type of the node OS.
  platform              = "AliyunLinux3"         # The OS distribution.
  cluster_domain        = "cluster.local"        # The cluster domain name.
  proxy_mode            = "ipvs"                 # The kube-proxy mode.
  custom_san            = "www.terraform.io"     # The custom subject alternative name (SAN) of the API server certificate of the cluster.
  new_nat_gateway       = "true"                 # Create a NAT gateway.
  dynamic "addons" {
    for_each = var.cluster_addons
    content {
      name   = lookup(addons.value, "name", var.cluster_addons)
      config = lookup(addons.value, "config", var.cluster_addons)
    }
  }
}

Etapa 2: Inicialize o Terraform

terraform init

Uma inicialização bem-sucedida retorna:

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.

Etapa 3: Visualize o plano de execução

terraform plan

Este comando exibe as alterações planejadas nos recursos sem aplicá-las.

Um plano bem-sucedido retorna:

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: 8 to add, 0 to change, 0 to destroy.
...

Etapa 4: Crie o cluster

terraform apply

Quando solicitado, digite yes e pressione Enter.

Uma aplicação bem-sucedida retorna:

...
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_managed_kubernetes.default: Creation complete after 8m26s [id=************]

Apply complete!  Resources: 8 added, 0 changed, 0 destroyed.

Verifique o cluster

Após a conclusão do terraform apply, verifique o cluster usando um dos métodos abaixo:

Execute o comando terraform show

Opção 1: Use terraform show

terraform show

Lista todos os recursos criados pelo Terraform e seus estados atuais.

Faça login no console do ACK

Opção 2: Verifique no console do ACK

Faça login no console do ACK e confirme se o novo cluster aparece na lista Clusters.

Limpeza de recursos

Importante

A execução de terraform destroy exclui permanentemente todos os recursos criados por esta configuração. Esta ação é irreversível.

Libere os recursos. Consulte Comandos comuns para opções do terraform destroy.

terraform destroy

Quando solicitado, digite yes e pressione Enter. Uma destruição bem-sucedida retorna:

...
Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes
...
Destroy complete!  Resources: 7 destroyed.

Código de exemplo

Execute este código no Terraform Explorer .
provider "alicloud" {
  region = var.region_id
}

variable "region_id" {
  type    = string
  default = "cn-hangzhou"
}

variable "zone_ids" {
  type    = list(string)
  default = ["cn-hangzhou-i","cn-hangzhou-j","cn-hangzhou-k"]
}

# Specify the resource name or label.
variable "name" {
  default = "tf-example"
}

# Specify the ID of an existing VPC. If you leave this variable blank, a new VPC is created.
variable "vpc_id" {
  description = "Existing vpc id used to create several vswitches and other resources."
  default     = ""
}

# Specify the CIDR block of the new VPC. This variable takes effect if you leave the vpc_id variable blank.
variable "vpc_cidr" {
  description = "The cidr block used to launch a new vpc when 'vpc_id' is not specified."
  default     = "10.0.0.0/8"
}

# Specify the IDs of existing vSwitches.
variable "vswitch_ids" {
  description = "List of existing vswitch id."
  type        = list(string)
  default     = []
}

# If vswitch_ids is not specified, you must specify three CIDR blocks to create vSwitches. The CIDR blocks cannot overlap with each other.
variable "vswitch_cidrs" {
  description = "List of cidr blocks used to create several new vswitches when 'vswitch_ids' is not specified."
  type        = list(string)
  default     = ["10.1.0.0/16", "10.2.0.0/16", "10.3.0.0/16"]
}

# Specify the Terway configurations.
variable "terway_vswitch_ids" {
  description = "List of existing vswitch ids for terway."
  type        = list(string)
  default     = []
}

# This variable specifies the CIDR blocks in which Terway vSwitches are created if you leave the terway_vswitch_ids variable blank.
variable "terway_vswitch_cidrs" {
  description = "List of cidr blocks used to create several new vswitches when 'terway_vswitch_cidrs' is not specified."
  type        = list(string)
  default     = ["10.4.0.0/16", "10.5.0.0/16", "10.6.0.0/16"]
}

# Specify the components that you want to install in the ACK cluster. You must specify the name and configuration of each component that you want to install.
variable "cluster_addons" {
  type = list(object({
    name   = string
    config = string
  }))

  default = [
    {
      "name"   = "terway-eniip",
      "config" = "",
    },
    {
      "name"   = "csi-plugin",
      "config" = "",
    },
    {
      "name"   = "csi-provisioner",
      "config" = "",
    },
    {
      "name"   = "logtail-ds",
      "config" = "{\"IngressDashboardEnabled\":\"true\"}",
    },
    {
      "name"   = "nginx-ingress-controller",
      "config" = "{\"IngressSlbNetworkType\":\"internet\"}",
    },
    {
      "name"   = "arms-prometheus",
      "config" = "",
    },
    {
      "name"   = "ack-node-problem-detector",
      "config" = "{\"sls_project_name\":\"\"}",
    }
  ]
}

locals {
  all_zone_ids = [for zones in data.alicloud_enhanced_nat_available_zones.enhanced.zones : zones.zone_id]
  common_zone_ids = setintersection(toset(var.zone_ids),toset(local.all_zone_ids))

  # Obtain the instance types available in each zone.
  instance_types_per_az = { for az, types in data.alicloud_instance_types.default : az => [for t in types.instance_types : t.id] }

  # Obtain the list of instance types in all listed zones
  all_instance_types_in_zones = [for zone in local.common_zone_ids : local.instance_types_per_az[zone]]

  # Convert each list into a collection
  sets = [for s in local.all_instance_types_in_zones : toset(s)]

  # Calculate the instance types that are common to all zones.
  common_instance_types = [for element in local.sets[0]: element if length([for set in local.sets: set if contains(set, element)]) == length(local.sets)]
}

# Query the zones that support enhanced NAT gateways.
data "alicloud_enhanced_nat_available_zones" "enhanced" {
}

# If you do not specify the vpc_id variable, this Terraform resource creates a VPC. The CIDR block of the VPC is specified by the vpc_cidr variable.
resource "alicloud_vpc" "vpc" {
  count      = var.vpc_id == "" ?  1 : 0
  cidr_block = var.vpc_cidr
}

# If you do not specify the vswitch_ids variable, a new vSwitch is created based on the vswitch_cidrs.
resource "alicloud_vswitch" "vswitches" {
  count      = length(var.vswitch_ids) > 0 ?  0 : length(var.vswitch_cidrs)
  vpc_id     = var.vpc_id == "" ?  join("", alicloud_vpc.vpc.*.id) : var.vpc_id
  cidr_block = element(var.vswitch_cidrs, count.index)
  zone_id    = tolist(local.common_zone_ids)[count.index]
}

# If you do not specify the terway_vswitch_ids variable, the vSwitch used by Terway is created based on the vswitch_cidrs parameter.
resource "alicloud_vswitch" "terway_vswitches" {
  count      = length(var.terway_vswitch_ids) > 0 ?  0 : length(var.terway_vswitch_cidrs)
  vpc_id     = var.vpc_id == "" ?  join("", alicloud_vpc.vpc.*.id) : var.vpc_id
  cidr_block = element(var.terway_vswitch_cidrs, count.index)
  zone_id    = tolist(local.common_zone_ids)[count.index]
}

# Query the resource group managed by the RAM user.
data "alicloud_resource_manager_resource_groups" "default" {
  status = "OK"
}

# Query ECS instance types.
data "alicloud_instance_types" "default" {
  for_each            = toset(local.common_zone_ids )
  availability_zone   = each.key
  cpu_core_count      = 8
  memory_size         = 16
  kubernetes_node_role = "Master"
  system_disk_category = "cloud_essd"
}

# Create an ACK dedicated cluster and configure control plane vSwitches, pod vSwitches, instance types, disks, the password used to log on to nodes, and the Service CIDR block.
resource "alicloud_cs_kubernetes" "default" {
  master_vswitch_ids    = length(var.vswitch_ids) > 0 ?  split(",", join(",", var.vswitch_ids)) : length(var.vswitch_cidrs) < 1 ?  [] : split(",", join(",", alicloud_vswitch.vswitches.*.id)) # Query the zones that support enhanced NAT gateways.
  pod_vswitch_ids       = length(var.terway_vswitch_ids) > 0 ?  split(",", join(",", var.terway_vswitch_ids)) : length(var.terway_vswitch_cidrs) < 1 ?  [] : split(",", join(",", alicloud_vswitch.terway_vswitches.*.id)) # The CIDR blocks of pod vSwitches if you use Terway as the network component.
  master_instance_types = [local.common_instance_types[0],local.common_instance_types[0],local.common_instance_types[0]] # The instance type of the control planes.
  master_disk_category  = "cloud_essd"            # The system disk type of the control plane.
  password              = "Yourpassword1234"     # The password used for SSH logon.
  service_cidr          = "172.18.0.0/16"        # The Service CIDR block.
  load_balancer_spec    = "slb.s1.small"         # The SLB instance type.
  install_cloud_monitor = "true"                 # Enable CloudMonitor.
  resource_group_id     = data.alicloud_resource_manager_resource_groups.default.groups.0.id # The ID of the resource group to which the cluster belongs. Resource groups are used to isolate resources.
  deletion_protection   = "false"                # Deletion protection can prevent clusters from being accidentally deleted in the console or by calling API operations.
  timezone              = "Asia/Shanghai"        # The time zone of the cluster.
  os_type               = "Linux"                # The type of the node OS.
  platform              = "AliyunLinux3"         # The OS distribution.
  cluster_domain        = "cluster.local"        # The cluster domain name.
  proxy_mode            = "ipvs"                 # The kube-proxy mode.
  custom_san            = "www.terraform.io"     # The custom SAN for the API server certificate of the cluster.
  new_nat_gateway       = "true"                 # Create a NAT gateway.
  dynamic "addons" {
    for_each = var.cluster_addons
    content {
      name   = lookup(addons.value, "name", var.cluster_addons)
      config = lookup(addons.value, "config", var.cluster_addons)
    }
  }
}

Próximos passos