O Terraform é uma ferramenta de código aberto da HashiCorp para orquestração de recursos em nuvem. Com ele, você visualiza, configura e gerencia infraestruturas e recursos de nuvem de forma segura e eficiente. O Terraform permite criar e atualizar automaticamente recursos na infraestrutura da Alibaba Cloud. Este tópico descreve como criar e excluir uma instância do Service Mesh (ASM) usando o Terraform.
Pré-requisitos
Terraform instalado e configurado em sua máquina local. Para mais informações, consulte Instalar e configurar o Terraform no PC local.
-
Conta Alibaba Cloud configurada. Variáveis de ambiente criadas para especificar suas credenciais de autenticação e informações de região.
# Replace YOUR_ACCESS_KEY_ID and YOUR_ACCESS_KEY_SECRET in the following commands with the ID and secret of your Alibaba Cloud account AccessKey. export ALICLOUD_ACCESS_KEY="YOUR_ACCESS_KEY_ID" export ALICLOUD_SECRET_KEY="YOUR_ACCESS_KEY_SECRET" # Replace the value with the region ID of the cluster. export ALICLOUD_REGION="cn-beijing" # If the cluster is in a US region, configure the following environment variable to use the US endpoint. export ALIBABA_CLOUD_ENDPOINT_SERVICEMESH="servicemesh.us-east-1.aliyuncs.com"NotaPara aumentar a flexibilidade e a segurança no gerenciamento de permissões, recomendamos criar um usuário do Resource Access Management (RAM) chamado Terraform. Em seguida, crie um par de AccessKey para esse usuário RAM e conceda as permissões necessárias. Para mais informações, consulte Criar um usuário RAM e Conceder permissões a um usuário RAM.
Informações básicas
Para mais detalhes sobre o Terraform, visite o site oficial do Terraform.
Criar uma instância do ASM
-
Crie localmente um arquivo de configuração chamado main.tf.
-
Se você ainda não tiver uma virtual private cloud (VPC) ou um vSwitch, crie um arquivo main.tf com o seguinte conteúdo:
terraform { required_providers { alicloud = { source = "aliyun/alicloud" } } } variable "k8s_name_prefix" { description = "The name prefix used to create Service Mesh (ASM)." default = "tf-asm" } resource "random_uuid" "this" {} # The default resource names and configurations. locals { # The name of the ASM instance. mesh_name = substr(join("-", [var.k8s_name_prefix, random_uuid.this.result]), 0, 63) # The edition of the ASM instance. Valid values: enterprise and ultimate, which indicate Enterprise Edition and Ultimate Edition. mesh_spec = "enterprise" # The name of the VPC to be created. new_vpc_name = "vpc-for-${local.mesh_name}" # The name of the vSwitch to be created. new_vsw_name = "vsw-for-${local.mesh_name}" } # The zone in which you can create a vSwitch. data "alicloud_zones" "default" { available_resource_creation = "VSwitch" } # The VPC. resource "alicloud_vpc" "default" { vpc_name = local.new_vpc_name } # The vSwitch. resource "alicloud_vswitch" "default" { vpc_id = alicloud_vpc.default.id cidr_block = cidrsubnet(alicloud_vpc.default.cidr_block, 8, 2) zone_id = data.alicloud_zones.default.zones.0.id vswitch_name = local.new_vsw_name } # Query the ASM editions available for creating the ASM instance. data "alicloud_service_mesh_versions" "default" { edition = local.mesh_spec == "standard" ? "Default" : "Pro" } # Select the first available edition to create the ASM instance. locals { mesh_version = split(":", data.alicloud_service_mesh_versions.default.ids[0])[1] } # The ASM instance. resource "alicloud_service_mesh_service_mesh" "default" { # The name of the ASM instance. service_mesh_name = local.mesh_name # The network configurations of the ASM instance. network { # The ID of the VPC. vpc_id = alicloud_vpc.default.id # The ID of the vSwitch. vswitche_list = [alicloud_vswitch.default.id] } # The edition of the ASM instance. version = local.mesh_version # The load balancer for exposing the API servers and Istio Pilot of the ASM instance. load_balancer { # Specify whether to expose the load balancer for the API servers of the ASM instance using an elastic IP address (EIP). api_server_public_eip = true } # Configure the ASM instance by defining Mesh Config options. mesh_config { # Collect access logs to Alibaba Cloud Simple Log Service. access_log { enabled = true } # Enable the collection of control plane logs. To enable this feature, make sure that you have enabled Simple Log Service. control_plane_log { enabled = true } # Enable Tracing Analysis in Application Real-Time Monitoring Service (ARMS). tracing = true # If Tracing Analysis is enabled, set the sampling percentage. pilot { trace_sampling = 100 } # Enable Prometheus monitoring. telemetry = true # Enable Mesh Topology. To enable Mesh Topology, make sure that you have enabled Prometheus monitoring. kiali { enabled = true } # Enable the mesh audit feature. To enable this feature, make sure that you have enabled Simple Log Service. audit { enabled = true } } # The edition of the ASM instance. Valid values: enterprise and ultimate, which indicate Enterprise Edition and Ultimate Edition. cluster_spec = local.mesh_spec }Defina os parâmetros descritos na tabela abaixo no arquivo main.tf conforme necessário. O Terraform chama automaticamente as operações de API relevantes para obter os valores dos demais parâmetros.
Parâmetro
Descrição
mesh_name
Nome personalizado da instância do Service Mesh.
mesh_spec
Edição da instância do Service Mesh. Valores válidos:
Standard: Standard Edition (Gratuita).
enterprise: Enterprise Edition
ultimate: Ultimate Edition
new_vpc_name
Nome personalizado da VPC.
new_vsw_name
Nome personalizado do vSwitch.
api_server_public_eip
Indica se o balanceador de carga dos servidores de API da instância do Service Mesh deve ser exposto via EIP. Valores válidos:
true: expõe o balanceador de carga dos servidores de API da instância do Service Mesh usando um EIP.
false: não expõe o balanceador de carga dos servidores de API da instância do Service Mesh usando um EIP.
-
Se você já tiver criado uma VPC e um vSwitch, crie um arquivo main.tf com o seguinte conteúdo:
ImportanteA VPC e o vSwitch devem pertencer à região especificada na variável de ambiente ALICLOUD_REGION durante a configuração do Terraform. Caso contrário, o Terraform não reconhecerá a VPC ou o vSwitch.
terraform { required_providers { alicloud = { source = "aliyun/alicloud" } } } variable "asm_name_prefix" { description = "The name prefix used to create Service Mesh (ASM)." default = "tf-asm" } resource "random_uuid" "this" {} # The default resource names and configurations. locals { # The name of the ASM instance. mesh_name = substr(join("-", [var.asm_name_prefix, random_uuid.this.result]), 0, 63) # The edition of the ASM instance. Valid values: enterprise and ultimate, which indicate Enterprise Edition and Ultimate Edition. mesh_spec = "enterprise" # The name of the created VPC. vpc_name = "vpc-luying-hangzhou1" # The name of the created vSwitch. vsw_name = "vsw-luying-hangzhou1" } # The VPC. data "alicloud_vpcs" "default" { name_regex = local.vpc_name # The name of the created VPC. } # The vSwitch. data "alicloud_vswitches" "default" { vpc_id = data.alicloud_vpcs.default.ids[0] } locals { exist_vswitch_ids = [for vsw in data.alicloud_vswitches.default.vswitches : vsw.id if vsw.name == local.vsw_name] } # Query the ASM editions available for creating the ASM instance. data "alicloud_service_mesh_versions" "default" { edition = local.mesh_spec == "standard" ? "Default" : "Pro" } # Select the first available edition to create the ASM instance. locals { mesh_version = split(":", data.alicloud_service_mesh_versions.default.ids[0])[1] } # The ASM instance. resource "alicloud_service_mesh_service_mesh" "default" { # The name of the ASM instance. service_mesh_name = local.mesh_name # The network configurations of the ASM instance. network { # The ID of the VPC. vpc_id = data.alicloud_vpcs.default.ids[0] # The ID of the vSwitch. vswitche_list = [local.exist_vswitch_ids[0]] } # The edition of the ASM instance. version = local.mesh_version # The load balancer for exposing the load balancer for the API servers and Istio Pilot of the ASM instance. load_balancer { # Specify whether to expose the load balancer for the API servers of the ASM instance using an EIP. api_server_public_eip = true } # Configure the ASM instance by defining Mesh Config options. mesh_config { # Collect access logs to Alibaba Cloud Simple Log Service. access_log { enabled = true } # Enable the collection of control plane logs. To enable this feature, make sure that you have enabled Simple Log Service. control_plane_log { enabled = true } # Enable Tracing Analysis in ARMS. tracing = true # If Tracing Analysis is enabled, set the sampling percentage. pilot { trace_sampling = 100 } # Enable Prometheus monitoring. telemetry = true # Enable Mesh Topology. To enable Mesh Topology, make sure that you have enabled Prometheus monitoring. kiali { enabled = true } # Enable the mesh audit feature. To enable this feature, make sure that you have enabled Simple Log Service. audit { enabled = true } } # The edition of the ASM instance. Valid values: enterprise and ultimate, which indicate Enterprise Edition and Ultimate Edition. cluster_spec = local.mesh_spec }Configure os parâmetros listados na tabela a seguir no arquivo main.tf conforme necessário. O Terraform obtém automaticamente os valores dos outros parâmetros por meio de chamadas de API.
Parâmetro
Descrição
mesh_name
Nome personalizado da instância do Service Mesh.
mesh_spec
Edição da instância do Service Mesh. Valores válidos:
Standard: Standard Edition (Gratuita)
enterprise: Enterprise Edition
ultimate: Ultimate Edition
vpc_name
Nome da VPC criada.
vsw_name
Nome do vSwitch criado.
api_server_public_eip
Define se o balanceador de carga dos servidores de API da instância do Service Mesh será exposto via EIP.
true: expõe o balanceador de carga dos servidores de API da instância do Service Mesh usando um EIP.
false: não expõe o balanceador de carga dos servidores de API da instância do Service Mesh usando um EIP.
-
-
Execute o comando abaixo para inicializar o ambiente de execução do Terraform:
terraform initSaída esperada:
Initializing the backend... Initializing provider plugins... - Finding aliyun/alicloud versions matching "1.166.0"... - Finding latest version of hashicorp/random... ... 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. -
Execute o seguinte comando para gerar um plano de execução do Terraform:
terraform planSaída esperada:
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: ... Plan: 2 to add, 0 to change, 0 to destroy. -
Execute o comando a seguir para criar uma instância do ASM utilizando o arquivo main.tf:
terraform applySaída esperada:
alicloud_service_mesh_service_mesh.example: Refreshing state... ... Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value:Digite yes ao lado de Enter a value. Saída esperada:
... alicloud_service_mesh_service_mesh.default: Creating... alicloud_service_mesh_service_mesh.default: Still creating... [10s elapsed] ... alicloud_service_mesh_service_mesh.example: Creation complete after 2m42s [id=**********] Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Excluir uma instância do ASM
Para executar o comando destroy do Terraform e excluir uma instância do ASM, acesse o diretório onde o arquivo main.tf está localizado.
Navegue até o diretório que contém o arquivo main.tf e execute o comando abaixo para remover a instância do ASM:
terraform destroy
Saída esperada:
...
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:
Digite yes ao lado de Enter a value. Saída esperada:
...
Destroy complete! Resources: 2 destroyed.
Alterar atributos de uma instância do ASM
Modifique as definições de atributos no arquivo .tf e execute o comando terraform apply para aplicar as alterações na instância do ASM. O exemplo a seguir demonstra a alteração do atributo http10_enabled. Use este modelo como referência para ajustar outros atributos da instância do ASM via Terraform.
-
Este exemplo usa o arquivo .tf para um cenário em que já existem uma VPC e um vSwitch. Altere o valor da propriedade
mesh_config.pilot.http10_enableddo recurso service mesh paratrue.terraform { required_providers { alicloud = { source = "aliyun/alicloud" } } } variable "asm_name_prefix" { description = "The name prefix used to create Service Mesh (ASM)." default = "tf-asm" } resource "random_uuid" "this" {} # The default resource names and configurations. locals { # The name of the ASM instance. mesh_name = substr(join("-", [var.asm_name_prefix, random_uuid.this.result]), 0, 63) # The edition of the ASM instance. Valid values: enterprise and ultimate, which indicate Enterprise Edition and Ultimate Edition. mesh_spec = "enterprise" # The name of the created VPC. vpc_name = "prod-hz-vpc" # The name of the created vSwitch. vsw_name = "prod-hz-vpc-default" } # The VPC. data "alicloud_vpcs" "default" { name_regex = local.vpc_name # The name of the created VPC. } # The vSwitch. data "alicloud_vswitches" "default" { vpc_id = data.alicloud_vpcs.default.ids[0] } locals { exist_vswitch_ids = [for vsw in data.alicloud_vswitches.default.vswitches : vsw.id if vsw.name == local.vsw_name] } # Query the ASM editions available for creating the ASM instance. data "alicloud_service_mesh_versions" "default" { edition = local.mesh_spec == "standard" ? "Default" : "Pro" } # Select the first available edition to create the ASM instance. locals { mesh_version = split(":", data.alicloud_service_mesh_versions.default.ids[0])[1] } # The ASM instance. resource "alicloud_service_mesh_service_mesh" "default" { # The name of the ASM instance. service_mesh_name = local.mesh_name # The network configurations of the ASM instance. network { # The ID of the VPC. vpc_id = data.alicloud_vpcs.default.ids[0] # The ID of the vSwitch. vswitche_list = [local.exist_vswitch_ids[0]] } # The edition of the ASM instance. version = local.mesh_version # The load balancer for exposing the API servers and Istio Pilot of the ASM instance. load_balancer { # Specify whether to expose the load balancer for the API servers of the ASM instance using an EIP. api_server_public_eip = true } # Configure the ASM instance by defining Mesh Config options. mesh_config { # Collect access logs to Alibaba Cloud Simple Log Service. access_log { enabled = true } # Enable the collection of control plane logs. To enable this feature, make sure that you have enabled Simple Log Service. control_plane_log { enabled = true project = "mesh-log-cab09b566d4a64c1fa05271d5365495f1" } # Enable Tracing Analysis in ARMS. tracing = true # If Tracing Analysis is enabled, set the sampling percentage. pilot { trace_sampling = 100 http10_enabled = true } # Enable Prometheus monitoring. telemetry = true # Enable Mesh Topology. To enable Mesh Topology, make sure that you have enabled Prometheus monitoring. kiali { enabled = true } # Enable the mesh audit feature. To enable this feature, make sure that you have enabled Simple Log Service. audit { enabled = true } } # The edition of the ASM instance. Valid values: enterprise and ultimate, which indicate Enterprise Edition and Ultimate Edition. cluster_spec = local.mesh_spec } -
Execute
terraform apply. A saída exibirá a alteração planejada para o campo.terraform apply random_uuid.this: Refreshing state... [id=6ab24265-2381-dad9-3be5-351329c5665a] data.alicloud_vpcs.default: Reading... data.alicloud_service_mesh_versions.default: Reading... data.alicloud_service_mesh_versions.default: Read complete after 1s [id=605899410] data.alicloud_vpcs.default: Read complete after 1s [id=2909606812] data.alicloud_vswitches.default: Reading... data.alicloud_vswitches.default: Read complete after 0s [id=866499268] alicloud_service_mesh_service_mesh.default: Refreshing state... [id=cab09b566d4a64c1fa05271d5365495f1] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: ~ update in-place Terraform will perform the following actions: # alicloud_service_mesh_service_mesh.default will be updated in-place ~ resource "alicloud_service_mesh_service_mesh" "default" { id = "cab09b566d4a64c1fa05271d5365495f1" # (6 unchanged attributes hidden) ~ mesh_config { # (5 unchanged attributes hidden) ~ pilot { ~ http10_enabled = false -> true # (1 unchanged attribute hidden) } # (7 unchanged blocks hidden) } # (2 unchanged blocks hidden) } Plan: 0 to add, 1 to change, 0 to destroy. Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: -
Insira
yespara confirmar a alteração....Omit irrelevant content... 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_service_mesh_service_mesh.default: Modifying... [id=cab09b566d4a64c1fa05271d5365495f1] alicloud_service_mesh_service_mesh.default: Still modifying... [id=cab09b566d4a64c1fa05271d5365495f1, 10s elapsed] alicloud_service_mesh_service_mesh.default: Still modifying... [id=cab09b566d4a64c1fa05271d5365495f1, 20s elapsed] alicloud_service_mesh_service_mesh.default: Still modifying... [id=cab09b566d4a64c1fa05271d5365495f1, 30s elapsed] alicloud_service_mesh_service_mesh.default: Modifications complete after 37s [id=cab09b566d4a64c1fa05271d5365495f1]
Adicionar ou remover um cluster Kubernetes
Modifique o array cluster_ids no arquivo .tf para gerenciar clusters. Para adicionar um cluster ao ASM, acrescente seu ID ao array. Para removê-lo, exclua o ID correspondente. Em seguida, execute terraform apply para efetivar as mudanças na instância do ASM.
-
O exemplo abaixo ilustra a adição de um cluster a uma instância do ASM. Atualize o campo
cluster_idsdo recurso service mesh adicionando o ID do cluster ao array:......Omit irrelevant content...... # The ASM instance. resource "alicloud_service_mesh_service_mesh" "default" { # The name of the service mesh. service_mesh_name = local.mesh_name # The network configuration of the service mesh. network { # The VPC ID. vpc_id = data.alicloud_vpcs.default.ids[0] # The virtual switch ID. vswitche_list = [local.exist_vswitch_ids[0]] } # The version of the service mesh. version = local.mesh_version # The load balancer configuration for the API Server and Pilot of the service mesh. load_balancer { # Specifies whether to use an EIP to expose the API Server through a load balancer. api_server_public_eip = true } cluster_ids = [ "c94a1a1d968e04c55861b8747********" # Add the cluster ID to the array. ] ......Omit irrelevant content...... } ......Omit irrelevant content...... -
Execute
terraform apply. A saída mostrará a mudança planejada no array de IDs de clusters do plano de dados.random_uuid.this: Refreshing state... [id=6ab24265-2381-dad9-3be5-351329c5665a] data.alicloud_service_mesh_versions.default: Reading... data.alicloud_vpcs.default: Reading... data.alicloud_vpcs.default: Read complete after 1s [id=2909606812] data.alicloud_vswitches.default: Reading... data.alicloud_vswitches.default: Read complete after 0s [id=866499268] data.alicloud_service_mesh_versions.default: Read complete after 1s [id=3077056360] alicloud_service_mesh_service_mesh.default: Refreshing state... [id=c71fe2f2301234701b2e4116397426342] Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: ~ update in-place Terraform will perform the following actions: # alicloud_service_mesh_service_mesh.default will be updated in-place ~ resource "alicloud_service_mesh_service_mesh" "default" { ~ cluster_ids = [ + "c94a1a1d968e04c55861b8747********", ] id = "c71fe2f2301234701b2e4116397426342" tags = {} # (6 unchanged attributes hidden) } Plan: 0 to add, 1 to change, 0 to destroy. Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: -
Insira
yespara aplicar a alteração....Omit irrelevant content... 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_service_mesh_service_mesh.default: Modifying... [id=c71fe2f2301234701b2e4116397426342] alicloud_service_mesh_service_mesh.default: Still modifying... [id=c71fe2f2301234701b2e4116397426342, 10s elapsed] alicloud_service_mesh_service_mesh.default: Still modifying... [id=c71fe2f2301234701b2e4116397426342, 20s elapsed] alicloud_service_mesh_service_mesh.default: Still modifying... [id=c71fe2f2301234701b2e4116397426342, 30s elapsed] alicloud_service_mesh_service_mesh.default: Still modifying... [id=c71fe2f2301234701b2e4116397426342, 40s elapsed] alicloud_service_mesh_service_mesh.default: Still modifying... [id=c71fe2f2301234701b2e4116397426342, 50s elapsed] alicloud_service_mesh_service_mesh.default: Still modifying... [id=c71fe2f2301234701b2e4116397426342, 1m0s elapsed] alicloud_service_mesh_service_mesh.default: Still modifying... [id=c71fe2f2301234701b2e4116397426342, 1m10s elapsed] alicloud_service_mesh_service_mesh.default: Still modifying... [id=c71fe2f2301234701b2e4116397426342, 1m20s elapsed] alicloud_service_mesh_service_mesh.default: Still modifying... [id=c71fe2f2301234701b2e4116397426342, 1m30s elapsed] alicloud_service_mesh_service_mesh.default: Still modifying... [id=c71fe2f2301234701b2e4116397426342, 1m40s elapsed] alicloud_service_mesh_service_mesh.default: Modifications complete after 1m44s [id=c71fe2f2301234701b2e4116397426342] Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
Recursos e fontes de dados do Terraform
A tabela a seguir lista os recursos e fontes de dados do Terraform disponíveis para gerenciar recursos do ASM.
Tipo | Nome | Descrição |
Recursos | Gerencia instâncias do ASM. | |
Configura permissões em instâncias do ASM. | ||
Fontes de Dados | Consulta todas as instâncias do ASM. | |
Lista todas as versões disponíveis do Service Mesh. |
O que fazer se um aviso indicar que alguns campos serão excluídos ao executar o comando terraform apply?
Para simplificar a operação, o servidor atribui valores padrão a certas propriedades do ASM mesmo quando não especificadas na criação. Esse comportamento assemelha-se à tag de atributo Computed do Terraform. Contudo, se essas propriedades fossem definidas como Computed, não seria possível alterá-las para valores vazios, como string vazia, zero ou falso booleano. Para permitir tais alterações, o provedor do ASM para Terraform não as marca como Computed. Ao executar terraform apply, o servidor retorna essas propriedades. Se elas não estiverem declaradas explicitamente no arquivo .tf, o Terraform assumirá que você deseja excluir seus valores. Caso queira mantê-las, adicione-as manualmente ao arquivo .tf conforme indicado e execute terraform apply novamente.