本文介绍如何使用Terraform创建专有网络,交换机以及NAT网关。

前提条件

在开始之前,请您确保完成以下操作:

操作步骤

  1. 创建专有网络和交换机。
    1. 创建terraform.tf文件 ,定义专有网络和交换机资源,文件内容如下。
      provider "alicloud" {
        configuration_source = "terraform-provider-alicloud/examples/vpc"
      }
      
      resource "alicloud_vpc" "main" {
        # VPC名称
        name       = "alicloud"
        # VPC地址块
        cidr_block = "10.1.0.0/21"
      }
      
      resource "alicloud_vswitch" "main" {
        # VPC ID
        vpc_id            = alicloud_vpc.main.id
        # 交换机地址块
        cidr_block        = "10.1.0.0/24"
        # 可用区
        availability_zone = "cn-hangzhou-b"
        # 资源依赖,会优先创建该依赖资源
        depends_on = [alicloud_vpc.main]
      }
    2. 运行terraform apply开始创建。出现类似下面的日志,说明创建成功。
      alicloud_vpc.main: Creating...
      alicloud_vpc.main: Creation complete after 6s [id=vpc-bp1ureoqifi1v1l87l2qt]
      alicloud_vswitch.main: Creating...
      alicloud_vswitch.main: Creation complete after 6s [id=vsw-bp17yxb3jsofbkaop7kxq]
      
      Apply complete! Resources: 2 added, 0 changed, 0 destroyed
    3. 运行terraform show查看已创建的专有和专有网络。
  2. 创建NAT网关。
    1. terraform.tf文件中增加以下内容:
      resource "alicloud_nat_gateway" "main" {
        vpc_id        = alicloud_vpc.main.id
        specification = "Small"
        name          = "from-tf-example"
      }
      
      resource "alicloud_eip" "foo" {
      }
      
      resource "alicloud_eip_association" "foo" {
        allocation_id = alicloud_eip.foo.id
        instance_id   = alicloud_nat_gateway.main.id
      }
    2. 运行terraform apply开始创建。出现下面的日志,说明创建成功。
      alicloud_eip.foo: Creating...
        bandwidth:            "" => "5"
        instance:             "" => "<computed>"
        instance_charge_type: "" => "PostPaid"
        internet_charge_type: "" => "PayByTraffic"
        ip_address:           "" => "<computed>"
        status:               "" => "<computed>"
      alicloud_nat_gateway.main: Creating...
        bandwidth_package_ids: "" => "<computed>"
        forward_table_ids:     "" => "<computed>"
        name:                  "" => "from-tf-example"
        snat_table_ids:        "" => "<computed>"
        specification:         "" => "Small"
        vpc_id:                "" => "vpc-bp1xhaa5nw4ad43m7wdai"
      alicloud_eip.foo: Creation complete after 2s (ID: eip-bp1y9pynihhurist6r1hk)
      alicloud_nat_gateway.main: Creation complete after 2s (ID: ngw-bp1wiycnrxk04vqnorzuo)
      alicloud_eip_association.foo: Creating...
        allocation_id: "" => "eip-bp1y9pynihhurist6r1hk"
        instance_id:   "" => "ngw-bp1wiycnrxk04vqnorzuo"
      alicloud_eip_association.foo: Creation complete after 6s (ID: eip-bp1y9pynihhurist6r1hk:ngw-bp1wiycnrxk04vqnorzuo)
      
      Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
    3. 运行terraform show查看已经创建的NAT网关。