Terraform est un outil open source fourni par HashiCorp pour l'orchestration des ressources cloud. Il permet de prévisualiser, de configurer et de gérer les infrastructures et ressources cloud en toute sécurité et efficacité. Vous pouvez utiliser Terraform pour créer et mettre à jour automatiquement les ressources sur l'infrastructure Alibaba Cloud. Cette rubrique décrit comment créer et supprimer une instance Service Mesh (ASM) à l'aide de Terraform.
Prérequis
Terraform est installé et configuré sur votre machine locale. Pour plus d'informations, consultez la rubrique Installer et configurer Terraform sur le PC local.
-
Votre compte Alibaba Cloud est configuré. Des variables d'environnement sont créées pour spécifier vos identifiants d'authentification et les informations de région.
# 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"RemarquePour améliorer la flexibilité et la sécurité de la gestion des autorisations, nous vous recommandons de créer un utilisateur Resource Access Management (RAM) nommé Terraform. Créez ensuite une paire AccessKey pour cet utilisateur RAM et accordez-lui les autorisations nécessaires. Pour plus d'informations, consultez les rubriques Créer un utilisateur RAM et Accorder des autorisations à un utilisateur RAM.
Contexte
Pour plus d'informations sur Terraform, visitez le site officiel de Terraform.
Créer une instance ASM
-
Créez localement un fichier de configuration nommé main.tf.
-
Si vous ne disposez pas encore de réseau privé virtuel (VPC) ni de vSwitch, créez un fichier main.tf contenant le contenu suivant :
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 }Définissez les paramètres décrits dans le tableau suivant dans le fichier main.tf selon vos besoins. Terraform appelle automatiquement les opérations API pertinentes pour obtenir les valeurs des autres paramètres.
Paramètre
Description
mesh_name
Nom personnalisé de l'instance Service Mesh.
mesh_spec
Édition de l'instance Service Mesh. Valeurs valides :
Standard : Édition Standard (Gratuite).
enterprise : Édition Enterprise
ultimate : Édition Ultimate
new_vpc_name
Nom personnalisé du VPC.
new_vsw_name
Nom personnalisé du vSwitch.
api_server_public_eip
Indique si l'équilibreur de charge des serveurs API de l'instance Service Mesh doit être exposé via une adresse IP élastique (EIP). Valeurs valides :
true : expose l'équilibreur de charge des serveurs API de l'instance Service Mesh via une EIP.
false : n'expose pas l'équilibreur de charge des serveurs API de l'instance Service Mesh via une EIP.
-
Si vous avez déjà créé un VPC et un vSwitch, créez un fichier main.tf contenant le contenu suivant :
ImportantLe VPC et le vSwitch doivent appartenir à la région que vous avez spécifiée dans la variable d'environnement ALICLOUD_REGION lors de la configuration de Terraform. Sinon, Terraform ne pourra pas reconnaître le VPC ou le 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 }Définissez les paramètres décrits dans le tableau suivant dans le fichier main.tf selon vos besoins. Terraform appelle automatiquement les opérations API pertinentes pour obtenir les valeurs des autres paramètres.
Paramètre
Description
mesh_name
Nom personnalisé de l'instance Service Mesh.
mesh_spec
Édition de l'instance Service Mesh. Valeurs valides :
Standard : Édition Standard (Gratuite)
enterprise : Édition Enterprise
ultimate : Édition Ultimate
vpc_name
Nom du VPC créé.
vsw_name
Nom du vSwitch créé.
api_server_public_eip
Indique si l'équilibreur de charge des serveurs API de l'instance Service Mesh doit être exposé via une EIP.
true : expose l'équilibreur de charge des serveurs API de l'instance Service Mesh via une EIP.
false : n'expose pas l'équilibreur de charge des serveurs API de l'instance Service Mesh via une EIP.
-
-
Exécutez la commande suivante pour initialiser l'environnement d'exécution de Terraform :
terraform initRésultat attendu :
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. -
Exécutez la commande suivante pour générer un plan d'exécution Terraform :
terraform planRésultat attendu :
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. -
Exécutez la commande suivante pour créer une instance ASM à l'aide du fichier main.tf :
terraform applyRésultat attendu :
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:Saisissez yes à droite de Enter a value. Résultat attendu :
... 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.
Supprimer une instance ASM
Pour exécuter la commande destroy de Terraform afin de supprimer une instance ASM, vous devez accéder au répertoire contenant le fichier main.tf.
Accédez au répertoire contenant le fichier main.tf et exécutez la commande suivante pour supprimer une instance ASM :
terraform destroy
Résultat attendu :
...
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:
Saisissez yes à droite de Enter a value. Résultat attendu :
...
Destroy complete! Resources: 2 destroyed.
Modifier les attributs d'une instance ASM
Vous pouvez modifier les définitions d'attributs dans le fichier .tf et exécuter la commande terraform apply pour appliquer les modifications à l'instance ASM. L'exemple suivant modifie l'attribut http10_enabled. Inspirez-vous de cet exemple pour modifier les attributs d'une instance ASM à l'aide de Terraform.
-
Cet exemple utilise le fichier .tf pour un scénario où un VPC et un commutateur virtuel existent déjà. Modifiez la valeur de la propriété
mesh_config.pilot.http10_enabledpour la ressource de maillage de service en la définissant surtrue.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 } -
Exécutez
terraform apply. Le résultat affiche la modification planifiée pour le champ.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: -
Saisissez
yespour appliquer la modification....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]
Ajouter ou supprimer un cluster Kubernetes
Vous pouvez modifier le tableau cluster_ids dans le fichier .tf. Pour ajouter un cluster à gérer par ASM, ajoutez son ID au tableau. Pour retirer un cluster d'ASM, supprimez son ID du tableau. Ensuite, exécutez terraform apply pour appliquer les modifications à l'instance ASM.
-
Cet exemple montre comment ajouter un cluster à une instance ASM. Modifiez les
cluster_idsde la ressource de maillage de service en ajoutant l'ID du cluster au tableau :......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...... -
Exécutez
terraform apply. Le résultat affiche la modification planifiée du tableau d'ID des clusters du plan de données.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: -
Saisissez
yespour appliquer la modification....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.
Ressources et sources de données Terraform
Le tableau suivant décrit les ressources et sources de données Terraform pouvant être utilisées pour gérer les ressources ASM.
Type | Nom | Description |
Ressources | Gère les instances ASM. | |
Configure les autorisations sur les instances ASM. | ||
Sources de données | Interroge toutes les instances ASM. | |
Interroge toutes les versions disponibles de Service Mesh. |
Que faire si une invite indique que certains champs seront supprimés lors de l'exécution de la commande terraform apply ?
Pour simplifier les opérations, le serveur attribue des valeurs par défaut à certaines propriétés ASM même si vous ne les spécifiez pas lors de la création. Cela est similaire à la balise d'attribut Computed dans Terraform. Toutefois, si ces propriétés étaient définies comme Computed, leurs valeurs ne pourraient pas être modifiées pour devenir des valeurs vides, telles qu'une chaîne vide, le nombre 0 ou une valeur booléenne false. Pour permettre la modification de ces propriétés vers des valeurs vides, le fournisseur Terraform ASM ne les définit pas comme Computed. Lorsque vous exécutez terraform apply, le serveur renvoie ces propriétés. Si elles ne sont pas explicitement déclarées dans votre fichier .tf, Terraform suppose que vous souhaitez supprimer leurs valeurs. Si vous ne souhaitez pas supprimer ces propriétés, vous devez les ajouter manuellement à votre fichier .tf comme indiqué dans l'invite, puis exécuter à nouveau terraform apply.