> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# OCI Monitoring Should Have Event Rule For VCN Changes

### More Info:

VCN lifecycle events must be tracked via Event Rules. Deploying rogue virtual networks is often a precursor to launching illicit infrastructure or isolated cryptomining rigs.

### Risk Level

Medium

### Address

Compliance, Security

### Compliance Standards

* APRA CPS 234 (Australia)
* AWS Well Architected Framework
* BSI C5 (Germany)
* Brazil LGPD
* CCPA / CPRA (California)
* CIS AWS
* CIS Critical Security Controls v8
* CMMC 2.0
* CSA Cloud Controls Matrix v4
* Cloudanix Best Practice
* DPDPA
* Digital Operational Resilience Act (EU)
* HIPAA
* HITRUST CSF
* ISO 27001
* ISO/IEC 27017
* ISO/IEC 27018
* ISO/IEC 27701
* KSA PDPL
* MAS Technology Risk Management (Singapore)
* MITRE ATT\&CK (Cloud)
* NIS2 Directive
* NIST
* NIST CSF
* NIST SP 800-171
* NYDFS 23 NYCRR 500
* SOC2
* SWIFT Customer Security Controls Framework
* Sarbanes-Oxley IT General Controls
* UK NCSC Cyber Assessment Framework

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        Below are concise, step‑by‑step instructions to create an OCI Event Rule for VCN changes and wire it into alerting via Notifications (and optionally Monitoring Alarms), using only the OCI Console.

        ***

        ## 1. Prerequisites

        1. Make sure you have:
           * Permissions to manage `events` and `ons` (Notifications) in the target compartment.
        2. Decide:
           * Which compartment you want to monitor VCN changes in.
           * Where you want alerts to go (email, Slack via HTTPS, PagerDuty, etc.).

        ***

        ## 2. Create a Notifications Topic

        1. Sign in to OCI Console.
        2. Open the hamburger menu → **Developer Services** → **Notifications** → **Topics**.
        3. Click **Create Topic**.
           * **Name**: e.g., `vcn-change-alerts-topic`
           * **Compartment**: Choose the target compartment.
        4. Click **Create**.

        ### Add a Subscription

        1. Open the topic you just created.
        2. Under **Subscriptions**, click **Create Subscription**.
        3. Choose:
           * **Protocol**: e.g., `Email`.
           * **Email**: enter the recipient address.
        4. Click **Create**.
        5. Go to your email and **confirm** the subscription (mandatory).

        ***

        ## 3. Create an Event Rule for VCN Changes

        1. Open the hamburger menu → **Observability & Management** → **Events Service** → **Rules**.
        2. Make sure the **compartment** is the one where you want the rule to live.
        3. Click **Create Rule**.

        ### Rule Details

        1. **Name**: e.g., `detect-vcn-changes`.
        2. **Description**: `Alert on VCN create, update, and delete events`.
        3. **State**: Ensure it is set to **Enabled**.

        ### Define the Event Pattern

        You have two main options:

        #### Option A: Use the Basic Pattern (Service + Event Types)

        1. Under **Rule Conditions**, select:
           * **Service Name**: `Networking` (or `Virtual Cloud Network` depending on console wording).
        2. For **Event Type**, select VCN-related events such as:
           * `com.oraclecloud.virtualnetwork.createvcn.end`
           * `com.oraclecloud.virtualnetwork.updatevcn.end`
           * `com.oraclecloud.virtualnetwork.deletevcn.end`
             (Name may appear slightly differently; pick all VCN Create/Update/Delete event types).
        3. Narrow by **Compartment**:
           * Choose the compartment where the VCNs are/will be created (or `root` if you want tenancy-wide and then filter via conditions or multiple rules).

        #### Option B: Use an Advanced Pattern (if needed)

        1. Switch to **Use a Custom Event Pattern (Advanced)**.
        2. Use a filter similar to:

        ```json theme={null}
        {
          "eventType": [
            "com.oraclecloud.virtualnetwork.createvcn.end",
            "com.oraclecloud.virtualnetwork.updatevcn.end",
            "com.oraclecloud.virtualnetwork.deletevcn.end"
          ],
          "data": {
            "compartmentId": [
              "<OCID_OF_TARGET_COMPARTMENT>"
            ]
          }
        }
        ```

        Replace `<OCID_OF_TARGET_COMPARTMENT>` with your compartment OCID if you want to constrain scope.

        ***

        ## 4. Add the Action (Send Notification)

        1. In the **Actions** section of the rule, click **Add Action**.
        2. **Action Type**: `Notifications`.
        3. **Topic**: Select the topic you created (`vcn-change-alerts-topic`).
        4. Click **Add**.
        5. Click **Create** to finalize the Event Rule.

        Now, every time a VCN is created, updated, or deleted in the specified compartment(s), an event will trigger a message to your Notifications topic, which will send email (or other protocol) alerts.

        ***

        ## 5. (Optional) Integrate with Monitoring Alarms

        If you specifically want OCI **Monitoring Alarms** (metrics‑based) in addition to event‑based notifications:

        1. Typically, VCN configuration changes are event‑driven, not metric‑driven, so you:
           * Keep the Event Rule to push messages via Notifications to people/tools.
           * Use Monitoring Alarms for metrics (e.g., traffic, errors) separately.
        2. If you want an alarm-like behavior:
           * Create an **Alarm** in **Observability & Management → Monitoring → Alarms** for relevant network metrics (e.g., dropped packets, high traffic) and send it to the **same Notifications topic**.

        ***

        ## 6. Validate the Setup

        1. Make a small, safe VCN change in the monitored compartment:
           * e.g., update the VCN display name or create a test VCN.
        2. Confirm:
           * Event Rule logs an invocation (visible in Events Service details).
           * A notification email (or other protocol message) is received at the configured subscription.

        This completes remediation: OCI now has an Event Rule for VCN changes wired into your alerting via Notifications (and optionally Monitoring alarms).
      </Accordion>

      <Accordion title="Using CLI">
        Below are step‑by‑step OCI CLI instructions to ensure Monitoring/Alerting is in place for VCN changes by creating an **Events rule** that triggers a **Notifications topic** whenever a VCN is created/updated/deleted.

        ***

        ## 0. Prerequisites

        * OCI CLI installed and configured (`oci setup config` already done).

        * Your **compartment OCID** is known:
          ```bash theme={null}
          COMPARTMENT_OCID="<your_compartment_ocid>"
          ```

        * You have permission to use:
          * `oci ons` (Notifications)
          * `oci events`
          * `oci iam` (if you need policies)

        ***

        ## 1. (Optional) Create a Notifications Topic

        If you already have a Notifications topic you want to use, skip to step 3 and use its OCID.

        ```bash theme={null}
        TOPIC_NAME="vcn-change-topic"
        TOPIC_DESC="Topic for VCN change events"

        oci ons topic create \
          --name "$TOPIC_NAME" \
          --compartment-id "$COMPARTMENT_OCID" \
          --description "$TOPIC_DESC" \
          --wait-for-state ACTIVE \
          --query "data.id" \
          --raw-output
        ```

        Save the output as:

        ```bash theme={null}
        TOPIC_OCID="<output_from_command_above>"
        ```

        ***

        ## 2. (Optional) Add a Subscription to the Topic

        For example, an email subscription:

        ```bash theme={null}
        SUBSCR_PROTOCOL="EMAIL"
        SUBSCR_ENDPOINT="you@example.com"

        oci ons subscription create \
          --compartment-id "$COMPARTMENT_OCID" \
          --topic-id "$TOPIC_OCID" \
          --protocol "$SUBSCR_PROTOCOL" \
          --endpoint "$SUBSCR_ENDPOINT" \
          --wait-for-state ACTIVE
        ```

        Confirm the subscription by clicking the link in the email.

        ***

        ## 3. Create Event Rule JSON Condition for VCN Changes

        Create a file `vcn-events-condition.json`:

        ```json theme={null}
        {
          "eventType": [
            "com.oraclecloud.virtualnetwork.createvcn",
            "com.oraclecloud.virtualnetwork.updatevcn",
            "com.oraclecloud.virtualnetwork.deletevcn"
          ],
          "data": {
            "resourceName": [],
            "compartmentId": []
          }
        }
        ```

        You can also filter to a specific compartment or VCN by filling `data.compartmentId` or `data.resourceName` arrays, but for all VCNs, leave them empty as above.

        Wrap this in the Events Rule “condition” structure (OCI requires `"eventType"` and `"data"` to be inside `"conditions"`):

        Create `vcn-rule-condition.json`:

        ```json theme={null}
        {
          "eventType": [
            "com.oraclecloud.virtualnetwork.createvcn",
            "com.oraclecloud.virtualnetwork.updatevcn",
            "com.oraclecloud.virtualnetwork.deletevcn"
          ],
          "data": {
            "resourceName": [],
            "compartmentId": []
          }
        }
        ```

        The CLI expects it like this:

        ```bash theme={null}
        CONDITION_JSON=$(cat vcn-rule-condition.json | python -c 'import json,sys; print(json.dumps({"eventType": json.load(sys.stdin)["eventType"], "data": json.load(open("vcn-rule-condition.json"))["data"]}))')
        ```

        To avoid confusion, simply create a single correct condition file:

        **Final** `vcn-rule-condition.json`:

        ```json theme={null}
        {
          "eventType": [
            "com.oraclecloud.virtualnetwork.createvcn",
            "com.oraclecloud.virtualnetwork.updatevcn",
            "com.oraclecloud.virtualnetwork.deletevcn"
          ],
          "data": {
            "resourceName": [],
            "compartmentId": []
          }
        }
        ```

        ***

        ## 4. Create the Events Rule

        Use the Notifications topic as the rule’s action:

        ```bash theme={null}
        RULE_DISPLAY_NAME="VCN-Change-Rule"
        RULE_DESC="Triggers when VCNs are created, updated, or deleted"

        oci events rule create \
          --compartment-id "$COMPARTMENT_OCID" \
          --display-name "$RULE_DISPLAY_NAME" \
          --is-enabled true \
          --condition "$(cat vcn-rule-condition.json)" \
          --actions '{
            "actions": [
              {
                "actionType": "ONS",
                "isEnabled": true,
                "topicId": "'"$TOPIC_OCID"'"
              }
            ]
          }' \
          --description "$RULE_DESC" \
          --wait-for-state ACTIVE
        ```

        This creates a rule that:

        * Listens for these event types:
          * `com.oraclecloud.virtualnetwork.createvcn`
          * `com.oraclecloud.virtualnetwork.updatevcn`
          * `com.oraclecloud.virtualnetwork.deletevcn`
        * Sends a notification to the ONS topic when they occur.

        ***

        ## 5. (Optional) Verify the Rule

        List rules in the compartment:

        ```bash theme={null}
        oci events rule list \
          --compartment-id "$COMPARTMENT_OCID" \
          --all \
          --query "data[?\"display-name\"=='$RULE_DISPLAY_NAME']"
        ```

        ***

        ## 6. (Optional) Update an Existing Rule

        If a rule exists but lacks VCN events, adjust it:

        1. Get the rule OCID:

           ```bash theme={null}
           RULE_OCID="<existing_rule_ocid>"
           ```

        2. Update the `condition` file with VCN event types and then run:

           ```bash theme={null}
           oci events rule update \
             --rule-id "$RULE_OCID" \
             --condition "$(cat vcn-rule-condition.json)" \
             --force \
             --wait-for-state ACTIVE
           ```

        ***

        Once these steps are done, your OCI environment will have an Events rule that alerts (via Notifications) for all VCN configuration changes, satisfying the requirement “OCI Monitoring Should Have Event Rule For VCN Changes.”
      </Accordion>

      <Accordion title="Using Python">
        Below is a concrete way to remediate “OCI Monitoring should have Event Rule for VCN changes” using Python and the OCI SDK.

        Goal\
        Create an Event Rule that listens to VCN configuration changes and sends alerts (via OCI Notifications / Monitoring).

        Assumptions

        * You have:
          * OCI tenancy, compartment OCID
          * Proper IAM permissions: `manage events-rules`, `manage ons-topics`, etc.
          * Working `~/.oci/config` profile (or equivalent config in environment variables).
        * You want:
          * An Events rule that triggers when a VCN is created/updated/deleted.
          * An alert via Notifications (email) or similar.

        ***

        ## 1. Define what events you want to capture

        Typical VCN configuration change events come from the `com.oraclecloud.virtualnetwork` service and category `Resource` (or `Api` depending on how strict you want). Safe generic pattern:

        ```json theme={null}
        {
          "eventType": "com.oraclecloud.virtualnetwork.vcn.*",
          "data": {
            "eventType": "com.oraclecloud.virtualnetwork.vcn.*"
          }
        }
        ```

        To be more precise, you can match:

        * `com.oraclecloud.virtualnetwork.vcn.create`
        * `com.oraclecloud.virtualnetwork.vcn.update`
        * `com.oraclecloud.virtualnetwork.vcn.delete`

        OCI Events use an **event pattern** (JSON) to filter events.

        ***

        ## 2. Create (or reuse) a Notifications topic

        You generally want the Event Rule to send messages to an OCI Notifications topic, then subscribe email / HTTPS, etc.

        ### Sample Python script: create topic (if not exists) and subscription

        ```python theme={null}
        import oci

        config = oci.config.from_file()  # default profile and path
        compartment_id = "<YOUR_COMPARTMENT_OCID>"
        topic_name = "vcn-change-alerts-topic"
        subscription_endpoint = "<YOUR_EMAIL_ADDRESS>"  # or HTTPS endpoint

        ons_client = oci.ons.NotificationControlPlaneClient(config)

        # 1. Check if topic exists
        existing_topics = oci.pagination.list_call_get_all_results(
            ons_client.list_topics,
            compartment_id=compartment_id
        ).data

        topic = next((t for t in existing_topics if t.name == topic_name), None)

        # 2. Create topic if needed
        if not topic:
            create_topic_details = oci.ons.models.CreateTopicDetails(
                name=topic_name,
                compartment_id=compartment_id,
                description="Alerts for VCN configuration changes"
            )
            topic = ons_client.create_topic(create_topic_details).data
            print(f"Created topic: {topic.name} ({topic.topic_id})")
        else:
            print(f"Using existing topic: {topic.name} ({topic.topic_id})")

        topic_id = topic.topic_id

        # 3. Create subscription (email example)
        ons_sub_client = oci.ons.NotificationDataPlaneClient(config)

        create_sub_details = oci.ons.models.CreateSubscriptionDetails(
            compartment_id=compartment_id,
            topic_id=topic_id,
            protocol="EMAIL",  # or "HTTPS", "PAGERDUTY", "SLACK", etc.
            endpoint=subscription_endpoint,
            freeform_tags={"purpose": "vcn-change-alerts"}
        )

        subscription = ons_sub_client.create_subscription(create_sub_details).data
        print(f"Created subscription: {subscription.id}")
        print("You must confirm the subscription from your email/endpoint.")
        ```

        ***

        ## 3. Create the Event Rule for VCN changes

        Use the **Events** client and create a rule that:

        * Targets your compartment
        * Has an event pattern that matches VCN changes
        * Uses the Notifications topic (`topic_id`) as an action

        ### Event pattern (example)

        This pattern matches all VCN events (`create`, `update`, `delete`):

        ```json theme={null}
        {
          "eventType": [
            "com.oraclecloud.virtualnetwork.vcn.create",
            "com.oraclecloud.virtualnetwork.vcn.update",
            "com.oraclecloud.virtualnetwork.vcn.delete"
          ]
        }
        ```

        You can further constrain by `data.compartmentId` or other fields if needed.

        ### Python script to create the Event Rule

        ```python theme={null}
        import json
        import oci

        config = oci.config.from_file()
        compartment_id = "<YOUR_COMPARTMENT_OCID>"
        topic_id = "<YOUR_TOPIC_OCID>"  # from previous step
        rule_display_name = "VCN-Change-Event-Rule"

        events_client = oci.events.EventsClient(config)

        # 1. Build the event pattern
        event_pattern = {
            "eventType": [
                "com.oraclecloud.virtualnetwork.vcn.create",
                "com.oraclecloud.virtualnetwork.vcn.update",
                "com.oraclecloud.virtualnetwork.vcn.delete"
            ]
            # You could optionally add more filters like:
            # "data": {
            #     "compartmentId": ["<YOUR_COMPARTMENT_OCID>"]
            # }
        }

        # 2. Define the action to send to Notifications
        action = oci.events.models.CreateRuleActionDetails(
            action_type="ONS",
            is_enabled=True,
            description="Send VCN change events to Notifications topic",
            topic_id=topic_id
        )

        # 3. Build the rule details
        create_rule_details = oci.events.models.CreateRuleDetails(
            compartment_id=compartment_id,
            display_name=rule_display_name,
            is_enabled=True,
            condition=event_pattern,
            actions=oci.events.models.Actions(
                actions=[action]
            ),
            description="Rule that triggers on VCN create/update/delete events"
        )

        # 4. Check if rule already exists
        existing_rules = oci.pagination.list_call_get_all_results(
            events_client.list_rules,
            compartment_id=compartment_id
        ).data

        rule = next((r for r in existing_rules if r.display_name == rule_display_name), None)

        if rule:
            print(f"Rule '{rule_display_name}' already exists: {rule.id}")
        else:
            # 5. Create the rule
            response = events_client.create_rule(create_rule_details)
            rule = response.data
            print(f"Created rule: {rule.display_name} ({rule.id})")
            print("Event Rule for VCN changes is now active.")
        ```

        ***

        ## 4. (Optional) Integrate with Monitoring Alarms

        If your security standard specifically wants **Monitoring service** to raise alarms from events, you can:

        1. Use Event Rule → Notifications → custom HTTPS endpoint.
        2. That endpoint can push metrics (via `oci.monitoring.MonitoringClient`) and then:
        3. Create a Monitoring Alarm on those custom metrics.

        However, for most CSPM requirements, having an Event Rule + Notifications alert is sufficient and is what “OCI Monitoring / Alerting” usually refers to at policy level.

        ***

        ## 5. Validation

        1. Confirm Notifications subscription.
        2. Create/update/delete a test VCN in the compartment.
        3. Verify that:
           * Event shows in OCI Console → Observability & Management → Events.
           * Notification is received at your configured endpoint.

        If you paste your compartment OCID and preferred channel (email/HTTPS/Slack/PagerDuty), I can adjust the Python snippets exactly to your environment.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "oci_events_rule" "vcn_lifecycle_events" {
          # Monitors VCN lifecycle events and routes them to an Alerting/Notifications target.
          compartment_id = "COMPARTMENT_OCID"         # replace with the OCID of the compartment to monitor
          display_name   = "VCN-Lifecycle-Events-Rule"

          is_enabled = true

          # Track create, update, and delete operations for VCNs.
          # You can narrow this to a specific compartment/VCN using an additional "data" filter if required.
          condition = <<EOT
        {
          "eventType": [
            "com.oraclecloud.virtualnetwork.createvcn",
            "com.oraclecloud.virtualnetwork.updatevcn",
            "com.oraclecloud.virtualnetwork.deletevcn"
          ]
        }
        EOT

          actions {
            # Example: send the events to an existing Notifications topic that you plug into OCI Monitoring/Alerting.
            actions {
              action_type = "ONS"
              is_enabled  = true
              description = "Route VCN lifecycle events to Alerting/Monitoring"

              topic_id = "OCI_ONS_TOPIC_OCID"         # replace with the OCID of an ONS Notifications topic
            }

            # If you use Streaming, Functions, or other targets, add additional `actions {}` blocks here.
          }

          # Optional: freeform_tags or defined_tags if you use tagging standards
          # freeform_tags = {
          #   "Owner" = "NETWORK_TEAM"
          # }
        }
        ```

        This change does not force replacement of other resources; it only creates or updates the `oci_events_rule` itself.

        For verification, `terraform plan` should show this `oci_events_rule.vcn_lifecycle_events` being created (or updated if you are adding the condition to an existing rule), with `is_enabled = true` and the `condition` JSON listing the three `com.oraclecloud.virtualnetwork.*vcn` event types.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
