Tous les produits
Search
Centre de documentation

Serverless App Engine:Associer et dissocier une instance SLB publique à une application SAE avec Terraform

Dernière mise à jour :Aug 11, 2026

Après avoir déployé une application dans Serverless App Engine (SAE), vous pouvez ajouter une instance Server Load Balancer (SLB) exposée sur Internet pour rendre l'application accessible au public, ou ajouter une instance SLB interne pour permettre la communication entre les applications situées dans le même Virtual Private Cloud (VPC). Cette rubrique explique comment utiliser Terraform pour associer et dissocier une instance SLB exposée sur Internet d'une application SAE.

Remarque

Exécutez l'exemple de code de cette rubrique via le lien suivant : Exécuter en un clic

Prérequis

  • L'utilisation de la clé AccessKey d'un compte Alibaba Cloud présente un risque élevé pour la sécurité, car ce compte dispose de toutes les autorisations sur l'ensemble des ressources. Nous vous recommandons de créer et d'utiliser un utilisateur RAM pour la gestion de votre infrastructure. Pour plus d'informations, consultez les rubriques Créer un utilisateur RAM et Créer une clé AccessKey.

  • Cette stratégie personnalisée permet à l'utilisateur RAM de décrire, créer, supprimer, configurer et modifier le statut des instances SLB. Elle accorde également les autorisations nécessaires pour associer et dissocier les applications SAE aux instances SLB.

    Attachez la stratégie suivante à l'utilisateur RAM utilisé pour exécuter les commandes Terraform. Elle accorde les autorisations minimales requises pour gérer les ressources présentées dans ce tutoriel. Pour plus d'informations, consultez la rubrique Gérer les autorisations des utilisateurs RAM.

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "slb:DescribeLoadBalancers",
            "slb:DescribeLoadBalancerAttribute",
            "slb:CreateLoadBalancer",
            "slb:DeleteLoadBalancer",
            "slb:ModifyLoadBalancerInternetSpec",
            "slb:CreateLoadBalancerTCPListener",
            "slb:CreateLoadBalancerHTTPListener",
            "slb:CreateLoadBalancerHTTPSListener",
            "slb:DeleteLoadBalancerListener",
            "slb:SetLoadBalancerStatus",
            "sae:BindSlb",
            "sae:UnbindSlb"
          ],
          "Resource": "*"
        }
      ]
    }
  • Préparez un environnement d'exécution Terraform. Vous pouvez utiliser l'une des méthodes suivantes :

Ressources

Créer une application et associer une instance SLB

Cet exemple montre comment déployer une application personnalisée à partir d'une image et l'associer à une instance SLB dans la région Chine (Shenzhen).

  1. Créez un dossier de projet nommé terraform pour vos fichiers Terraform.

  2. Accédez au répertoire du projet :

    cd terraform
  3. Créez un fichier de configuration nommé main.tf.

    Le fichier doit contenir la configuration suivante :

    # Configure the provider
    provider "alicloud" {
      region = var.region_id
    }
    # Define variables
    variable "region_id" {
      type    = string
      default = "cn-shenzhen"
    }
    variable "app_name" {
      description = "The name of the application."
      type        = string
      default     = "app-slb"
    }
    variable "image_url" {
      description = "The URL of the image."
      type        = string
      default     = "registry.cn-hangzhou.aliyuncs.com/google_containers/nginx-slim:0.9"
    }
    variable "namespace_id" {
      description = "The ID of the namespace."
      type        = string
      default     = "cn-shenzhen:demo"
    }
    variable "namespace_name" {
      description = "The name of the namespace."
      type        = string
      default     = "demo"
    }
    # Namespace
    resource "alicloud_sae_namespace" "default" {
      namespace_description = var.namespace_description
      namespace_id          = var.namespace_id
      namespace_name        = var.namespace_name
    }
    # VPC
    resource "alicloud_vpc" "default" {
      vpc_name   = var.name
      cidr_block = "10.4.0.0/16"
    }
    # VSwitch
    resource "alicloud_vswitch" "default" {
      vswitch_name = var.name
      cidr_block   = "10.4.0.0/24"
      vpc_id       = alicloud_vpc.default.id
      zone_id      = var.zone_id
    }
    # Security group
    resource "alicloud_security_group" "sg" {
      name        = var.name
      description = var.description
      vpc_id      = alicloud_vpc.default.id
    }
    resource "alicloud_security_group_rule" "sg_rule" {
      type              = "ingress"
      ip_protocol       = "tcp"
      nic_type          = "intranet"
      policy            = "accept"
      port_range        = var.port_range
      priority          = 1
      security_group_id = alicloud_security_group.sg.id
      cidr_ip           = var.cidr_ip
    }
    # Application configuration
    resource "alicloud_sae_application" "manual" {
      app_name          = var.app_name
      app_description   = var.app_description
      deploy            = true
      image_url         = var.image_url
      namespace_id      = alicloud_sae_namespace.default.id
      vswitch_id        = alicloud_vswitch.default.id
      vpc_id            = alicloud_vpc.default.id
      security_group_id = alicloud_security_group.sg.id
      package_type      = var.package_type
      timezone          = "Asia/Beijing"
      replicas          = var.replicas
      cpu               = var.cpu
      memory            = var.memory
    }
    # SLB configuration
    resource "alicloud_slb_load_balancer" "slb" {
      load_balancer_name = "prod"
      address_type       = "internet"
      load_balancer_spec = "slb.s2.small"
      vswitch_id         = alicloud_vswitch.default.id
    }
    resource "alicloud_sae_load_balancer_internet" "example" {
      app_id          = alicloud_sae_application.manual.id
      internet_slb_id = alicloud_slb_load_balancer.slb.id
      internet {
        protocol    = "HTTP"
        port        = var.port
        target_port = 80
      }
    }
    # Other variable definitions
    variable "namespace_description" {
      description = "A description for the namespace."
      default     = "a namespace"
    }
    variable "name" {
      default     = "tf"
      description = "The name for the security group rule."
      type        = string
    }
    variable "description" {
      default     = "A description for the security group rule."
      description = "The description of the security group rule."
      type        = string
    }
    variable "port_range" {
      default     = "1/65535"
      description = "The port range for the security group rule."
      type        = string
    }
    variable "cidr_ip" {
      description = "The CIDR block used to create a new security group rule."
      type        = string
      default     = "0.0.0.0/0"
    }
    variable "zone_id" {
      description = "The ID of the availability zone."
      type        = string
      default     = "cn-shenzhen-a"
    }
    variable "app_description" {
      default     = "A description for the application, created by Terraform."
      description = "The description of the application."
      type        = string
    }
    variable "package_type" {
      default     = "Image"
      description = "The package type of the application."
      type        = string
    }
    variable "cpu" {
      default     = "500"
      description = "The CPU allocation for the application, in millicores."
      type        = string
    }
    variable "memory" {
      default     = "1024"
      description = "The memory allocation for the application, in MB."
      type        = string
    }
    variable "replicas" {
      default     = "1"
      description = "The number of application instances (replicas)."
      type        = string
    }
    variable "port" {
      description = "The listening port of the SLB instance."
      type        = string
      default     = "8000"
    }
    # Outputs
    output "namespace_id" {
      value       = var.namespace_id
      description = "The ID of the namespace."
    }
    output "app_id" {
      description = "The ID of the application."
      value       = alicloud_sae_application.manual.id
    }
    output "app_name" {
      description = "The name of the application."
      value       = var.app_name
    }
    output "endpoint" {
      value = format("http://%s:%s", alicloud_slb_load_balancer.slb.address, var.port)
    }
  4. Exécutez la commande suivante pour initialiser votre répertoire de travail Terraform.

    terraform init
  5. Sortie attendue :

    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.
  6. Exécutez les commandes suivantes pour créer les ressources.

    1. Pour déployer l'application, exécutez la commande suivante. Lorsque vous y êtes invité, saisissez yes et appuyez sur Enter pour confirmer le déploiement.

      terraform apply

      Sortie attendue :

      Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
      Outputs:
      app_id = "8abb794f-a47b-474b-b6f5-2xxx"
      app_name = "app-slb"
      endpoint = "http://8.xxx.xxx:8000"
      namespace_id = "cn-shenzhen:demo"

    Terraform crée l'application app-slb et l'associe à une instance SLB. La sortie affiche l'adresse IP publique et le port de l'instance SLB.

  7. Vérifiez le résultat :

    Exécuter terraform show

    Exécutez la commande suivante pour afficher les détails des ressources créées par Terraform :

    terraform show
    # alicloud_sae_application.manual:
    resource "alicloud_sae_application" "manual" {
        app_description            = "A description for the application, created by Terraform."
        app_name                   = "app-slb"
        cpu                        = 500
        deploy                     = true
        id                         = "8abb794f-a47b-474b-bxxx51"
        image_url                  = "registry.cn-hangzhou.aliyuncs.com/google_containers/nginx-slim:0.9"
        memory                     = 1024
        namespace_id               = "cn-shenzhen:demo"
        package_type               = "Image"
        replicas                   = 1
        security_group_id          = "sg-xxx"
        status                     = "RUNNING"
        timezone                   = "Asia/Beijing"
        vpc_id                     = "vpc-xxx"
        vswitch_id                 = "vsw-xxx"
    }
    
    # alicloud_sae_load_balancer_internet.example:
    resource "alicloud_sae_load_balancer_internet" "example" {
        app_id          = "8abb794f-a47b-474b-bxxx51"
        id              = "8abb794f-a47b-474b-bxxx51"
        internet_ip     = "8.xxx.xxx"
        internet_slb_id = "lb-xxx"
    
        internet {
            port        = 8000
            protocol    = "HTTP"
            target_port = 80
        }
    }

    Vérifier dans un navigateur

    Saisissez l'adresse IP et le port de l'instance SLB dans un navigateur web, par exemple http://121.43.XXX.XX:8000. La page d'accueil Nginx affichant le message Welcome to nginx! apparaît, ce qui confirme que l'application fonctionne correctement.

Nettoyer les ressources

Cette rubrique utilise l'application app-slb dans la région Chine (Shenzhen) comme exemple pour expliquer comment dissocier une instance SLB et supprimer l'application.

  1. Pour supprimer toutes les ressources créées, exécutez la commande suivante dans le répertoire de votre projet :

    terraform destroy
  2. Sortie attendue :

    Destroy complete! Resources: 8 destroyed.

    Cette commande dissocie l'instance SLB, supprime l'application SAE et retire toutes les autres ressources créées dans ce tutoriel.

Exemple de code complet

Remarque

Exécutez l'exemple de code de cette rubrique via le lien suivant : Exécuter en un clic

# Configure the provider
provider "alicloud" {
  region = var.region_id
}
# Define variables
variable "region_id" {
  type    = string
  default = "cn-shenzhen"
}
variable "app_name" {
  description = "The name of the application."
  type        = string
  default     = "app-slb"
}
variable "image_url" {
  description = "The URL of the image."
  type        = string
  default     = "registry.cn-hangzhou.aliyuncs.com/google_containers/nginx-slim:0.9"
}
variable "namespace_id" {
  description = "The ID of the namespace."
  type        = string
  default     = "cn-shenzhen:demo"
}
variable "namespace_name" {
  description = "The name of the namespace."
  type        = string
  default     = "demo"
}
# Namespace
resource "alicloud_sae_namespace" "default" {
  namespace_description = var.namespace_description
  namespace_id          = var.namespace_id
  namespace_name        = var.namespace_name
}
# VPC
resource "alicloud_vpc" "default" {
  vpc_name   = var.name
  cidr_block = "10.4.0.0/16"
}
# VSwitch
resource "alicloud_vswitch" "default" {
  vswitch_name = var.name
  cidr_block   = "10.4.0.0/24"
  vpc_id       = alicloud_vpc.default.id
  zone_id      = var.zone_id
}
# Security group
resource "alicloud_security_group" "sg" {
  name        = var.name
  description = var.description
  vpc_id      = alicloud_vpc.default.id
}
resource "alicloud_security_group_rule" "sg_rule" {
  type              = "ingress"
  ip_protocol       = "tcp"
  nic_type          = "intranet"
  policy            = "accept"
  port_range        = var.port_range
  priority          = 1
  security_group_id = alicloud_security_group.sg.id
  cidr_ip           = var.cidr_ip
}
# Application configuration
resource "alicloud_sae_application" "manual" {
  app_name          = var.app_name
  app_description   = var.app_description
  deploy            = true
  image_url         = var.image_url
  namespace_id      = alicloud_sae_namespace.default.id
  vswitch_id        = alicloud_vswitch.default.id
  vpc_id            = alicloud_vpc.default.id
  security_group_id = alicloud_security_group.sg.id
  package_type      = var.package_type
  timezone          = "Asia/Beijing"
  replicas          = var.replicas
  cpu               = var.cpu
  memory            = var.memory
}
# SLB configuration
resource "alicloud_slb_load_balancer" "slb" {
  load_balancer_name = "prod"
  address_type       = "internet"
  load_balancer_spec = "slb.s2.small"
  vswitch_id         = alicloud_vswitch.default.id
}
resource "alicloud_sae_load_balancer_internet" "example" {
  app_id          = alicloud_sae_application.manual.id
  internet_slb_id = alicloud_slb_load_balancer.slb.id
  internet {
    protocol    = "HTTP"
    port        = var.port
    target_port = 80
  }
}
# Other variable definitions
variable "namespace_description" {
  description = "A description for the namespace."
  default     = "a namespace"
}
variable "name" {
  default     = "tf"
  description = "The name for the security group rule."
  type        = string
}
variable "description" {
  default     = "A description for the security group rule."
  description = "The description of the security group rule."
  type        = string
}
variable "port_range" {
  default     = "1/65535"
  description = "The port range for the security group rule."
  type        = string
}
variable "cidr_ip" {
  description = "The CIDR block used to create a new security group rule."
  type        = string
  default     = "0.0.0.0/0"
}
variable "zone_id" {
  description = "The ID of the availability zone."
  type        = string
  default     = "cn-shenzhen-a"
}
variable "app_description" {
  default     = "A description for the application, created by Terraform."
  description = "The description of the application."
  type        = string
}
variable "package_type" {
  default     = "Image"
  description = "The package type of the application."
  type        = string
}
variable "cpu" {
  default     = "500"
  description = "The CPU allocation for the application, in millicores."
  type        = string
}
variable "memory" {
  default     = "1024"
  description = "The memory allocation for the application, in MB."
  type        = string
}
variable "replicas" {
  default     = "1"
  description = "The number of application instances (replicas)."
  type        = string
}
variable "port" {
  description = "The listening port of the SLB instance."
  type        = string
  default     = "8000"
}
# Outputs
output "namespace_id" {
  value       = var.namespace_id
  description = "The ID of the namespace."
}
output "app_id" {
  description = "The ID of the application."
  value       = alicloud_sae_application.manual.id
}
output "app_name" {
  description = "The name of the application."
  value       = var.app_name
}
output "endpoint" {
  value = format("http://%s:%s", alicloud_slb_load_balancer.slb.address, var.port)
}

Documentation connexe