> ## 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 IAM Policy Changes

### More Info:

Ensure Event Rules capture IAM Policy modifications. Policy changes must trigger events so that security orchestration tools can validate the change against approved infrastructure-as-code deployments.

### 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)
* Essential 8
* 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 CSF
* NIST SP 800-171
* NYDFS 23 NYCRR 500
* PCI
* 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 step‑by‑step instructions to set up an OCI Event Rule for IAM policy changes and wire it into OCI alerting/monitoring using the OCI Console.

        ***

        ## 1. Create (or choose) a Notifications Topic

        1. Sign in to the **OCI Console**.
        2. In the top-left menu, go to **Developer Services > Application Integration > Notifications**.
        3. Make sure you’re in the **correct region**.
        4. Click **Create Topic**.
           * **Name**: `iam-policy-changes-topic` (or any name you prefer)
           * **Description**: `Alerts for IAM policy create/update/delete`
        5. Click **Create**.

        ### Add a Subscription (email/SNS/Slack/etc.)

        1. Open the topic you just created.
        2. Under **Subscriptions**, click **Create Subscription**.
        3. Set:
           * **Protocol**: e.g., `Email`
           * **Endpoint**: your email address (or webhook/Slack URL, etc.).
        4. Click **Create**.
        5. If using **Email**, check your inbox and **confirm the subscription** via the link.

        ***

        ## 2. Create an Event Rule for IAM Policy Changes

        1. In the top-left menu, go to\
           **Observability & Management > Events Service > Rules**.
        2. Make sure you’re in the **same region** as the resources/policies you care about.
        3. Click **Create Rule**.

        ### Basic Rule Configuration

        1. **Name**: `iam-policy-changes-rule`
        2. **Description**: `Trigger notification when IAM policies are created, updated, or deleted`
        3. **State**: Leave as **Enabled**.

        ### Define the Event Pattern

        You want events from the **Identity** service when policies change.

        1. Under **Rule Conditions**, choose:
           * **Rule Type**: `Event Type`
        2. Configure:
           * **Service Name**: `Identity`
           * **Event Types** (select all that are available for IAM policies in your tenancy/region, typically):
             * **Create Policy**\
               (`com.oraclecloud.identitycontrolplane.createpolicy`)
             * **Update Policy**\
               (`com.oraclecloud.identitycontrolplane.updatepolicy`)
             * **Delete Policy**\
               (`com.oraclecloud.identitycontrolplane.deletepolicy`)
             * Optionally, **Change Policy Compartment**\
               (`com.oraclecloud.identitycontrolplane.changepolicycompartment`) if listed.

        (Names may appear in friendly form; just select all IAM “Policy” related event types.)

        If you want to scope to a specific compartment:

        * Under **Condition (optional)**, you can add a filter on:
          * `data.compartmentId` = `<OCID of the compartment>`\
            or
          * `data.additionalDetails.compartmentName` = `<compartment-name>`

        ***

        ## 3. Add the Action: Send to Notifications

        1. Under **Actions**, click **Add Action**.
        2. **Action Type**: `Notifications`
        3. **Topic**: select the topic you created earlier\
           e.g., `iam-policy-changes-topic`.
        4. (Optional) Add additional actions if needed (e.g., trigger a Function).

        Click **Create Rule** to save.

        ***

        ## 4. Test the Alert

        1. Ensure your subscription (email, etc.) is **confirmed**.
        2. As a test, perform one of the following in the **Identity** service:
           * Create a new IAM policy.
           * Edit an existing IAM policy (e.g., change a statement).
           * Delete a test policy.
        3. Within a short time, you should receive an alert through your Notifications subscription.

        ***

        You now have an OCI Event Rule that detects IAM policy changes and pushes alerts via OCI Notifications, which is the standard mechanism used by OCI Monitoring/Alerting for event-based notifications.
      </Accordion>

      <Accordion title="Using CLI">
        Below is a minimal, end‑to‑end way to set up an OCI Event Rule for IAM policy changes and send alerts using OCI CLI.

        Assumptions:

        * You already have `oci` CLI configured (`~/.oci/config`)
        * You know your compartment OCID and tenancy region

        ***

        ## 1. Set environment variables

        ```bash theme={null}
        export COMPARTMENT_OCID="ocid1.compartment.oc1..xxxx"
        export REGION="us-ashburn-1"   # change to your region
        oci setup repair-file-permissions --file ~/.oci/config
        ```

        (Optional) Set region in your CLI config or in each command with `--region`.

        ***

        ## 2. Create a Notifications topic

        ```bash theme={null}
        oci ons topic create \
          --name "iam-policy-change-alerts" \
          --compartment-id "$COMPARTMENT_OCID" \
          --description "Alerts for OCI IAM policy changes" \
          --region "$REGION"
        ```

        Capture the topic OCID from the output:

        ```bash theme={null}
        export TOPIC_OCID="ocid1.onstopic.oc1..xxxx"
        ```

        ***

        ## 3. Create a subscription (email example)

        ```bash theme={null}
        oci ons subscription create \
          --topic-id "$TOPIC_OCID" \
          --protocol EMAIL \
          --endpoint "you@example.com" \
          --region "$REGION"
        ```

        Confirm the subscription from your email before testing.

        ***

        ## 4. Create the IAM Policy Change Event Rule

        Create a JSON file `iam-policy-change-rule.json`:

        ```json theme={null}
        {
          "displayName": "iam-policy-change-rule",
          "isEnabled": true,
          "condition": "{\"eventType\":[\"com.oraclecloud.identity.policy.create\",\"com.oraclecloud.identity.policy.update\",\"com.oraclecloud.identity.policy.delete\"]}",
          "compartmentId": "OCID_OF_TENANCY_OR_ROOT_COMPARTMENT",
          "actions": {
            "actions": [
              {
                "actionType": "ONS",
                "isEnabled": true,
                "topicId": "OCID_OF_TOPIC"
              }
            ]
          }
        }
        ```

        Replace:

        * `OCID_OF_TENANCY_OR_ROOT_COMPARTMENT` with your **tenancy or root compartment OCID** (policies live there).
        * `OCID_OF_TOPIC` with `$TOPIC_OCID`.

        Then run:

        ```bash theme={null}
        oci events rule create \
          --from-json file://iam-policy-change-rule.json \
          --region "$REGION"
        ```

        Alternatively, inline:

        ```bash theme={null}
        oci events rule create \
          --display-name "iam-policy-change-rule" \
          --is-enabled true \
          --compartment-id "ocid1.tenancy.oc1..xxxx" \
          --condition '{"eventType":["com.oraclecloud.identity.policy.create","com.oraclecloud.identity.policy.update","com.oraclecloud.identity.policy.delete"]}' \
          --actions '{"actions":[{"actionType":"ONS","isEnabled":true,"topicId":"'"$TOPIC_OCID"'"}]}' \
          --region "$REGION"
        ```

        ***

        ## 5. Verify the rule

        ```bash theme={null}
        oci events rule list \
          --compartment-id "ocid1.tenancy.oc1..xxxx" \
          --region "$REGION"
        ```

        Check that:

        * `isEnabled` is `true`
        * `condition` contains the three policy event types
        * `actions.actions[0].topicId` is your Notification topic

        ***

        ## 6. Test the alert

        Make a small change to an IAM policy (e.g., add/remove a statement) via Console or CLI, then confirm you receive an email from the Notifications topic.

        ***

        This sets up continuous alerting for OCI IAM policy create/update/delete using Events + Notifications via OCI CLI. Monitoring Alarms are not used here because IAM policy changes are event-driven, not metric-based.
      </Accordion>

      <Accordion title="Using Python">
        Below are the steps and a Python example to ensure **OCI has an Event Rule for IAM policy changes** and alerts via Monitoring/Notifications.

        ***

        ## 1. What you need first

        * **OCI Tenancy OCID**
        * **Compartment OCID** where you will create the rule
        * **Region**
        * **Configured OCI credentials** (config file `~/.oci/config` with a profile, or instance/principal auth)
        * An **email address** (or other channel) for notification

        You’ll use:

        * **OCI Events** to capture IAM policy changes
        * **OCI Notifications** to send alerts
        * Optionally, Monitoring alarms if you want metric-based alerts (but usually Events + Notifications is enough for IAM changes)

        ***

        ## 2. Install Python SDK

        ```bash theme={null}
        pip install oci
        ```

        ***

        ## 3. Event pattern for IAM policy changes

        Use an Events rule with this event pattern (no spaces/newlines when passing as JSON string):

        ```json theme={null}
        {
          "eventType": [
            "com.oraclecloud.identitycontrolplane.changepolicy",
            "com.oraclecloud.identitycontrolplane.createpolicy",
            "com.oraclecloud.identitycontrolplane.deletepolicy"
          ]
        }
        ```

        You can add `updatepolicy` as needed, depending on your tenancy.

        ***

        ## 4. Full Python script (create topic, subscription, and event rule)

        ```python theme={null}
        import oci
        import json
        import sys
        from oci.core import models as core_models
        from oci.events import models as events_models
        from oci.ons import NotificationControlPlaneClient
        from oci.ons import models as ons_models

        # ----------------- CONFIGURE THESE -----------------
        PROFILE_NAME = "DEFAULT"   # profile in ~/.oci/config
        COMPARTMENT_OCID = "<your_compartment_ocid>"
        TENANCY_OCID = "<your_tenancy_ocid>"  # optional but useful to set as a condition
        REGION = "us-phoenix-1"    # change to your region
        ALERT_EMAIL = "you@example.com"
        TOPIC_NAME = "iam-policy-change-alerts"
        EVENT_RULE_DISPLAY_NAME = "Detect-IAM-Policy-Changes"
        # ---------------------------------------------------

        def main():
            # Load config
            config = oci.config.from_file("~/.oci/config", PROFILE_NAME)
            config["region"] = REGION

            # Clients
            ons_client = NotificationControlPlaneClient(config)
            events_client = oci.events.EventsClient(config)

            # 1) Create or get Notifications topic
            topic_ocid = get_or_create_topic(ons_client, COMPARTMENT_OCID, TOPIC_NAME)

            # 2) Create or get subscription for email
            create_email_subscription_if_not_exists(ons_client, topic_ocid, ALERT_EMAIL)

            # 3) Create Events rule for IAM policy changes
            create_or_update_iam_policy_change_rule(
                events_client,
                COMPARTMENT_OCID,
                topic_ocid,
                EVENT_RULE_DISPLAY_NAME
            )

            print("Setup complete.")
            print(f"Topic OCID: {topic_ocid}")


        def get_or_create_topic(ons_client, compartment_id, topic_name):
            topics = oci.pagination.list_call_get_all_results(
                ons_client.list_topics,
                compartment_id=compartment_id
            ).data

            for t in topics:
                if t.name == topic_name:
                    print(f"Found existing topic: {t.name}")
                    return t.topic_id

            details = ons_models.CreateTopicDetails(
                name=topic_name,
                compartment_id=compartment_id,
                description="Alerts for IAM policy changes"
            )
            topic = ons_client.create_topic(details).data
            print(f"Created topic: {topic.name}")
            return topic.topic_id


        def create_email_subscription_if_not_exists(ons_client, topic_ocid, email):
            subs = oci.pagination.list_call_get_all_results(
                ons_client.list_subscriptions,
                compartment_id=COMPARTMENT_OCID,
                topic_id=topic_ocid
            ).data

            # Skip if already exists
            for s in subs:
                if s.protocol.lower() == "email" and s.endpoint.lower() == email.lower():
                    print(f"Email subscription already exists: {email}")
                    return

            details = ons_models.CreateSubscriptionDetails(
                compartment_id=COMPARTMENT_OCID,
                topic_id=topic_ocid,
                protocol="EMAIL",
                endpoint=email
            )
            sub = ons_client.create_subscription(details).data
            print(f"Created email subscription: {email}")
            print("IMPORTANT: Confirm the subscription from your email inbox.")


        def create_or_update_iam_policy_change_rule(
            events_client,
            compartment_id,
            topic_ocid,
            display_name
        ):
            # Event pattern for IAM policy changes
            event_pattern = {
                "eventType": [
                    "com.oraclecloud.identitycontrolplane.changepolicy",
                    "com.oraclecloud.identitycontrolplane.createpolicy",
                    "com.oraclecloud.identitycontrolplane.deletepolicy",
                    "com.oraclecloud.identitycontrolplane.updatepolicy"
                ]
            }

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

            target = events_models.ActionDetails(
                action_type="ONS",
                is_enabled=True,
                topic_id=topic_ocid
            )

            if existing_rules:
                for r in existing_rules:
                    if r.display_name == display_name:
                        print(f"Found existing rule '{display_name}', updating it.")
                        update_details = events_models.UpdateRuleDetails(
                            display_name=display_name,
                            description="Trigger on IAM policy create/change/delete/update events",
                            is_enabled=True,
                            condition=json.dumps(event_pattern),
                            actions=events_models.ActionList(
                                actions=[target]
                            )
                        )
                        events_client.update_rule(rule_id=r.id, update_rule_details=update_details)
                        print("Event rule updated.")
                        return

            print(f"Creating new event rule '{display_name}'")
            create_details = events_models.CreateRuleDetails(
                display_name=display_name,
                description="Trigger on IAM policy create/change/delete/update events",
                is_enabled=True,
                compartment_id=compartment_id,
                condition=json.dumps(event_pattern),
                actions=events_models.ActionList(
                    actions=[target]
                )
            )
            rule = events_client.create_rule(create_rule_details=create_details).data
            print(f"Event rule created. OCID: {rule.id}")


        if __name__ == "__main__":
            if "<your_compartment_ocid>" in COMPARTMENT_OCID:
                print("Set COMPARTMENT_OCID, TENANCY_OCID, and other variables at top of script.")
                sys.exit(1)
            main()
        ```

        ***

        ## 5. Steps to use

        1. Update the variables at the top of the script:
           * `COMPARTMENT_OCID`
           * `TENANCY_OCID` (optional in this script but good to keep)
           * `REGION`
           * `ALERT_EMAIL`
        2. Ensure your `~/.oci/config` is correctly configured with the given profile.
        3. Run the script:
           ```bash theme={null}
           python oci_iam_policy_events_alert.py
           ```
        4. Open the confirmation email from OCI Notifications and **confirm the subscription**.
        5. Test by creating/updating/deleting an IAM policy; you should receive an alert.

        If you want, I can also add Monitoring alarms on top of this to track a metric for policy changes.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "oci_events_rule" "iam_policy_change_events" {
          # Replace with the OCID of the compartment where you want the rule defined
          compartment_id = "OCID_OF_TARGET_COMPARTMENT"

          display_name = "iam-policy-change-events"
          description  = "Capture IAM policy create/update/delete events for monitoring/alerting"
          is_enabled   = true

          # Match IAM policy create, update, and delete events
          condition = <<EOF
        {
          "eventType": [
            "com.oraclecloud.identitycontrolplane.policy.create",
            "com.oraclecloud.identitycontrolplane.policy.update",
            "com.oraclecloud.identitycontrolplane.policy.delete"
          ]
        }
        EOF

          # Optional: forward matching events to an OCI Notifications topic consumed by your
          # monitoring/alerting/automation tools.
          actions {
            actions {
              action_type = "ONS"
              is_enabled  = true

              # Replace with the OCID of an existing Notifications topic
              topic_id    = "OCID_OF_OCI_NOTIFICATIONS_TOPIC"

              description = "Forward IAM policy change events to monitoring/alerting pipeline"
            }
          }
        }
        ```

        This change does not force replacement of other resources; `oci_events_rule.iam_policy_change_events` will be created or updated in place.

        Verification: `terraform plan` should show either a new `oci_events_rule.iam_policy_change_events` resource being created, or an in-place update where the `condition` now includes the three IAM policy event types (and the `actions` block, if added).
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
