Unregister your appliance from Network Security

To unregister your Network Security virtual appliance from the Network Security management interface at the same time that the instance is deleted from AWS, create the following lambda function and CloudWatch rule in the AWS management console.

NOTE: To proceed, you must have permission to create a lambda function and CloudWatch rules, as well as be able to view CloudWatch logs.

Before you begin, note the following information needed to unregister the Network Security instance or instances:

  • Instance IDs
  • VPC ID
  • Subnet ID
  • Security Group names
  • Trend Micro Cloud One API key
  • HA monitoring IAM role

Create the lambda function

  1. From the AWS Management Console, navigate to the Lambda Dashboard and select Functions in the navigation.

  2. Click Create function.

  3. Select Author from scratch, and then enter the following parameters:

  4. Function name: Enter a descriptive name, like terminate_unregister_lambda1.

  5. Runtime: Select Python 3.8.

  6. Permissions: Under Choose or create an execution role, select Use an existing role, and then choose the CloudWatch_logs role you previously created from the drop down menu.

    NOTE: If you do not have this role, create it before proceeding by following these steps to create an IAM policy and role.

  7. Click Create function.

  8. In the Function code section, under Code entry type, select Edit code inline.

  9. Copy and paste the following function code in the text field, replacing <Region> with your Trend Micro Cloud One account's region and <API key> with your Trend Micro Cloud One API key:

    import json
    import urllib3
    region = "<Region>" # Trend Micro Cloud One region, for example: "us-1"
    api_key = "<API key>" # Trend Micro Cloud One API Key
    host = f"network.{region}.cloudone.trendmicro.com"
    api_version = "v1"
    def lambda_handler(event, context):
        if event is not None and "detail" in event:
            detail = event["detail"]
            instance = detail["instance-id"]
            url = f"https://{host}/api/appliances/search"
            payload = {
                "searchCriteria": [
                        "stringTest": "equal",
                        "stringValue": instance,
                        "fieldName": "instanceId",
            headers = {
                "Content-Type": "application/json",
                "Authorization": "ApiKey " + api_key,
                "api-version": api_version,
            http = urllib3.PoolManager()
            response = http.request("POST", url, headers=headers, body=json.dumps(payload))
            print(f"post/search instanceId:{instance}, rsp.code:{response.status}")
            if response.status == 200:
                data = json.loads(response.data)
                if "appliances" in data:
                    appliances = data["appliances"]
                    if len(appliances) == 1:
                        appliance = appliances[0]
                        if "ID" in appliance:
                            appliance_id = appliance["ID"]
                            print(f"resp - instanceId:{instance}, id:{appliance_id}")
                            url = f"https://{host}/api/appliances/{appliance_id}"
                            payload = {}
                            response = http.request("DELETE", url, headers=headers)
                            print(f"delete ID:{appliance_id}, resp.status:{response.status}")
                            if response.status != 200 and response.status != 204:
                                print(f"Error: delete ID:{appliance_id}, failed with rsp code:{response.status}")
                            print("Error: ID not found in response")
                        print(f"Error: unexpected number of appliances:{len(appliances)}, instanceId:{instance}")
                    print("Error: appliances not found in response")
                print(f"Error: post/search instanceId:{instance} failed, rsp code:{response.status}")
            print("Error - unable to process event")
  10. Click Save at the top of the page.

  11. Scroll down the lambda function page until you get to the VPC section, and then click Edit.

  12. Select Custom VPC under VPC connection.

  13. Select the VPC, subnets, and security groups for your environment.

  14. Click Save.

Create the CloudWatch rule

  1. From the AWS management console, navigate to CloudWatch.
  2. In the left navigation under Events, select Rules, and then click Create rule.
  3. Select Event Pattern.
  4. Under Build event pattern to match events by service, enter the following parameters:
  5. Service name: Select EC2.
  6. Event type: Select EC2 Instance State-change Notification.
  7. Specific state(s): Select terminated.
  8. Any instance: Add the instance IDs that you want to remove from the Network Security management interface.
  9. Check that the correct instances appear in the Event Pattern Preview.
  10. In the Targets section, click Add target.
  11. Select Lambda function from the drop down menu, and then select the lambda function that you created in the steps above.
  12. Click Configure details.
  13. Enter a name and description for the new rule, and then click Create rule.
  14. On the main Rules page, make sure that the new rule you just created shows a green status to indicate that it is enabled.

Create a CloudWatch alarm

We recommend that you create a CloudWatch alarm to alert you if the unregister lambda that you created encounters an error and fails. This alarm is activated when a CloudWatch metric is fulfilled and sends an email to a designated email address. The metric is based on the occurrence of an error in the lambda log output.

Create an SNS topic

The SNS topic is used to send an email to a designated user to alert them when an error occurs.

NOTE: You can use the same SNS topic that you created for the High Availability CloudWatch alarm.

Follow these steps to create a new topic.

  1. Navigate to the SNS Dashboard.
  2. Click TopicsCreate topic.
  3. Enter a name, like appliance-termination-error, and then click Create topic.
  4. Next, click Subscriptions → Create subscription.
  5. For Topic ARN, enter the topic name that you just created.
  6. For Protocol, select Email, and then enter the endpoint email address that you want to use.
  7. Click Create subscription.

Create a metric filter

The metric filter sorts through the lambda logs for any errors.

  1. Navigate to the CloudWatch Management Console, and click on Log groups.
  2. Find the lambda function that you created above, and click on the name. This takes you to the log groups details page.
  3. From the Actions drop down menu near the top of the page, select Create metric filter.
  4. For the Filter pattern, enter the following: [w1=ERROR || w1="Error:" || w1=Error, w2]
  5. Click Next.
  6. Enter the following parameters, then click Next:
    • Filter name: Use a recognizable name, like instance-lambda-error-filter.
    • Metric namespace: Enter LogMetrics.
    • Metric name: Use a recognizable name, like instance-term-lambda-error-metric.
    • Metric value: Enter 1.
  7. Review the entered parameters, then click Create metric filter.

NOTE: Metrics are automatically deleted by AWS if they are not used for 14 days.

Force the custom metric to display

Before you can create the alarm for this metric, you first have to force an error so that the metric appears when you create the alarm. This is necessary because AWS CloudWatch does not display a metric unless it has already been triggered.

Use the following steps to force an error to generate in the log.

  1. Navigate to the Lambda Dashboard, and from the Functions page, select the lambda function that you previously created.
  2. From the Actions drop down menu, select Test. The Configure test event page appears.
  3. Leave the default testing settings, and click Create.

The unexpected test event causes the lambda to generate an error in the log. This error is sufficient to make the metric you created appear in the CloudWatch alarm page.

Create the CloudWatch alarm

  1. Navigate back to the CloudWatch Management Console.

  2. Click Alarms, and then Create alarm.

  3. Click Select metric.

  4. In the All metrics tab, under Custom Namespaces, click LogMetrics, and then click Metrics with no dimensions.

    NOTE: If you did not save your metric filter in a Custom Namespace, we recommend doing a search to find your metric.

  5. Select the name of the metric that you created in Create a metric filter, and then click Select metric.

  6. Under Conditions, enter 0 for the than... parameter, and then click Next.

  7. On the Configure actions page, under Send a notification to..., select the SNS topic that you created, and then click Next.

  8. Enter a name for the alarm, like instance-terminate-lambda-error-alarm, and then click Next.

  9. Review the settings, then click Create alarm.