This topic describes how to automate the deployment of EventBridge resources based on Infrastructure as Code (IaC). This helps reduce workload in managing a large number of cloud services.
Background information
IaC is a practical method that you can use to configure and manage infrastructure, such as virtual machines (VMs) and networks, by using code. This method uses the code-based and version-based management mode to replace the traditional manual management mode. This not only improves the management efficiency, but also prevents accidental operations caused by manual management. In the process of IaC, developers use code to describe the configuration and changes of infrastructure, then run the code to configure and change the infrastructure. Cloud services, such as VMs and networks, can be deployed within several minutes. This greatly shortens the deployment duration, ensures the configuration consistency of multiple environments, reduces manual operations, and minimizes errors.
HashiCorp Terraform is a tool that you can use to automate the orchestration of IT infrastructure. As one of the mainstream IaC tools, Terraform provides powerful capabilities to automate the management of infrastructure. The easy-to-use CLI of Terraform allows you to deploy configuration files on Alibaba Cloud or in other supported clouds and control the versions of the configuration files. Most Alibaba Cloud services, including EventBridge, support Terraform. This simplifies the deployment of infrastructure across multiple clouds. For more information, see What is Terraform?
This topic describes how to use Terraform to automate the deployment of infrastructure based on IaC.
Before you start
An Alibaba Cloud account has full permissions on all resources that belong to this account. If the credentials of an Alibaba Cloud account are leaked, security risks may arise. We recommend that you use Resource Access Management (RAM) users to manage resources. When you create a RAM user, you need to create an AccessKey pair for the RAM user. For more information, see Create a RAM user and Create an AccessKey pair.
Attach the following policy to the RAM user that you use to run commands in Terraform. The policy includes the minimum permissions required to run commands in Terraform. For more information, see the "Create a custom policy on the JSON tab" section of the Create custom policies topic.
The policy allows you to use the RAM user to manage resources in EventBridge and Function Compute.
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": [ "eventbridge:CreateEventBus", "eventbridge:DeleteEventBus", "eventbridge:DescribeEventBus", "eventbridge:ListEventBuses", "eventbridge:PutRule", "eventbridge:DeleteRule", "eventbridge:DescribeRule", "eventbridge:ListRules", "eventbridge:PutTargets", "eventbridge:RemoveTargets", "eventbridge:ListTargetsByRule", "eventbridge:PutEvents", "eventbridge:PutPermission", "eventbridge:RemovePermission", "eventbridge:CreateEventSource", "eventbridge:DeleteEventSource", "eventbridge:DescribeEventSource", "eventbridge:ListEventSources" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "ram:PassRole" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "fc:CreateService", "fc:DeleteService", "fc:UpdateService", "fc:DescribeService", "fc:ListServices", "fc:CreateFunction", "fc:DeleteFunction", "fc:UpdateFunction", "fc:InvokeFunction", "fc:DescribeFunction", "fc:ListFunctions" ], "Resource": "*" } ] }Prepare the runtime environment for Terraform by using one of the following methods:
Use Terraform in Terraform Explorer: Alibaba Cloud provides Terraform Explorer, an online runtime environment for Terraform. You can use Terraform after you log on to Terraform Explorer without the need to install Terraform. This method is suitable for scenarios in which you want to use and debug Terraform in a fast and convenient manner at no additional costs.
Use Terraform in Cloud Shell: Terraform is preinstalled in Cloud Shell, and identity credentials are configured. You can run Terraform commands in Cloud Shell. This method is suitable for scenarios in which you want to use and debug Terraform in a fast and convenient manner at low costs.
Install and configure Terraform on your on-premises machine: This method is suitable for scenarios in which network connections are unstable or a custom development environment is required.
Required resources
alicloud_event_bridge_rule: allows you to create rules in EventBridge to filter events and then send the filtered events to the specified event targets, such as Function Compute and DingTalk chatbots.
You can run the sample code with a few clicks.
Use a custom event bus to trigger Function Compute
If you want events generated by your application to be processed by Function Compute, you can configure a custom event source and then specify Function Compute as the event target in the EventBridge console. In the following example, Terraform, instead of the EventBridge console and the Function Compute console, is used to deploy EventBridge and Function Compute resources.
Create a file named 2_trigger_function.tf to declare a custom event bus, a custom event source, a Function Compute service, a Function Compute function, and an event rule that is used to filter events from the custom event source.
# Define the variable. variable "region_id" { type = string default = "cn-shenzhen" } # # Specify Alibaba Cloud as the provider. provider "alicloud" { region = var.region_id } # Obtain the information about the current account. data "alicloud_caller_identity" "current" {} # Create a custom event bus. resource "alicloud_event_bridge_event_bus" "demo_event_bus" { event_bus_name = "demo_event_yiyi" description = "This is a demo event bus." } # Create a custom event source. resource "alicloud_event_bridge_event_source" "demo_event_source" { event_bus_name = alicloud_event_bridge_event_bus.demo_event_bus.event_bus_name event_source_name = "demo_event_source_yiyi" description = "This is a demo event source." linked_external_source = false } # Create a Function Compute service. resource "alicloud_fc_service" "fc_service" { name = "eb-fc-service" description = "This service handles events from EventBridge." publish = true } # Automatically generates a Python script file. resource "local_file" "python_script" { content = <<EOF # -*- coding: utf-8 -*- import logging def handler(event, context): logger = logging.getLogger() logger.info('Event: ' + str(event)) return str(event) EOF filename = "${path.module}/src/index.py" } # Compress the generated Python script file into a ZIP package. data "archive_file" "code" { type = "zip" source_dir = "${path.module}/src" output_path = "${path.module}/code.zip" depends_on = [local_file.python_script] } # Create an Object Storage Service (OSS) bucket. resource "alicloud_oss_bucket" "code_bucket" { bucket = "fc-code-bucket-${random_string.random_suffix.result}" } # Generate a random string as the suffix of the OSS bucket name to ensure its uniqueness. resource "random_string" "random_suffix" { length = 8 special = false upper = false } # Upload the ZIP package to OSS. resource "alicloud_oss_bucket_object" "function_code" { bucket = alicloud_oss_bucket.code_bucket.bucket key = "index.py.zip" source = data.archive_file.code.output_path } # Use the code in OSS to create a Function Compute function. resource "alicloud_fc_function" "fc_function" { service = alicloud_fc_service.fc_service.name name = "eb-fc-function" description = "This function executes based on EventBridge rules." oss_bucket = alicloud_oss_bucket.code_bucket.bucket oss_key = alicloud_oss_bucket_object.function_code.key memory_size = 128 runtime = "python3" handler = "index.handler" } # Create an event rule in EventBridge. resource "alicloud_event_bridge_rule" "demo_rule" { event_bus_name = alicloud_event_bridge_event_bus.demo_event_bus.event_bus_name rule_name = "demo_rule" description = "Rule for triggering Function Compute on events." filter_pattern = jsonencode({ "source" : [alicloud_event_bridge_event_source.demo_event_source.id] }) lifecycle { ignore_changes = [ targets ] } targets { target_id = "demo-fc-target" type = "acs.fc.function" endpoint = "acs:fc:${var.region_id}:${data.alicloud_caller_identity.current.account_id}:services/${alicloud_fc_service.fc_service.name}.LATEST/functions/${alicloud_fc_function.fc_function.name}" param_list { resource_key = "serviceName" form = "CONSTANT" value = alicloud_fc_service.fc_service.name } param_list { resource_key = "functionName" form = "CONSTANT" value = alicloud_fc_function.fc_function.name } param_list { resource_key = "Qualifier" form = "CONSTANT" value = "LATEST" } param_list { resource_key = "Body" form = "ORIGINAL" } } }Use Terraform to create the resources that are declared in the 2_trigger_function.tf file.
Run the terraform init command to initialize Terraform. The following output indicates that the initialization is successful:

Run the terraform plan command to preview the changes. In the returned output, you can preview the resources to be created.

Run the terraform apply command to apply the changes to your application. During command execution, follow the instructions to type
yesand press the Enter key. Wait until the command is run. If the following information is returned, the resources are created.
Run the terraform show command
Run the following command to query the details of the resources created by using Terraform:
terraform show
Check whether the custom event bus and custom event source are created
Check whether the custom event bus and custom event source are created.
Log on to the EventBridge console. In the left-side navigation pane, click Event Buses.
In the top navigation bar, select the region where the resources were created.
On the Event Buses page, find and click demo_event_yiyi.
In the left-side navigation pane, click Event Sources. On the Event Sources page, find and click demo_event_yiyi to view the details.
Check whether the Function Compute service and function are created.
Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
In the top navigation bar, select the region where the resources were created.
On the Services page, find and click eb-fc-service to view the details.
Trigger an event.
Log on to the EventBridge console. In the left-side navigation pane, click Event Buses.
In the top navigation bar, select the region where the resources were created.
On the Event Buses page, find and click demo_event_yiyi.
In the upper-right corner of the Overview page, click Publish Event. In the Publish Event to Custom Event Bus demo_event_yiyi panel, select demo_event_yiyi from the Custom Event Source drop-down list and click OK.
View event details.
In the left-side navigation pane of the demo_event_bus page, click Event Tracking.
Find the published event and click Event Trace in the Operations column. In the Event Trace dialog box, check whether the event is delivered to the eb-fc-function function.
Delete created resources
In this example, resources are stopped and then deleted.
Run the following command in the project directory to execute the configuration file:
terraform destroyExpected results:
