Use Terraform to create an access control policy in a specific policy group for a VPC firewall

Updated at:

Use the alicloud_cloud_firewall_vpc_firewall_control_policy Terraform resource to create an access control policy in a specific policy group for a VPC firewall.

Run the sample code in this topic directly in Terraform Explorer.

Prerequisites

Before you begin, ensure that you have:

  • A RAM user with an AccessKey pair — avoid using your Alibaba Cloud root account, since compromised root account credentials expose all resources in the account. See Create a RAM user and Create an AccessKey pair

  • The following permissions granted to your RAM user. See Grant permissions to RAM users

    {
        "Version": "1",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "yundun-cloudfirewall:*",
                    "yundun-ndr:*",
                    "vpc:CreateVpc",
                    "vpc:DeleteVpc",
                    "vpc:DescribeVpcs",
                    "vpc:CreateVSwitch",
                    "vpc:DeleteVSwitch",
                    "vpc:DescribeVSwitches",
                    "vpc:CreateRouteEntry",
                    "vpc:DeleteRouteEntry",
                    "vpc:DescribeRouteEntries",
                    "vpc:CreateVpcPeerConnection",
                    "vpc:DeleteVpcPeerConnection",
                    "vpc:DescribeVpcPeerConnections",
                    "cloudfirewall:CreateVpcFirewall",
                    "cloudfirewall:DeleteVpcFirewall",
                    "cloudfirewall:DescribeVpcFirewalls"
                ],
                "Resource": "*"
            }
        ]
    }
  • A Terraform environment. Choose one of the following options:

Resources used

alicloud_cloud_firewall_vpc_firewall_control_policy: Add access control policy。

Create an access control policy

Step 1: Create main.tf

Create a working directory, then create a main.tf file in that directory. The following sample code sets up the full infrastructure — two VPCs connected by a VPC peering connection, a VPC firewall, and the access control policy.

variable "region" {
  default = "cn-heyuan"
}
provider "alicloud" {
  region = var.region
}
# Obtain the ID of the current Alibaba Cloud account.
data "alicloud_account" "current" {
}
# Create VPC 1.
resource "alicloud_vpc" "vpc" {
  vpc_name   = "dd-tf-vpc-01"
  cidr_block = "192.168.0.0/16"
}
# Create VPC 2.
resource "alicloud_vpc" "vpc1" {
  vpc_name   = "dd-tf-vpc-02"
  cidr_block = "172.16.0.0/12"
}
# Create a vSwitch and allocate the CIDR block 192.168.10.0/24 to the vSwitch.
resource "alicloud_vswitch" "vsw" {
  vpc_id       = alicloud_vpc.vpc.id
  cidr_block   = "192.168.10.0/24"
  zone_id      = "cn-heyuan-a"
  vswitch_name = "dd-tf-vpc-01-example-1"
}
# Create a vSwitch and allocate the CIDR block 192.168.20.0/24 to the vSwitch.
resource "alicloud_vswitch" "vsw1" {
  vpc_id       = alicloud_vpc.vpc.id
  cidr_block   = "192.168.20.0/24"
  zone_id      = "cn-heyuan-b"
  vswitch_name = "dd-tf-vpc-01-example-2"
}
# Create a vSwitch and allocate the CIDR block 172.16.10.0/24 to the vSwitch.
resource "alicloud_vswitch" "vsw2" {
  vpc_id       = alicloud_vpc.vpc1.id
  cidr_block   = "172.16.10.0/24"
  zone_id      = "cn-heyuan-a"
  vswitch_name = "dd-tf-vpc-02-example-11"
}
# Create a vSwitch and allocate the CIDR block 172.16.20.0/24 to the vSwitch.
resource "alicloud_vswitch" "vsw3" {
  vpc_id       = alicloud_vpc.vpc1.id
  cidr_block   = "172.16.20.0/24"
  zone_id      = "cn-heyuan-b"
  vswitch_name = "dd-tf-vpc-02-example-22"
}
# Create a VPC peering connection.
resource "alicloud_vpc_peer_connection" "default" {
  peer_connection_name = "terraform-example-vpc-peer-connection"
  vpc_id               = alicloud_vpc.vpc.id
  accepting_ali_uid    = data.alicloud_account.current.id
  # If both VPCs are in the same region, use the same region ID for both.
  accepting_region_id  = "cn-heyuan"
  accepting_vpc_id     = alicloud_vpc.vpc1.id
  description          = "terraform-example"
  force_delete         = true
}
# Accept the VPC peering connection.
resource "alicloud_vpc_peer_connection_accepter" "default" {
  instance_id = alicloud_vpc_peer_connection.default.id
}
# Configure a route for VPC-A.
resource "alicloud_route_entry" "foo" {
  route_table_id        = alicloud_vpc.vpc.route_table_id
  destination_cidrblock = "1.2.3.4/32"
  nexthop_type          = "VpcPeer"
  nexthop_id            = alicloud_vpc_peer_connection.default.id
}
# Configure a route for VPC-B.
resource "alicloud_route_entry" "foo1" {
  route_table_id        = alicloud_vpc.vpc1.route_table_id
  destination_cidrblock = "4.3.X.X/32"
  nexthop_type          = "VpcPeer"
  nexthop_id            = alicloud_vpc_peer_connection.default.id
}
# Wait for routing to propagate before creating the VPC firewall.
resource "time_sleep" "wait_before_firewall" {
  depends_on = [
    alicloud_route_entry.foo,
    alicloud_route_entry.foo1
  ]
  create_duration = "720s" # Adjust based on your network propagation time.
}
resource "null_resource" "wait_for_firewall" {
  provisioner "local-exec" {
    command = "echo waiting for firewall to be ready"
  }
  depends_on = [time_sleep.wait_before_firewall]
}
# Create the VPC firewall over the VPC peering connection.
resource "alicloud_cloud_firewall_vpc_firewall" "default" {
  depends_on = [
    null_resource.wait_for_firewall
  ]
  timeouts {
    create = "30m"
  }
  vpc_firewall_name = "tf-test"
  member_uid        = data.alicloud_account.current.id
  local_vpc {
    vpc_id    = alicloud_vpc.vpc.id
    region_no = "cn-heyuan"
    local_vpc_cidr_table_list {
      local_route_table_id = alicloud_vpc.vpc.route_table_id
      local_route_entry_list {
        local_next_hop_instance_id = alicloud_vpc_peer_connection.default.id
        local_destination_cidr     = alicloud_route_entry.foo.destination_cidrblock
      }
    }
  }
  peer_vpc {
    vpc_id    = alicloud_vpc.vpc1.id
    region_no = "cn-heyuan"
    peer_vpc_cidr_table_list {
      peer_route_table_id = alicloud_vpc.vpc1.route_table_id
      peer_route_entry_list {
        peer_destination_cidr      = alicloud_route_entry.foo1.destination_cidrblock
        peer_next_hop_instance_id  = alicloud_vpc_peer_connection.default.id
      }
    }
  }
  # open: enable the VPC firewall immediately after creation.
  # close: create the VPC firewall without enabling it.
  status = "open"
}
# Create the access control policy.
resource "alicloud_cloud_firewall_vpc_firewall_control_policy" "default" {
  vpc_firewall_id  = alicloud_cloud_firewall_vpc_firewall.default.id
  member_uid       = data.alicloud_account.current.id
  order            = "1"           # Priority: 1 is highest. Lower values take precedence.
  acl_action       = "accept"      # Valid values: accept, drop, log.
  proto            = "TCP"         # Valid values: ANY, TCP, UDP, ICMP.
  source           = "0.0.0.0/0"
  source_type      = "net"         # Valid values: net, group.
  destination      = "0.0.0.0/0"
  destination_type = "net"         # Valid values: net, group.
  dest_port        = "80/88"       # Destination port range.
  dest_port_type   = "port"        # Valid values: port, group.
  application_name = "ANY"
  lang             = "zh"          # Language for request/response content. Valid values: zh, en.
  description      = "Created_by_Terraform"
  release          = true          # true: enable the policy after creation (default).
}

Step 2: Initialize Terraform

terraform init

The following output confirms a successful initialization:

Initializing the backend...

Initializing provider plugins...
- Finding latest version of hashicorp/alicloud...
- Using hashicorp/alicloud v1.231.0 from the shared cache directory

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

╷
│ Warning: Additional provider information from registry
│
│ The remote registry returned warnings for registry.terraform.io/hashicorp/alicloud:
│ - For users on Terraform 0.13 or greater, this provider has moved to aliyun/alicloud. Please update your source in required_providers.
╵

╷
│ Warning: Incomplete lock file information for providers
│
│ Due to your customized provider installation methods, Terraform was forced to calculate lock file checksums locally for the following providers:
│   - hashicorp/alicloud
│
│ The current .terraform.lock.hcl file only includes checksums for linux_amd64, so Terraform running on another platform will fail to install these providers.
│
│ To calculate additional checksums for another platform, run:
│   terraform providers lock -platform=linux_amd64
│ (where linux_amd64 is the platform to generate)
╵

Terraform has been successfully initialized!

Step 3: Preview changes

terraform plan

Step 4: Apply the configuration

terraform apply

When prompted, type yes and press Enter. The following output confirms the policy was created:

alicloud_cloud_firewall_vpc_firewall_control_policy.default: Creating...
alicloud_cloud_firewall_vpc_firewall_control_policy.default: Creation complete after 0s [id=vfw-c7536567ab694fb1a59f:ca14e184-15dc-4a68-b0d8-fb71a15ff***]

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

Step 5: Verify the result

Run terraform show

terraform show

The output displays the full state of the created policy:

# alicloud_cloud_firewall_vpc_firewall_control_policy.default:
resource "alicloud_cloud_firewall_vpc_firewall_control_policy" "default" {
    acl_action              = "accept"
    acl_uuid                = "ba164e52-acd2-4899-bf72-6816b13a****"
    application_id          = "0"
    application_name        = "ANY"
    description             = "Created_by_Terraform"
    dest_port               = "80/88"
    dest_port_group_ports   = []
    dest_port_type          = "port"
    destination             = "0.X.X.0/0"
    destination_group_cidrs = []
    destination_type        = "net"
    hit_times               = 0
    id                      = "vfw-d7b8ce273791475b****:ba164e52-acd2-4899-bf72-6816b13a****"
    lang                    = "zh"
    member_uid              = "1415189284827****"
    order                   = 1
    proto                   = "TCP"
    release                 = true
    source                  = "0.X.X.0/0"
    source_group_cidrs      = []
    source_type             = "net"
    vpc_firewall_id         = "vfw-d7b8ce273791475b****"
}

Verify in the console

Log in to the Cloud Firewall console and go to Cloud Firewall consoleAccess Control > VPC Border. Confirm the policy appears in the list.

image

Argument reference

Required arguments

Argument

Type

Description

vpc_firewall_id

String

The ID of the VPC firewall to which the policy is applied.

acl_action

String

The action applied to matching traffic. Valid values: accept, drop, log.

proto

String

The protocol type. Valid values: ANY, TCP, UDP, ICMP.

source

String

The source address. If source_type is net, enter a CIDR block.

source_type

String

The type of the source address. Valid values: net, group.

destination

String

The destination address. If destination_type is net, enter a CIDR block.

destination_type

String

The type of the destination address. Valid values: net, group.

application_name

String

The application type. Use ANY to match all application types.

order

String

The priority of the policy. Starts from 1. A lower value means higher priority.

lang

String

The language for request and response content. Valid values: zh, en.

Optional arguments

Argument

Type

Description

dest_port

String

The destination port or port range (for example, 80/88). Required when dest_port_type is port.

dest_port_type

String

The type of the destination port. Valid values: port, group.

description

String

A description of the policy.

member_uid

String

The ID of the Alibaba Cloud account. Defaults to the current account.

release

Boolean

Specifies whether to enable the policy after creation. Default: true.

Attributes reference

The following attributes are exported after the policy is created:

Attribute

Description

id

The unique ID of the policy, in the format <vpc_firewall_id>:<acl_uuid>.

acl_uuid

The UUID of the access control policy.

application_id

The application ID assigned by the system.

hit_times

The number of times the policy has been matched.

dest_port_group_ports

The ports in the destination port group. Returned when dest_port_type is group.

destination_group_cidrs

The CIDR blocks in the destination address group. Returned when destination_type is group.

source_group_cidrs

The CIDR blocks in the source address group. Returned when source_type is group.

destination_group_type

The type of the destination address group.

source_group_type

The type of the source address group.

Timeouts

The timeouts block lets you specify how long Terraform waits for the underlying VPC firewall to become ready before creating the policy. The following timeout is supported:

Operation

Default

Description

create

30 minutes

The time to wait when creating the VPC firewall (alicloud_cloud_firewall_vpc_firewall).

The time_sleep resource in the sample code adds a 720-second (12-minute) wait to allow routing changes to propagate before the VPC firewall is created. Adjust create_duration based on your network environment.

Import an existing policy

To bring an existing access control policy under Terraform management, use terraform import with the policy's composite ID in the format <vpc_firewall_id>:<acl_uuid>:

terraform import alicloud_cloud_firewall_vpc_firewall_control_policy.default <vpc_firewall_id>:<acl_uuid>

Example:

terraform import alicloud_cloud_firewall_vpc_firewall_control_policy.default vfw-d7b8ce273791475b****:ba164e52-acd2-4899-bf72-6816b13a****

Get the vpc_firewall_id and acl_uuid from the Cloud Firewall console or by running terraform show on an existing state.

Release resources

To delete the resources created in this topic, run:

terraform destroy

For details on the terraform destroy command, see Common commands.