# Deploy Event Subscription (VPC Event Source, EG Event Target)

## Application Scenario

Huawei Cloud EventGrid (EG) event subscription functionality supports automatically routing events generated by VPC (Virtual Private Cloud) to another EG event channel, implementing event forwarding and distribution between different EG channels. Through this integration approach, you can build complex event-driven architectures, pushing VPC network operation events (such as VPC creation, deletion, modification, etc.) to target EG channels in real-time for downstream consumers to process and analyze further.

This best practice is particularly suitable for scenarios requiring cross-region event forwarding, building event relay architectures, implementing VPC event and EG channel integration, such as multi-region event synchronization, event auditing and monitoring, complex event processing workflows, etc. This best practice will introduce how to use Terraform to automatically deploy a complete VPC to EG event subscription configuration, including VPC network, custom event channel, and event subscription creation.

## Related Resources/Data Sources

This best practice involves the following main resources and data sources:

### Data Sources

- [EventGrid Event Channels Query Data Source (data.huaweicloud\_eg\_event\_channels)](https://registry.terraform.io/providers/huaweicloud/huaweicloud/latest/docs/data-sources/eg_event_channels)

### Resources

- [VPC Resource (huaweicloud\_vpc)](https://registry.terraform.io/providers/huaweicloud/huaweicloud/latest/docs/resources/vpc)
- [VPC Subnet Resource (huaweicloud\_vpc\_subnet)](https://registry.terraform.io/providers/huaweicloud/huaweicloud/latest/docs/resources/vpc_subnet)
- [Custom Event Channel Resource (huaweicloud\_eg\_custom\_event\_channel)](https://registry.terraform.io/providers/huaweicloud/huaweicloud/latest/docs/resources/eg_custom_event_channel)
- [Event Subscription Resource (huaweicloud\_eg\_event\_subscription)](https://registry.terraform.io/providers/huaweicloud/huaweicloud/latest/docs/resources/eg_event_subscription)
- [Time Sleep Resource (time\_sleep)](https://registry.terraform.io/providers/hashicorp/time/latest/docs/resources/sleep)

### Resource/Data Source Dependencies

```
data.huaweicloud_eg_event_channels
    └── huaweicloud_eg_event_subscription

huaweicloud_vpc
    └── huaweicloud_vpc_subnet

huaweicloud_eg_custom_event_channel
    ├── time_sleep
    └── huaweicloud_eg_event_subscription

time_sleep.test
    └── huaweicloud_eg_event_subscription
```

## Operation Steps

### 1. Script Preparation

Prepare the TF file (e.g., main.tf) in the specified workspace for writing the current best practice script, ensuring that it (or other TF files in the same directory) contains the provider version declaration and Huawei Cloud authentication information required for deploying resources. Refer to the "Preparation Before Deploying Huawei Cloud Resources" document for configuration introduction.

### 2. Create VPC Network

Add the following script to the TF file (e.g., main.tf) to instruct Terraform to create a VPC resource:

```hcl
# Variable definitions for VPC
variable "vpc_name" {
  description = "The name of the VPC"
  type        = string
}

variable "vpc_cidr" {
  description = "The CIDR block of the VPC"
  type        = string
  default     = "172.16.0.0/16"
}

# Create a VPC resource under the specified region (if the region parameter is omitted, it defaults to the region specified in the current provider block)
resource "huaweicloud_vpc" "test" {
  name = var.vpc_name
  cidr = var.vpc_cidr
}
```

**Parameter Description**:

- **name**: VPC name, assigned by referencing the input variable vpc\_name
- **cidr**: VPC CIDR block, assigned by referencing the input variable vpc\_cidr, default value is "172.16.0.0/16"

### 3. Create VPC Subnet

Add the following script to the TF file to instruct Terraform to create a VPC subnet resource:

```hcl
# Variable definitions for subnet
variable "subnet_name" {
  description = "The name of the subnet"
  type        = string
}

variable "subnet_cidr" {
  description = "The CIDR block of the subnet"
  type        = string
  default     = "172.16.10.0/24"
}

variable "subnet_gateway" {
  description = "The gateway IP address of the subnet"
  type        = string
  default     = "172.16.10.1"
}

# Create a VPC subnet resource under the specified region (if the region parameter is omitted, it defaults to the region specified in the current provider block)
resource "huaweicloud_vpc_subnet" "test" {
  vpc_id     = huaweicloud_vpc.test.id
  name       = var.subnet_name
  cidr       = var.subnet_cidr
  gateway_ip = var.subnet_gateway
}
```

**Parameter Description**:

- **vpc\_id**: VPC ID that the subnet belongs to, referencing the ID of the VPC resource created earlier
- **name**: Subnet name, assigned by referencing the input variable subnet\_name
- **cidr**: Subnet CIDR block, assigned by referencing the input variable subnet\_cidr, default value is "172.16.10.0/24"
- **gateway\_ip**: Subnet gateway IP address, assigned by referencing the input variable subnet\_gateway, default value is "172.16.10.1"

### 4. Create Custom Event Channel

Add the following script to the TF file to instruct Terraform to create a custom event channel resource:

```hcl
# Variable definitions for custom event channel
variable "channel_name" {
  description = "The name of the custom event channel"
  type        = string
}

# Create a custom event channel resource under the specified region (if the region parameter is omitted, it defaults to the region specified in the current provider block)
resource "huaweicloud_eg_custom_event_channel" "test" {
  name = var.channel_name
}
```

**Parameter Description**:

- **name**: Custom event channel name, assigned by referencing the input variable channel\_name

### 5. Query EventGrid Event Channel Information

Add the following script to the TF file to instruct Terraform to query EventGrid event channel information:

```hcl
# Get all EventGrid event channel information that meets specific conditions under the specified region (if the region parameter is omitted, it defaults to the region specified in the current provider block), used to create event subscriptions
data "huaweicloud_eg_event_channels" "test" {
  provider_type = "OFFICIAL"
  name          = "default"
}
```

**Parameter Description**:

- **provider\_type**: Provider type, set to "OFFICIAL" for official provider
- **name**: Channel name, set to "default" for default channel

### 6. Create Time Sleep Resource

Add the following script to the TF file to instruct Terraform to create a time sleep resource:

```hcl
# Create a time sleep resource under the specified region (if the region parameter is omitted, it defaults to the region specified in the current provider block), used to wait for EG channel to be ready
resource "time_sleep" "test" {
  create_duration = "3s"

  depends_on = [
    huaweicloud_eg_custom_event_channel.test
  ]
}
```

**Parameter Description**:

- **create\_duration**: Wait time, set to "3s" to wait for 3 seconds
- **depends\_on**: Explicit dependency relationship, ensuring custom event channel exists before time sleep resource creation

### 7. Create Event Subscription Resource

Add the following script to the TF file to instruct Terraform to create an event subscription resource:

```hcl
# Variable definitions for event subscription
variable "sources_name" {
  description = "The name of the event source"
  type        = string
  default     = "HC.VPC"
}

variable "sources_provider_type" {
  description = "The provider type of the event source"
  type        = string
  default     = "OFFICIAL"
}

variable "source_op" {
  description = "The operation of the source"
  type        = string
  default     = "StringIn"
}

variable "type_op" {
  description = "The operation of the type"
  type        = string
  default     = "StringIn"
}

variable "subscription_source_values" {
  description = "The event types to be subscribed from VPC service"
  type        = list(string)
  default     = [
    "VPC:CloudTrace:ApiCall",
    "VPC:CloudTrace:ConsoleAction",
    "VPC:CloudTrace:SystemAction"
  ]
}

variable "targets_name" {
  description = "The name of the event target"
  type        = string
  default     = "HC.EG"
}

variable "targets_provider_type" {
  description = "The type of the event target"
  type        = string
  default     = "OFFICIAL"
}

variable "detail_name" {
  description = "The name(key) of the target detail configuration"
  type        = string
  default     = "eg_detail"
}

variable "transform" {
  description = "The transform configuration of the event target, in JSON format"
  type        = map(string)
  default     = {
    "type" : "ORIGINAL",
  }
}

variable "agency_name" {
  description = "The name of the agency"
  type        = string
  default     = "EG_AGENCY"
}

variable "target_project_id" {
  description = "The ID of the target project"
  type        = string
}

variable "target_region_name" {
  description = "The name of the target region"
  type        = string
  default     = ""
}

# Create an event subscription resource under the specified region (if the region parameter is omitted, it defaults to the region specified in the current provider block)
resource "huaweicloud_eg_event_subscription" "test" {
  channel_id = try(data.huaweicloud_eg_event_channels.test.channels[0].id, "")
  name       = try(data.huaweicloud_eg_event_channels.test.channels[0].name, "")

  sources {
    name          = var.sources_name
    provider_type = var.sources_provider_type

    filter_rule = jsonencode({
      "source" : [
        {
          "op" : var.source_op,
          "values" : ["HC.VPC"]
        }
      ],
      "type" : [
        {
          "op" : var.type_op,
          "values" : var.subscription_source_values
        }
      ],
    })
  }

  targets {
    name          = var.targets_name
    provider_type = var.targets_provider_type
    detail_name   = var.detail_name
    transform     = jsonencode(var.transform)
    detail        = jsonencode({
      "agency_name" : var.agency_name
      "target_channel_id" : huaweicloud_eg_custom_event_channel.test.id
      "target_project_id" : var.target_project_id
      "target_region" : var.target_region_name != "" ? var.target_region_name : var.region_name
    })
  }

  lifecycle {
    ignore_changes = [
      sources, targets
    ]
  }

  depends_on = [
    time_sleep.test
  ]
}
```

**Parameter Description**:

- **channel\_id**: Event channel ID, using the queried default event channel ID
- **name**: Event subscription name, using the queried default event channel name
- **sources**: Event source configuration block
  - **name**: Event source name, assigned by referencing the input variable sources\_name, default value is "HC.VPC"
  - **provider\_type**: Event source provider type, assigned by referencing the input variable sources\_provider\_type, default value is "OFFICIAL"
  - **filter\_rule**: Filter rule, configuring event source filter conditions in JSON format, including source and type filtering
- **targets**: Event target configuration block
  - **name**: Event target name, assigned by referencing the input variable targets\_name, default value is "HC.EG"
  - **provider\_type**: Event target provider type, assigned by referencing the input variable targets\_provider\_type, default value is "OFFICIAL"
  - **detail\_name**: Target detail configuration name, assigned by referencing the input variable detail\_name, default value is "eg\_detail"
  - **transform**: Transform configuration, configuring event transformation rules in JSON format, assigned by referencing the input variable transform, default type is "ORIGINAL"
  - **detail**: Target detail configuration, configuring target EG channel information in JSON format, including agency name, target channel ID, target project ID, and target region
- **lifecycle.ignore\_changes**: Lifecycle management, ignoring changes to sources and targets to avoid rebuilding subscriptions
- **depends\_on**: Explicit dependency relationship, ensuring time sleep resource is completed before event subscription creation

### 8. Preset Input Parameters Required for Resource Deployment (Optional)

In this practice, some resources and data sources use input variables to assign values to configuration content. These input parameters need to be manually entered during subsequent deployments. At the same time, Terraform provides a method to preset these configurations through `.tfvars` files, which can avoid repeated input during each execution.

Create a `terraform.tfvars` file in the working directory with the following example content:

```hcl
# Huawei Cloud authentication information
region_name = "cn-north-4"
access_key  = "your-access-key"
secret_key  = "your-secret-key"

# VPC network configuration
vpc_name    = "tf_test_vpc"
subnet_name = "tf_test_subnet"

# Custom event channel configuration
channel_name = "tf_test_channel"

# Target project configuration
target_project_id = "your target project ID"
```

**Usage**:

1. Save the above content as `terraform.tfvars` file in the working directory (this file name allows users to automatically import the content of this `tfvars` file when executing terraform commands; for other names, `.auto` needs to be added before tfvars, such as `variables.auto.tfvars`)
2. Modify parameter values as needed
3. When executing `terraform plan` or `terraform apply`, Terraform will automatically read the variable values from this file

In addition to using `terraform.tfvars` file, variable values can also be set in the following ways:

1. Command line parameters: `terraform apply -var="vpc_name=my-vpc" -var="channel_name=my-channel"`
2. Environment variables: `export TF_VAR_vpc_name=my-vpc`
3. Custom named variable files: `terraform apply -var-file="custom.tfvars"`

> Note: If the same variable is set in multiple ways, Terraform will use the variable value according to the following priority: command line parameters > variable files > environment variables > default values.

### 9. Initialize and Apply Terraform Configuration

After completing the above script configuration, execute the following steps to create resources:

1. Run `terraform init` to initialize the environment
2. Run `terraform plan` to view the resource creation plan
3. After confirming the resource plan is correct, run `terraform apply` to start creating event subscription (VPC event source, EG event target)
4. Run `terraform show` to view the details of the created event subscription (VPC event source, EG event target)

## Reference Information

- [Huawei Cloud EventGrid Product Documentation](https://support.huaweicloud.com/eg/index.html)
- [Huawei Cloud Provider Documentation](https://registry.terraform.io/providers/huaweicloud/huaweicloud/latest/docs)
- [Best Practice Source Code Reference For EventGrid Event Subscription (VPC Event Source, EG Event Target)](https://github.com/huaweicloud/terraform-provider-huaweicloud/tree/master/examples/eg/event-subscriptions/vpc-to-eg)