Update an existing rule

PUT https://api.ap1.datadoghq.com/api/v2/security_monitoring/rules/{rule_id}https://api.ap2.datadoghq.com/api/v2/security_monitoring/rules/{rule_id}https://api.datadoghq.eu/api/v2/security_monitoring/rules/{rule_id}https://api.ddog-gov.com/api/v2/security_monitoring/rules/{rule_id}https://api.us2.ddog-gov.com/api/v2/security_monitoring/rules/{rule_id}https://api.datadoghq.com/api/v2/security_monitoring/rules/{rule_id}https://api.us3.datadoghq.com/api/v2/security_monitoring/rules/{rule_id}https://api.us5.datadoghq.com/api/v2/security_monitoring/rules/{rule_id}

Overview

Update an existing rule. When updating cases, queries or options, the whole field must be included. For example, when modifying a query all queries must be included. Default rules can only be updated to be enabled, to change notifications, or to update the tags (default tags cannot be removed). This endpoint requires the security_monitoring_rules_write permission.

OAuth apps require the security_monitoring_rules_write authorization scope to access this endpoint.

Arguments

Path Parameters

Name

Type

Description

rule_id [required]

string

The ID of the rule.

Request

Body Data (required)

Expand All

Field

Type

Description

calculatedFields

[object]

Calculated fields. Only allowed for scheduled rules - in other words, when schedulingOptions is also defined.

expression [required]

string

Expression.

name [required]

string

Field name.

cases

[object]

Cases for generating signals.

actions

[object]

Action to perform for each rule case.

options

object

Options for the rule action

duration

int64

Duration of the action in seconds. 0 indicates no expiration.

flaggedIPType

enum

Used with the case action of type 'flag_ip'. The value specified in this field is applied as a flag to the IP addresses. Allowed enum values: SUSPICIOUS,FLAGGED

userBehaviorName

string

Used with the case action of type 'user_behavior'. The value specified in this field is applied as a risk tag to all users affected by the rule.

type

enum

The action type. Allowed enum values: block_ip,block_user,user_behavior,flag_ip

condition

string

A rule case contains logical operations (>,>=, &&, ||) to determine if a signal should be generated based on the event counts in the previously defined queries.

customStatus

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

name

string

Name of the case.

notifications

[string]

Notification targets for each rule case.

status

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

complianceSignalOptions

object

How to generate compliance signals. Useful for cloud_configuration rules only.

defaultActivationStatus

boolean

The default activation status.

defaultGroupByFields

[string]

The default group by fields.

userActivationStatus

boolean

Whether signals will be sent.

userGroupByFields

[string]

Fields to use to group findings by when sending signals.

customMessage

string

Custom/Overridden Message for generated signals (used in case of Default rule update).

customName

string

Custom/Overridden name (used in case of Default rule update).

filters

[object]

Additional queries to filter matched events before they are processed. This field is deprecated for log detection, signal correlation, and workload security rules.

action

enum

The type of filtering action. Allowed enum values: require,suppress

query

string

Query for selecting logs to apply the filtering action.

groupSignalsBy

[string]

Additional grouping to perform on top of the existing groups in the query section. Must be a subset of the existing groups.

hasExtendedTitle

boolean

Whether the notifications include the triggering group-by values in their title.

isEnabled

boolean

Whether the rule is enabled.

message

string

Message for generated signals.

name

string

Name of the rule.

options

object

Options.

anomalyDetectionOptions

object

Options on anomaly detection method.

bucketDuration

enum

Duration in seconds of the time buckets used to aggregate events matched by the rule. Must be greater than or equal to 300. Allowed enum values: 300,600,900,1800,3600,10800

detectionTolerance

enum

An optional parameter that sets how permissive anomaly detection is. Higher values require higher deviations before triggering a signal. Allowed enum values: 1,2,3,4,5

instantaneousBaseline

boolean

When set to true, Datadog uses previous values that fall within the defined learning window to construct the baseline, enabling the system to establish an accurate baseline more rapidly rather than relying solely on gradual learning over time.

learningDuration

enum

Learning duration in hours. Anomaly detection waits for at least this amount of historical data before it starts evaluating. Allowed enum values: 1,6,12,24,48,168,336

learningPeriodBaseline

int64

An optional override baseline to apply while the rule is in the learning period. Must be greater than or equal to 0.

complianceRuleOptions

object

Options for cloud_configuration rules. Fields resourceType and regoRule are mandatory when managing custom cloud_configuration rules.

complexRule

boolean

Whether the rule is a complex one. Must be set to true if regoRule.resourceTypes contains more than one item. Defaults to false.

regoRule

object

Rule details.

policy [required]

string

resourceTypes [required]

[string]

List of resource types that will be evaluated upon. Must have at least one element.

resourceType

string

Main resource type to be checked by the rule. It should be specified again in regoRule.resourceTypes.

decreaseCriticalityBasedOnEnv

boolean

If true, signals in non-production environments have a lower severity than what is defined by the rule case, which can reduce signal noise. The severity is decreased by one level: CRITICAL in production becomes HIGH in non-production, HIGH becomes MEDIUM and so on. INFO remains INFO. The decrement is applied when the environment tag of the signal starts with staging, test or dev.

detectionMethod

enum

The detection method. Allowed enum values: threshold,new_value,anomaly_detection,impossible_travel,hardcoded,third_party,anomaly_threshold,sequence_detection

evaluationWindow

enum

A time window is specified to match when at least one of the cases matches true. This is a sliding window and evaluates in real time. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

hardcodedEvaluatorType

enum

Hardcoded evaluator type. Allowed enum values: log4shell

impossibleTravelOptions

object

Options on impossible travel detection method.

baselineUserLocations

boolean

If true, signals are suppressed for the first 24 hours. In that time, Datadog learns the user's regular access locations. This can be helpful to reduce noise and infer VPN usage or credentialed API access.

baselineUserLocationsDuration

int32

The duration in days during which Datadog learns the user's regular access locations. After this period, signals are generated for accesses from unknown locations.

keepAlive

enum

Once a signal is generated, the signal will remain "open" if a case is matched at least once within this keep alive window. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

maxSignalDuration

enum

A signal will "close" regardless of the query being matched once the time exceeds the maximum duration. This time is calculated from the first seen timestamp. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

newValueOptions

object

Options on new value detection method.

forgetAfter

int32

The duration in days after which a learned value is forgotten.

instantaneousBaseline

boolean

When set to true, Datadog uses previous values that fall within the defined learning window to construct the baseline, enabling the system to establish an accurate baseline more rapidly rather than relying solely on gradual learning over time.

learningDuration

int32

The duration in days during which values are learned, and after which signals will be generated for values that weren't learned. If set to 0, a signal will be generated for all new values after the first value is learned.

learningMethod

enum

The learning method used to determine when signals should be generated for values that weren't learned. Allowed enum values: duration,threshold

default: duration

learningThreshold

enum

A number of occurrences after which signals will be generated for values that weren't learned. Allowed enum values: 0,1

sequenceDetectionOptions

object

Options on sequence detection method.

stepTransitions

[object]

Transitions defining the allowed order of steps and their evaluation windows.

child

string

Name of the child step.

evaluationWindow

enum

A time window is specified to match when at least one of the cases matches true. This is a sliding window and evaluates in real time. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

parent

string

Name of the parent step.

steps

[object]

Steps that define the conditions to be matched in sequence.

condition

string

Condition referencing rule queries (e.g., a > 0).

evaluationWindow

enum

A time window is specified to match when at least one of the cases matches true. This is a sliding window and evaluates in real time. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

name

string

Unique name identifying the step.

thirdPartyRuleOptions

object

Options on third party detection method.

defaultNotifications

[string]

Notification targets for the logs that do not correspond to any of the cases.

defaultStatus

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

rootQueries

[object]

Queries to be combined with third party case queries. Each of them can have different group by fields, to aggregate differently based on the type of alert.

groupByFields

[string]

Fields to group by.

query

string

Query to run on logs.

signalTitleTemplate

string

A template for the signal title; if omitted, the title is generated based on the case name.

queries

[ <oneOf>]

Queries for selecting logs which are part of the rule.

Option 1

object

Query for matching rule.

aggregation

enum

The aggregation type. Allowed enum values: count,cardinality,sum,max,new_value,geo_data,event_count,none

customQueryExtension

string

Query extension to append to the logs query.

dataSource

enum

Source of events, either logs, audit trail, security signals, or Datadog events. app_sec_spans is deprecated in favor of spans. Allowed enum values: logs,audit,app_sec_spans,spans,security_runtime,network,events,security_signals

default: logs

distinctFields

[string]

Field for which the cardinality is measured. Sent as an array.

groupByFields

[string]

Fields to group by.

hasOptionalGroupByFields

boolean

When false, events without a group-by value are ignored by the rule. When true, events with missing group-by fields are processed with N/A, replacing the missing values.

index

string

This field is currently unstable and might be removed in a minor version upgrade. The index to run the query on, if the dataSource is logs. Only used for scheduled rules - in other words, when the schedulingOptions field is present in the rule payload.

indexes

[string]

List of indexes to query when the dataSource is logs. Only used for scheduled rules, such as when the schedulingOptions field is present in the rule payload.

metric

string

DEPRECATED: (Deprecated) The target field to aggregate over when using the sum or max aggregations. metrics field should be used instead.

metrics

[string]

Group of target fields to aggregate over when using the sum, max, geo data, or new value aggregations. The sum, max, and geo data aggregations only accept one value in this list, whereas the new value aggregation accepts up to five values.

name

string

Name of the query.

query

string

Query to run on logs.

Option 2

object

Query for matching rule on signals.

aggregation

enum

The aggregation type. Allowed enum values: count,cardinality,sum,max,new_value,geo_data,event_count,none

correlatedByFields

[string]

Fields to group by.

correlatedQueryIndex

int32

Index of the rule query used to retrieve the correlated field.

metrics

[string]

Group of target fields to aggregate over.

name

string

Name of the query.

ruleId [required]

string

Rule ID to match on signals.

referenceTables

[object]

Reference tables for the rule.

checkPresence

boolean

Whether to include or exclude the matched values.

columnName

string

The name of the column in the reference table.

logFieldPath

string

The field in the log to match against the reference table.

ruleQueryName

string

The name of the query to apply the reference table to.

tableName

string

The name of the reference table.

schedulingOptions

object

Options for scheduled rules. When this field is present, the rule runs based on the schedule. When absent, it runs real-time on ingested logs.

rrule

string

Schedule for the rule queries, written in RRULE syntax. See RFC for syntax reference.

start

string

Start date for the schedule, in ISO 8601 format without timezone.

timezone

string

Time zone of the start date, in the tz database format.

tags

[string]

Tags for generated signals.

thirdPartyCases

[object]

Cases for generating signals from third-party rules. Only available for third-party rules.

customStatus

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

name

string

Name of the case.

notifications

[string]

Notification targets for each rule case.

query

string

A query to map a third party event to this case.

status

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

version

int32

The version of the rule being updated.

{
  "name": "Example-Security-Monitoring_cloud_updated",
  "isEnabled": false,
  "cases": [
    {
      "status": "info",
      "notifications": []
    }
  ],
  "options": {
    "complianceRuleOptions": {
      "resourceType": "gcp_compute_disk",
      "regoRule": {
        "policy": "package datadog\n\nimport data.datadog.output as dd_output\n\nimport future.keywords.contains\nimport future.keywords.if\nimport future.keywords.in\n\nmilliseconds_in_a_day := ((1000 * 60) * 60) * 24\n\neval(iam_service_account_key) = \"skip\" if {\n\tiam_service_account_key.disabled\n} else = \"pass\" if {\n\t(iam_service_account_key.resource_seen_at / milliseconds_in_a_day) - (iam_service_account_key.valid_after_time / milliseconds_in_a_day) <= 90\n} else = \"fail\"\n\n# This part remains unchanged for all rules\nresults contains result if {\n\tsome resource in input.resources[input.main_resource_type]\n\tresult := dd_output.format(resource, eval(resource))\n}\n",
        "resourceTypes": [
          "gcp_compute_disk"
        ]
      }
    }
  },
  "message": "ddd",
  "tags": [],
  "complianceSignalOptions": {
    "userActivationStatus": false,
    "userGroupByFields": []
  }
}
{
  "name": "Example-Security-Monitoring-Updated",
  "queries": [
    {
      "query": "@test:true",
      "aggregation": "count",
      "groupByFields": [],
      "distinctFields": [],
      "metrics": []
    }
  ],
  "filters": [],
  "cases": [
    {
      "name": "",
      "status": "info",
      "condition": "a > 0",
      "notifications": []
    }
  ],
  "options": {
    "evaluationWindow": 900,
    "keepAlive": 3600,
    "maxSignalDuration": 86400
  },
  "message": "Test rule",
  "tags": [],
  "isEnabled": true
}

Response

OK

Create a new rule.

Expand All

Field

Type

Description

Option 1

object

Rule.

calculatedFields

[object]

Calculated fields. Only allowed for scheduled rules - in other words, when schedulingOptions is also defined.

expression [required]

string

Expression.

name [required]

string

Field name.

cases

[object]

Cases for generating signals.

actions

[object]

Action to perform for each rule case.

options

object

Options for the rule action

duration

int64

Duration of the action in seconds. 0 indicates no expiration.

flaggedIPType

enum

Used with the case action of type 'flag_ip'. The value specified in this field is applied as a flag to the IP addresses. Allowed enum values: SUSPICIOUS,FLAGGED

userBehaviorName

string

Used with the case action of type 'user_behavior'. The value specified in this field is applied as a risk tag to all users affected by the rule.

type

enum

The action type. Allowed enum values: block_ip,block_user,user_behavior,flag_ip

condition

string

A rule case contains logical operations (>,>=, &&, ||) to determine if a signal should be generated based on the event counts in the previously defined queries.

customStatus

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

name

string

Name of the case.

notifications

[string]

Notification targets for each rule case.

status

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

complianceSignalOptions

object

How to generate compliance signals. Useful for cloud_configuration rules only.

defaultActivationStatus

boolean

The default activation status.

defaultGroupByFields

[string]

The default group by fields.

userActivationStatus

boolean

Whether signals will be sent.

userGroupByFields

[string]

Fields to use to group findings by when sending signals.

createdAt

int64

When the rule was created, timestamp in milliseconds.

creationAuthorId

int64

User ID of the user who created the rule.

customMessage

string

Custom/Overridden message for generated signals (used in case of Default rule update).

customName

string

Custom/Overridden name of the rule (used in case of Default rule update).

defaultTags

[string]

Default Tags for default rules (included in tags)

deprecationDate

int64

When the rule will be deprecated, timestamp in milliseconds.

filters

[object]

Additional queries to filter matched events before they are processed. This field is deprecated for log detection, signal correlation, and workload security rules.

action

enum

The type of filtering action. Allowed enum values: require,suppress

query

string

Query for selecting logs to apply the filtering action.

groupSignalsBy

[string]

Additional grouping to perform on top of the existing groups in the query section. Must be a subset of the existing groups.

hasExtendedTitle

boolean

Whether the notifications include the triggering group-by values in their title.

id

string

The ID of the rule.

isDefault

boolean

Whether the rule is included by default.

isDeleted

boolean

Whether the rule has been deleted.

isEnabled

boolean

Whether the rule is enabled.

message

string

Message for generated signals.

name

string

The name of the rule.

options

object

Options.

anomalyDetectionOptions

object

Options on anomaly detection method.

bucketDuration

enum

Duration in seconds of the time buckets used to aggregate events matched by the rule. Must be greater than or equal to 300. Allowed enum values: 300,600,900,1800,3600,10800

detectionTolerance

enum

An optional parameter that sets how permissive anomaly detection is. Higher values require higher deviations before triggering a signal. Allowed enum values: 1,2,3,4,5

instantaneousBaseline

boolean

When set to true, Datadog uses previous values that fall within the defined learning window to construct the baseline, enabling the system to establish an accurate baseline more rapidly rather than relying solely on gradual learning over time.

learningDuration

enum

Learning duration in hours. Anomaly detection waits for at least this amount of historical data before it starts evaluating. Allowed enum values: 1,6,12,24,48,168,336

learningPeriodBaseline

int64

An optional override baseline to apply while the rule is in the learning period. Must be greater than or equal to 0.

complianceRuleOptions

object

Options for cloud_configuration rules. Fields resourceType and regoRule are mandatory when managing custom cloud_configuration rules.

complexRule

boolean

Whether the rule is a complex one. Must be set to true if regoRule.resourceTypes contains more than one item. Defaults to false.

regoRule

object

Rule details.

policy [required]

string

resourceTypes [required]

[string]

List of resource types that will be evaluated upon. Must have at least one element.

resourceType

string

Main resource type to be checked by the rule. It should be specified again in regoRule.resourceTypes.

decreaseCriticalityBasedOnEnv

boolean

If true, signals in non-production environments have a lower severity than what is defined by the rule case, which can reduce signal noise. The severity is decreased by one level: CRITICAL in production becomes HIGH in non-production, HIGH becomes MEDIUM and so on. INFO remains INFO. The decrement is applied when the environment tag of the signal starts with staging, test or dev.

detectionMethod

enum

The detection method. Allowed enum values: threshold,new_value,anomaly_detection,impossible_travel,hardcoded,third_party,anomaly_threshold,sequence_detection

evaluationWindow

enum

A time window is specified to match when at least one of the cases matches true. This is a sliding window and evaluates in real time. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

hardcodedEvaluatorType

enum

Hardcoded evaluator type. Allowed enum values: log4shell

impossibleTravelOptions

object

Options on impossible travel detection method.

baselineUserLocations

boolean

If true, signals are suppressed for the first 24 hours. In that time, Datadog learns the user's regular access locations. This can be helpful to reduce noise and infer VPN usage or credentialed API access.

baselineUserLocationsDuration

int32

The duration in days during which Datadog learns the user's regular access locations. After this period, signals are generated for accesses from unknown locations.

keepAlive

enum

Once a signal is generated, the signal will remain "open" if a case is matched at least once within this keep alive window. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

maxSignalDuration

enum

A signal will "close" regardless of the query being matched once the time exceeds the maximum duration. This time is calculated from the first seen timestamp. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

newValueOptions

object

Options on new value detection method.

forgetAfter

int32

The duration in days after which a learned value is forgotten.

instantaneousBaseline

boolean

When set to true, Datadog uses previous values that fall within the defined learning window to construct the baseline, enabling the system to establish an accurate baseline more rapidly rather than relying solely on gradual learning over time.

learningDuration

int32

The duration in days during which values are learned, and after which signals will be generated for values that weren't learned. If set to 0, a signal will be generated for all new values after the first value is learned.

learningMethod

enum

The learning method used to determine when signals should be generated for values that weren't learned. Allowed enum values: duration,threshold

default: duration

learningThreshold

enum

A number of occurrences after which signals will be generated for values that weren't learned. Allowed enum values: 0,1

sequenceDetectionOptions

object

Options on sequence detection method.

stepTransitions

[object]

Transitions defining the allowed order of steps and their evaluation windows.

child

string

Name of the child step.

evaluationWindow

enum

A time window is specified to match when at least one of the cases matches true. This is a sliding window and evaluates in real time. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

parent

string

Name of the parent step.

steps

[object]

Steps that define the conditions to be matched in sequence.

condition

string

Condition referencing rule queries (e.g., a > 0).

evaluationWindow

enum

A time window is specified to match when at least one of the cases matches true. This is a sliding window and evaluates in real time. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

name

string

Unique name identifying the step.

thirdPartyRuleOptions

object

Options on third party detection method.

defaultNotifications

[string]

Notification targets for the logs that do not correspond to any of the cases.

defaultStatus

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

rootQueries

[object]

Queries to be combined with third party case queries. Each of them can have different group by fields, to aggregate differently based on the type of alert.

groupByFields

[string]

Fields to group by.

query

string

Query to run on logs.

signalTitleTemplate

string

A template for the signal title; if omitted, the title is generated based on the case name.

queries

[object]

Queries for selecting logs which are part of the rule.

aggregation

enum

The aggregation type. Allowed enum values: count,cardinality,sum,max,new_value,geo_data,event_count,none

customQueryExtension

string

Query extension to append to the logs query.

dataSource

enum

Source of events, either logs, audit trail, security signals, or Datadog events. app_sec_spans is deprecated in favor of spans. Allowed enum values: logs,audit,app_sec_spans,spans,security_runtime,network,events,security_signals

default: logs

distinctFields

[string]

Field for which the cardinality is measured. Sent as an array.

groupByFields

[string]

Fields to group by.

hasOptionalGroupByFields

boolean

When false, events without a group-by value are ignored by the rule. When true, events with missing group-by fields are processed with N/A, replacing the missing values.

index

string

This field is currently unstable and might be removed in a minor version upgrade. The index to run the query on, if the dataSource is logs. Only used for scheduled rules - in other words, when the schedulingOptions field is present in the rule payload.

indexes

[string]

List of indexes to query when the dataSource is logs. Only used for scheduled rules, such as when the schedulingOptions field is present in the rule payload.

metric

string

DEPRECATED: (Deprecated) The target field to aggregate over when using the sum or max aggregations. metrics field should be used instead.

metrics

[string]

Group of target fields to aggregate over when using the sum, max, geo data, or new value aggregations. The sum, max, and geo data aggregations only accept one value in this list, whereas the new value aggregation accepts up to five values.

name

string

Name of the query.

query

string

Query to run on logs.

referenceTables

[object]

Reference tables for the rule.

checkPresence

boolean

Whether to include or exclude the matched values.

columnName

string

The name of the column in the reference table.

logFieldPath

string

The field in the log to match against the reference table.

ruleQueryName

string

The name of the query to apply the reference table to.

tableName

string

The name of the reference table.

schedulingOptions

object

Options for scheduled rules. When this field is present, the rule runs based on the schedule. When absent, it runs real-time on ingested logs.

rrule

string

Schedule for the rule queries, written in RRULE syntax. See RFC for syntax reference.

start

string

Start date for the schedule, in ISO 8601 format without timezone.

timezone

string

Time zone of the start date, in the tz database format.

tags

[string]

Tags for generated signals.

thirdPartyCases

[object]

Cases for generating signals from third-party rules. Only available for third-party rules.

customStatus

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

name

string

Name of the case.

notifications

[string]

Notification targets for each rule case.

query

string

A query to map a third party event to this case.

status

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

type

enum

The rule type. Allowed enum values: log_detection,infrastructure_configuration,workload_security,cloud_configuration,application_security,api_security,workload_activity

updateAuthorId

int64

User ID of the user who updated the rule.

updatedAt

int64

The date the rule was last updated, in milliseconds.

version

int64

The version of the rule.

Option 2

object

Rule.

cases

[object]

Cases for generating signals.

actions

[object]

Action to perform for each rule case.

options

object

Options for the rule action

duration

int64

Duration of the action in seconds. 0 indicates no expiration.

flaggedIPType

enum

Used with the case action of type 'flag_ip'. The value specified in this field is applied as a flag to the IP addresses. Allowed enum values: SUSPICIOUS,FLAGGED

userBehaviorName

string

Used with the case action of type 'user_behavior'. The value specified in this field is applied as a risk tag to all users affected by the rule.

type

enum

The action type. Allowed enum values: block_ip,block_user,user_behavior,flag_ip

condition

string

A rule case contains logical operations (>,>=, &&, ||) to determine if a signal should be generated based on the event counts in the previously defined queries.

customStatus

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

name

string

Name of the case.

notifications

[string]

Notification targets for each rule case.

status

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

createdAt

int64

When the rule was created, timestamp in milliseconds.

creationAuthorId

int64

User ID of the user who created the rule.

customMessage

string

Custom/Overridden message for generated signals (used in case of Default rule update).

customName

string

Custom/Overridden name of the rule (used in case of Default rule update).

deprecationDate

int64

When the rule will be deprecated, timestamp in milliseconds.

filters

[object]

Additional queries to filter matched events before they are processed. This field is deprecated for log detection, signal correlation, and workload security rules.

action

enum

The type of filtering action. Allowed enum values: require,suppress

query

string

Query for selecting logs to apply the filtering action.

hasExtendedTitle

boolean

Whether the notifications include the triggering group-by values in their title.

id

string

The ID of the rule.

isDefault

boolean

Whether the rule is included by default.

isDeleted

boolean

Whether the rule has been deleted.

isEnabled

boolean

Whether the rule is enabled.

message

string

Message for generated signals.

name

string

The name of the rule.

options

object

Options.

anomalyDetectionOptions

object

Options on anomaly detection method.

bucketDuration

enum

Duration in seconds of the time buckets used to aggregate events matched by the rule. Must be greater than or equal to 300. Allowed enum values: 300,600,900,1800,3600,10800

detectionTolerance

enum

An optional parameter that sets how permissive anomaly detection is. Higher values require higher deviations before triggering a signal. Allowed enum values: 1,2,3,4,5

instantaneousBaseline

boolean

When set to true, Datadog uses previous values that fall within the defined learning window to construct the baseline, enabling the system to establish an accurate baseline more rapidly rather than relying solely on gradual learning over time.

learningDuration

enum

Learning duration in hours. Anomaly detection waits for at least this amount of historical data before it starts evaluating. Allowed enum values: 1,6,12,24,48,168,336

learningPeriodBaseline

int64

An optional override baseline to apply while the rule is in the learning period. Must be greater than or equal to 0.

complianceRuleOptions

object

Options for cloud_configuration rules. Fields resourceType and regoRule are mandatory when managing custom cloud_configuration rules.

complexRule

boolean

Whether the rule is a complex one. Must be set to true if regoRule.resourceTypes contains more than one item. Defaults to false.

regoRule

object

Rule details.

policy [required]

string

resourceTypes [required]

[string]

List of resource types that will be evaluated upon. Must have at least one element.

resourceType

string

Main resource type to be checked by the rule. It should be specified again in regoRule.resourceTypes.

decreaseCriticalityBasedOnEnv

boolean

If true, signals in non-production environments have a lower severity than what is defined by the rule case, which can reduce signal noise. The severity is decreased by one level: CRITICAL in production becomes HIGH in non-production, HIGH becomes MEDIUM and so on. INFO remains INFO. The decrement is applied when the environment tag of the signal starts with staging, test or dev.

detectionMethod

enum

The detection method. Allowed enum values: threshold,new_value,anomaly_detection,impossible_travel,hardcoded,third_party,anomaly_threshold,sequence_detection

evaluationWindow

enum

A time window is specified to match when at least one of the cases matches true. This is a sliding window and evaluates in real time. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

hardcodedEvaluatorType

enum

Hardcoded evaluator type. Allowed enum values: log4shell

impossibleTravelOptions

object

Options on impossible travel detection method.

baselineUserLocations

boolean

If true, signals are suppressed for the first 24 hours. In that time, Datadog learns the user's regular access locations. This can be helpful to reduce noise and infer VPN usage or credentialed API access.

baselineUserLocationsDuration

int32

The duration in days during which Datadog learns the user's regular access locations. After this period, signals are generated for accesses from unknown locations.

keepAlive

enum

Once a signal is generated, the signal will remain "open" if a case is matched at least once within this keep alive window. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

maxSignalDuration

enum

A signal will "close" regardless of the query being matched once the time exceeds the maximum duration. This time is calculated from the first seen timestamp. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

newValueOptions

object

Options on new value detection method.

forgetAfter

int32

The duration in days after which a learned value is forgotten.

instantaneousBaseline

boolean

When set to true, Datadog uses previous values that fall within the defined learning window to construct the baseline, enabling the system to establish an accurate baseline more rapidly rather than relying solely on gradual learning over time.

learningDuration

int32

The duration in days during which values are learned, and after which signals will be generated for values that weren't learned. If set to 0, a signal will be generated for all new values after the first value is learned.

learningMethod

enum

The learning method used to determine when signals should be generated for values that weren't learned. Allowed enum values: duration,threshold

default: duration

learningThreshold

enum

A number of occurrences after which signals will be generated for values that weren't learned. Allowed enum values: 0,1

sequenceDetectionOptions

object

Options on sequence detection method.

stepTransitions

[object]

Transitions defining the allowed order of steps and their evaluation windows.

child

string

Name of the child step.

evaluationWindow

enum

A time window is specified to match when at least one of the cases matches true. This is a sliding window and evaluates in real time. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

parent

string

Name of the parent step.

steps

[object]

Steps that define the conditions to be matched in sequence.

condition

string

Condition referencing rule queries (e.g., a > 0).

evaluationWindow

enum

A time window is specified to match when at least one of the cases matches true. This is a sliding window and evaluates in real time. For third party detection method, this field is not used. Allowed enum values: 0,60,300,600,900,1800,3600,7200,10800,21600

Show 2 more,43200,86400

name

string

Unique name identifying the step.

thirdPartyRuleOptions

object

Options on third party detection method.

defaultNotifications

[string]

Notification targets for the logs that do not correspond to any of the cases.

defaultStatus

enum

Severity of the Security Signal. Allowed enum values: info,low,medium,high,critical

rootQueries

[object]

Queries to be combined with third party case queries. Each of them can have different group by fields, to aggregate differently based on the type of alert.

groupByFields

[string]

Fields to group by.

query

string

Query to run on logs.

signalTitleTemplate

string

A template for the signal title; if omitted, the title is generated based on the case name.

queries

[object]

Queries for selecting logs which are part of the rule.

aggregation

enum

The aggregation type. Allowed enum values: count,cardinality,sum,max,new_value,geo_data,event_count,none

correlatedByFields

[string]

Fields to correlate by.

correlatedQueryIndex

int32

Index of the rule query used to retrieve the correlated field.

defaultRuleId

string

Default Rule ID to match on signals.

distinctFields

[string]

Field for which the cardinality is measured. Sent as an array.

groupByFields

[string]

Fields to group by.

metrics

[string]

Group of target fields to aggregate over.

name

string

Name of the query.

ruleId

string

Rule ID to match on signals.

tags

[string]

Tags for generated signals.

type

enum

The rule type. Allowed enum values: signal_correlation

updateAuthorId

int64

User ID of the user who updated the rule.

version

int64

The version of the rule.

{
  "calculatedFields": [
    {
      "expression": "@request_end_timestamp - @request_start_timestamp",
      "name": "response_time"
    }
  ],
  "cases": [
    {
      "actions": [
        {
          "options": {
            "duration": 0,
            "flaggedIPType": "FLAGGED",
            "userBehaviorName": "string"
          },
          "type": "string"
        }
      ],
      "condition": "string",
      "customStatus": "critical",
      "name": "string",
      "notifications": [],
      "status": "critical"
    }
  ],
  "complianceSignalOptions": {
    "defaultActivationStatus": false,
    "defaultGroupByFields": [],
    "userActivationStatus": false,
    "userGroupByFields": []
  },
  "createdAt": "integer",
  "creationAuthorId": "integer",
  "customMessage": "string",
  "customName": "string",
  "defaultTags": [
    "security:attacks"
  ],
  "deprecationDate": "integer",
  "filters": [
    {
      "action": "string",
      "query": "string"
    }
  ],
  "groupSignalsBy": [
    "service"
  ],
  "hasExtendedTitle": false,
  "id": "string",
  "isDefault": false,
  "isDeleted": false,
  "isEnabled": false,
  "message": "string",
  "name": "string",
  "options": {
    "anomalyDetectionOptions": {
      "bucketDuration": 300,
      "detectionTolerance": 5,
      "instantaneousBaseline": false,
      "learningDuration": "integer",
      "learningPeriodBaseline": "integer"
    },
    "complianceRuleOptions": {
      "complexRule": false,
      "regoRule": {
        "policy": "package datadog\n\nimport data.datadog.output as dd_output\nimport future.keywords.contains\nimport future.keywords.if\nimport future.keywords.in\n\neval(resource) = \"skip\" if {\n  # Logic that evaluates to true if the resource should be skipped\n  true\n} else = \"pass\" {\n  # Logic that evaluates to true if the resource is compliant\n  true\n} else = \"fail\" {\n  # Logic that evaluates to true if the resource is not compliant\n  true\n}\n\n# This part remains unchanged for all rules\nresults contains result if {\n  some resource in input.resources[input.main_resource_type]\n  result := dd_output.format(resource, eval(resource))\n}",
        "resourceTypes": [
          "gcp_iam_service_account",
          "gcp_iam_policy"
        ]
      },
      "resourceType": "aws_acm"
    },
    "decreaseCriticalityBasedOnEnv": false,
    "detectionMethod": "string",
    "evaluationWindow": "integer",
    "hardcodedEvaluatorType": "string",
    "impossibleTravelOptions": {
      "baselineUserLocations": true,
      "baselineUserLocationsDuration": "integer"
    },
    "keepAlive": "integer",
    "maxSignalDuration": "integer",
    "newValueOptions": {
      "forgetAfter": "integer",
      "instantaneousBaseline": false,
      "learningDuration": "integer",
      "learningMethod": "string",
      "learningThreshold": "integer"
    },
    "sequenceDetectionOptions": {
      "stepTransitions": [
        {
          "child": "string",
          "evaluationWindow": "integer",
          "parent": "string"
        }
      ],
      "steps": [
        {
          "condition": "string",
          "evaluationWindow": "integer",
          "name": "string"
        }
      ]
    },
    "thirdPartyRuleOptions": {
      "defaultNotifications": [],
      "defaultStatus": "critical",
      "rootQueries": [
        {
          "groupByFields": [],
          "query": "source:cloudtrail"
        }
      ],
      "signalTitleTemplate": "string"
    }
  },
  "queries": [
    {
      "aggregation": "string",
      "customQueryExtension": "a > 3",
      "dataSource": "logs",
      "distinctFields": [],
      "groupByFields": [],
      "hasOptionalGroupByFields": false,
      "index": "string",
      "indexes": [],
      "metric": "string",
      "metrics": [],
      "name": "string",
      "query": "a > 3"
    }
  ],
  "referenceTables": [
    {
      "checkPresence": false,
      "columnName": "string",
      "logFieldPath": "string",
      "ruleQueryName": "string",
      "tableName": "string"
    }
  ],
  "schedulingOptions": {
    "rrule": "FREQ=HOURLY;INTERVAL=1;",
    "start": "2025-07-14T12:00:00",
    "timezone": "America/New_York"
  },
  "tags": [],
  "thirdPartyCases": [
    {
      "customStatus": "critical",
      "name": "string",
      "notifications": [],
      "query": "string",
      "status": "critical"
    }
  ],
  "type": "string",
  "updateAuthorId": "integer",
  "updatedAt": "integer",
  "version": "integer"
}

Bad Request

API error response.

Expand All

Field

Type

Description

errors [required]

[string]

A list of errors.

{
  "errors": [
    "Bad Request"
  ]
}

Concurrent Modification

API error response.

Expand All

Field

Type

Description

errors [required]

[string]

A list of errors.

{
  "errors": [
    "Bad Request"
  ]
}

Not Authorized

API error response.

Expand All

Field

Type

Description

errors [required]

[string]

A list of errors.

{
  "errors": [
    "Bad Request"
  ]
}

Not Found

API error response.

Expand All

Field

Type

Description

errors [required]

[string]

A list of errors.

{
  "errors": [
    "Bad Request"
  ]
}

Too many requests

API error response.

Expand All

Field

Type

Description

errors [required]

[string]

A list of errors.

{
  "errors": [
    "Bad Request"
  ]
}

Code Example

                          ## default
# 

# Path parameters
export rule_id="CHANGE_ME"
# Curl command
curl -X PUT "https://api.ap1.datadoghq.com"https://api.ap2.datadoghq.com"https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.us2.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com"https://api.us5.datadoghq.com/api/v2/security_monitoring/rules/${rule_id}" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_APP_KEY}" \ -d @- << EOF { "cases": [ { "condition": "a \u003e 0", "name": "", "notifications": [], "status": "info" } ], "filters": [], "isEnabled": true, "message": "Test rule", "name": "My security monitoring rule.", "options": { "evaluationWindow": 900, "keepAlive": 3600, "maxSignalDuration": 86400 }, "queries": [ { "aggregation": "count", "distinctFields": [], "groupByFields": [], "metrics": [], "query": "@test:true" } ], "tags": [] } EOF
                          ## default
# 

# Path parameters
export rule_id="CHANGE_ME"
# Curl command
curl -X PUT "https://api.ap1.datadoghq.com"https://api.ap2.datadoghq.com"https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.us2.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com"https://api.us5.datadoghq.com/api/v2/security_monitoring/rules/${rule_id}" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_APP_KEY}" \ -d @- << EOF { "cases": [ { "condition": "a \u003e 0", "name": "", "notifications": [], "status": "info" } ], "filters": [], "isEnabled": true, "message": "Test rule", "name": "My security monitoring rule.", "options": { "evaluationWindow": 900, "keepAlive": 3600, "maxSignalDuration": 86400 }, "queries": [ { "aggregation": "count", "distinctFields": [], "groupByFields": [], "metrics": [], "query": "@test:true" } ], "tags": [] } EOF
// Update a cloud configuration rule's details returns "OK" response

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
	"github.com/DataDog/datadog-api-client-go/v2/api/datadogV2"
)

func main() {
	// there is a valid "cloud_configuration_rule" in the system
	CloudConfigurationRuleID := os.Getenv("CLOUD_CONFIGURATION_RULE_ID")

	body := datadogV2.SecurityMonitoringRuleUpdatePayload{
		Name:      datadog.PtrString("Example-Security-Monitoring_cloud_updated"),
		IsEnabled: datadog.PtrBool(false),
		Cases: []datadogV2.SecurityMonitoringRuleCase{
			{
				Status:        datadogV2.SECURITYMONITORINGRULESEVERITY_INFO.Ptr(),
				Notifications: []string{},
			},
		},
		Options: &datadogV2.SecurityMonitoringRuleOptions{
			ComplianceRuleOptions: &datadogV2.CloudConfigurationComplianceRuleOptions{
				ResourceType: datadog.PtrString("gcp_compute_disk"),
				RegoRule: &datadogV2.CloudConfigurationRegoRule{
					Policy: `package datadog

import data.datadog.output as dd_output

import future.keywords.contains
import future.keywords.if
import future.keywords.in

milliseconds_in_a_day := ((1000 * 60) * 60) * 24

eval(iam_service_account_key) = "skip" if {
	iam_service_account_key.disabled
} else = "pass" if {
	(iam_service_account_key.resource_seen_at / milliseconds_in_a_day) - (iam_service_account_key.valid_after_time / milliseconds_in_a_day) <= 90
} else = "fail"

# This part remains unchanged for all rules
results contains result if {
	some resource in input.resources[input.main_resource_type]
	result := dd_output.format(resource, eval(resource))
}
`,
					ResourceTypes: []string{
						"gcp_compute_disk",
					},
				},
			},
		},
		Message: datadog.PtrString("ddd"),
		Tags:    []string{},
		ComplianceSignalOptions: &datadogV2.CloudConfigurationRuleComplianceSignalOptions{
			UserActivationStatus: *datadog.NewNullableBool(datadog.PtrBool(false)),
			UserGroupByFields:    *datadog.NewNullableList(&[]string{}),
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV2.NewSecurityMonitoringApi(apiClient)
	resp, r, err := api.UpdateSecurityMonitoringRule(ctx, CloudConfigurationRuleID, body)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error when calling `SecurityMonitoringApi.UpdateSecurityMonitoringRule`: %v\n", err)
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
	}

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `SecurityMonitoringApi.UpdateSecurityMonitoringRule`:\n%s\n", responseContent)
}
// Update an existing rule returns "OK" response

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
	"github.com/DataDog/datadog-api-client-go/v2/api/datadogV2"
)

func main() {
	// there is a valid "security_rule" in the system
	SecurityRuleID := os.Getenv("SECURITY_RULE_ID")

	body := datadogV2.SecurityMonitoringRuleUpdatePayload{
		Name: datadog.PtrString("Example-Security-Monitoring-Updated"),
		Queries: []datadogV2.SecurityMonitoringRuleQuery{
			datadogV2.SecurityMonitoringRuleQuery{
				SecurityMonitoringStandardRuleQuery: &datadogV2.SecurityMonitoringStandardRuleQuery{
					Query:          datadog.PtrString("@test:true"),
					Aggregation:    datadogV2.SECURITYMONITORINGRULEQUERYAGGREGATION_COUNT.Ptr(),
					GroupByFields:  []string{},
					DistinctFields: []string{},
					Metrics:        []string{},
				}},
		},
		Filters: []datadogV2.SecurityMonitoringFilter{},
		Cases: []datadogV2.SecurityMonitoringRuleCase{
			{
				Name:          datadog.PtrString(""),
				Status:        datadogV2.SECURITYMONITORINGRULESEVERITY_INFO.Ptr(),
				Condition:     datadog.PtrString("a > 0"),
				Notifications: []string{},
			},
		},
		Options: &datadogV2.SecurityMonitoringRuleOptions{
			EvaluationWindow:  datadogV2.SECURITYMONITORINGRULEEVALUATIONWINDOW_FIFTEEN_MINUTES.Ptr(),
			KeepAlive:         datadogV2.SECURITYMONITORINGRULEKEEPALIVE_ONE_HOUR.Ptr(),
			MaxSignalDuration: datadogV2.SECURITYMONITORINGRULEMAXSIGNALDURATION_ONE_DAY.Ptr(),
		},
		Message:   datadog.PtrString("Test rule"),
		Tags:      []string{},
		IsEnabled: datadog.PtrBool(true),
	}
	ctx := datadog.NewDefaultContext(context.Background())
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV2.NewSecurityMonitoringApi(apiClient)
	resp, r, err := api.UpdateSecurityMonitoringRule(ctx, SecurityRuleID, body)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error when calling `SecurityMonitoringApi.UpdateSecurityMonitoringRule`: %v\n", err)
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
	}

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `SecurityMonitoringApi.UpdateSecurityMonitoringRule`:\n%s\n", responseContent)
}

Instructions

First install the library and its dependencies and then save the example to main.go and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" go run "main.go"
// Update a cloud configuration rule's details returns "OK" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v2.api.SecurityMonitoringApi;
import com.datadog.api.client.v2.model.CloudConfigurationComplianceRuleOptions;
import com.datadog.api.client.v2.model.CloudConfigurationRegoRule;
import com.datadog.api.client.v2.model.CloudConfigurationRuleComplianceSignalOptions;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleCase;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleOptions;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleResponse;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleSeverity;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleUpdatePayload;
import java.util.Collections;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    SecurityMonitoringApi apiInstance = new SecurityMonitoringApi(defaultClient);

    // there is a valid "cloud_configuration_rule" in the system
    String CLOUD_CONFIGURATION_RULE_ID = System.getenv("CLOUD_CONFIGURATION_RULE_ID");

    SecurityMonitoringRuleUpdatePayload body =
        new SecurityMonitoringRuleUpdatePayload()
            .name("Example-Security-Monitoring_cloud_updated")
            .isEnabled(false)
            .cases(
                Collections.singletonList(
                    new SecurityMonitoringRuleCase().status(SecurityMonitoringRuleSeverity.INFO)))
            .options(
                new SecurityMonitoringRuleOptions()
                    .complianceRuleOptions(
                        new CloudConfigurationComplianceRuleOptions()
                            .resourceType("gcp_compute_disk")
                            .regoRule(
                                new CloudConfigurationRegoRule()
                                    .policy(
                                        """
package datadog

import data.datadog.output as dd_output

import future.keywords.contains
import future.keywords.if
import future.keywords.in

milliseconds_in_a_day := ((1000 * 60) * 60) * 24

eval(iam_service_account_key) = "skip" if {
	iam_service_account_key.disabled
} else = "pass" if {
	(iam_service_account_key.resource_seen_at / milliseconds_in_a_day) - (iam_service_account_key.valid_after_time / milliseconds_in_a_day) <= 90
} else = "fail"

# This part remains unchanged for all rules
results contains result if {
	some resource in input.resources[input.main_resource_type]
	result := dd_output.format(resource, eval(resource))
}

""")
                                    .resourceTypes(Collections.singletonList("gcp_compute_disk")))))
            .message("ddd")
            .complianceSignalOptions(
                new CloudConfigurationRuleComplianceSignalOptions().userActivationStatus(false));

    try {
      SecurityMonitoringRuleResponse result =
          apiInstance.updateSecurityMonitoringRule(CLOUD_CONFIGURATION_RULE_ID, body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println(
          "Exception when calling SecurityMonitoringApi#updateSecurityMonitoringRule");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}
// Update an existing rule returns "OK" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v2.api.SecurityMonitoringApi;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleCase;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleEvaluationWindow;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleKeepAlive;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleMaxSignalDuration;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleOptions;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleQuery;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleQueryAggregation;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleResponse;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleSeverity;
import com.datadog.api.client.v2.model.SecurityMonitoringRuleUpdatePayload;
import com.datadog.api.client.v2.model.SecurityMonitoringStandardRuleQuery;
import java.util.Collections;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    SecurityMonitoringApi apiInstance = new SecurityMonitoringApi(defaultClient);

    // there is a valid "security_rule" in the system
    String SECURITY_RULE_ID = System.getenv("SECURITY_RULE_ID");

    SecurityMonitoringRuleUpdatePayload body =
        new SecurityMonitoringRuleUpdatePayload()
            .name("Example-Security-Monitoring-Updated")
            .queries(
                Collections.singletonList(
                    new SecurityMonitoringRuleQuery(
                        new SecurityMonitoringStandardRuleQuery()
                            .query("@test:true")
                            .aggregation(SecurityMonitoringRuleQueryAggregation.COUNT))))
            .cases(
                Collections.singletonList(
                    new SecurityMonitoringRuleCase()
                        .name("")
                        .status(SecurityMonitoringRuleSeverity.INFO)
                        .condition("a > 0")))
            .options(
                new SecurityMonitoringRuleOptions()
                    .evaluationWindow(SecurityMonitoringRuleEvaluationWindow.FIFTEEN_MINUTES)
                    .keepAlive(SecurityMonitoringRuleKeepAlive.ONE_HOUR)
                    .maxSignalDuration(SecurityMonitoringRuleMaxSignalDuration.ONE_DAY))
            .message("Test rule")
            .isEnabled(true);

    try {
      SecurityMonitoringRuleResponse result =
          apiInstance.updateSecurityMonitoringRule(SECURITY_RULE_ID, body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println(
          "Exception when calling SecurityMonitoringApi#updateSecurityMonitoringRule");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}

Instructions

First install the library and its dependencies and then save the example to Example.java and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" java "Example.java"
"""
Update a cloud configuration rule's details returns "OK" response
"""

from os import environ
from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v2.api.security_monitoring_api import SecurityMonitoringApi
from datadog_api_client.v2.model.cloud_configuration_compliance_rule_options import (
    CloudConfigurationComplianceRuleOptions,
)
from datadog_api_client.v2.model.cloud_configuration_rego_rule import CloudConfigurationRegoRule
from datadog_api_client.v2.model.cloud_configuration_rule_compliance_signal_options import (
    CloudConfigurationRuleComplianceSignalOptions,
)
from datadog_api_client.v2.model.security_monitoring_rule_case import SecurityMonitoringRuleCase
from datadog_api_client.v2.model.security_monitoring_rule_options import SecurityMonitoringRuleOptions
from datadog_api_client.v2.model.security_monitoring_rule_severity import SecurityMonitoringRuleSeverity
from datadog_api_client.v2.model.security_monitoring_rule_update_payload import SecurityMonitoringRuleUpdatePayload

# there is a valid "cloud_configuration_rule" in the system
CLOUD_CONFIGURATION_RULE_ID = environ["CLOUD_CONFIGURATION_RULE_ID"]

body = SecurityMonitoringRuleUpdatePayload(
    name="Example-Security-Monitoring_cloud_updated",
    is_enabled=False,
    cases=[
        SecurityMonitoringRuleCase(
            status=SecurityMonitoringRuleSeverity.INFO,
            notifications=[],
        ),
    ],
    options=SecurityMonitoringRuleOptions(
        compliance_rule_options=CloudConfigurationComplianceRuleOptions(
            resource_type="gcp_compute_disk",
            rego_rule=CloudConfigurationRegoRule(
                policy='package datadog\n\nimport data.datadog.output as dd_output\n\nimport future.keywords.contains\nimport future.keywords.if\nimport future.keywords.in\n\nmilliseconds_in_a_day := ((1000 * 60) * 60) * 24\n\neval(iam_service_account_key) = "skip" if {\n\tiam_service_account_key.disabled\n} else = "pass" if {\n\t(iam_service_account_key.resource_seen_at / milliseconds_in_a_day) - (iam_service_account_key.valid_after_time / milliseconds_in_a_day) <= 90\n} else = "fail"\n\n# This part remains unchanged for all rules\nresults contains result if {\n\tsome resource in input.resources[input.main_resource_type]\n\tresult := dd_output.format(resource, eval(resource))\n}\n',
                resource_types=[
                    "gcp_compute_disk",
                ],
            ),
        ),
    ),
    message="ddd",
    tags=[],
    compliance_signal_options=CloudConfigurationRuleComplianceSignalOptions(
        user_activation_status=False,
        user_group_by_fields=[],
    ),
)

configuration = Configuration()
with ApiClient(configuration) as api_client:
    api_instance = SecurityMonitoringApi(api_client)
    response = api_instance.update_security_monitoring_rule(rule_id=CLOUD_CONFIGURATION_RULE_ID, body=body)

    print(response)
"""
Update an existing rule returns "OK" response
"""

from os import environ
from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v2.api.security_monitoring_api import SecurityMonitoringApi
from datadog_api_client.v2.model.security_monitoring_rule_case import SecurityMonitoringRuleCase
from datadog_api_client.v2.model.security_monitoring_rule_evaluation_window import (
    SecurityMonitoringRuleEvaluationWindow,
)
from datadog_api_client.v2.model.security_monitoring_rule_keep_alive import SecurityMonitoringRuleKeepAlive
from datadog_api_client.v2.model.security_monitoring_rule_max_signal_duration import (
    SecurityMonitoringRuleMaxSignalDuration,
)
from datadog_api_client.v2.model.security_monitoring_rule_options import SecurityMonitoringRuleOptions
from datadog_api_client.v2.model.security_monitoring_rule_query_aggregation import (
    SecurityMonitoringRuleQueryAggregation,
)
from datadog_api_client.v2.model.security_monitoring_rule_severity import SecurityMonitoringRuleSeverity
from datadog_api_client.v2.model.security_monitoring_rule_update_payload import SecurityMonitoringRuleUpdatePayload
from datadog_api_client.v2.model.security_monitoring_standard_rule_query import SecurityMonitoringStandardRuleQuery

# there is a valid "security_rule" in the system
SECURITY_RULE_ID = environ["SECURITY_RULE_ID"]

body = SecurityMonitoringRuleUpdatePayload(
    name="Example-Security-Monitoring-Updated",
    queries=[
        SecurityMonitoringStandardRuleQuery(
            query="@test:true",
            aggregation=SecurityMonitoringRuleQueryAggregation.COUNT,
            group_by_fields=[],
            distinct_fields=[],
            metrics=[],
        ),
    ],
    filters=[],
    cases=[
        SecurityMonitoringRuleCase(
            name="",
            status=SecurityMonitoringRuleSeverity.INFO,
            condition="a > 0",
            notifications=[],
        ),
    ],
    options=SecurityMonitoringRuleOptions(
        evaluation_window=SecurityMonitoringRuleEvaluationWindow.FIFTEEN_MINUTES,
        keep_alive=SecurityMonitoringRuleKeepAlive.ONE_HOUR,
        max_signal_duration=SecurityMonitoringRuleMaxSignalDuration.ONE_DAY,
    ),
    message="Test rule",
    tags=[],
    is_enabled=True,
)

configuration = Configuration()
with ApiClient(configuration) as api_client:
    api_instance = SecurityMonitoringApi(api_client)
    response = api_instance.update_security_monitoring_rule(rule_id=SECURITY_RULE_ID, body=body)

    print(response)

Instructions

First install the library and its dependencies and then save the example to example.py and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" python3 "example.py"
# Update a cloud configuration rule's details returns "OK" response

require "datadog_api_client"
api_instance = DatadogAPIClient::V2::SecurityMonitoringAPI.new

# there is a valid "cloud_configuration_rule" in the system
CLOUD_CONFIGURATION_RULE_ID = ENV["CLOUD_CONFIGURATION_RULE_ID"]

body = DatadogAPIClient::V2::SecurityMonitoringRuleUpdatePayload.new({
  name: "Example-Security-Monitoring_cloud_updated",
  is_enabled: false,
  cases: [
    DatadogAPIClient::V2::SecurityMonitoringRuleCase.new({
      status: DatadogAPIClient::V2::SecurityMonitoringRuleSeverity::INFO,
      notifications: [],
    }),
  ],
  options: DatadogAPIClient::V2::SecurityMonitoringRuleOptions.new({
    compliance_rule_options: DatadogAPIClient::V2::CloudConfigurationComplianceRuleOptions.new({
      resource_type: "gcp_compute_disk",
      rego_rule: DatadogAPIClient::V2::CloudConfigurationRegoRule.new({
        policy: 'package datadog\n\nimport data.datadog.output as dd_output\n\nimport future.keywords.contains\nimport future.keywords.if\nimport future.keywords.in\n\nmilliseconds_in_a_day := ((1000 * 60) * 60) * 24\n\neval(iam_service_account_key) = "skip" if {\n\tiam_service_account_key.disabled\n} else = "pass" if {\n\t(iam_service_account_key.resource_seen_at / milliseconds_in_a_day) - (iam_service_account_key.valid_after_time / milliseconds_in_a_day) <= 90\n} else = "fail"\n\n# This part remains unchanged for all rules\nresults contains result if {\n\tsome resource in input.resources[input.main_resource_type]\n\tresult := dd_output.format(resource, eval(resource))\n}\n',
        resource_types: [
          "gcp_compute_disk",
        ],
      }),
    }),
  }),
  message: "ddd",
  tags: [],
  compliance_signal_options: DatadogAPIClient::V2::CloudConfigurationRuleComplianceSignalOptions.new({
    user_activation_status: false,
    user_group_by_fields: [],
  }),
})
p api_instance.update_security_monitoring_rule(CLOUD_CONFIGURATION_RULE_ID, body)
# Update an existing rule returns "OK" response

require "datadog_api_client"
api_instance = DatadogAPIClient::V2::SecurityMonitoringAPI.new

# there is a valid "security_rule" in the system
SECURITY_RULE_ID = ENV["SECURITY_RULE_ID"]

body = DatadogAPIClient::V2::SecurityMonitoringRuleUpdatePayload.new({
  name: "Example-Security-Monitoring-Updated",
  queries: [
    DatadogAPIClient::V2::SecurityMonitoringStandardRuleQuery.new({
      query: "@test:true",
      aggregation: DatadogAPIClient::V2::SecurityMonitoringRuleQueryAggregation::COUNT,
      group_by_fields: [],
      distinct_fields: [],
      metrics: [],
    }),
  ],
  filters: [],
  cases: [
    DatadogAPIClient::V2::SecurityMonitoringRuleCase.new({
      name: "",
      status: DatadogAPIClient::V2::SecurityMonitoringRuleSeverity::INFO,
      condition: "a > 0",
      notifications: [],
    }),
  ],
  options: DatadogAPIClient::V2::SecurityMonitoringRuleOptions.new({
    evaluation_window: DatadogAPIClient::V2::SecurityMonitoringRuleEvaluationWindow::FIFTEEN_MINUTES,
    keep_alive: DatadogAPIClient::V2::SecurityMonitoringRuleKeepAlive::ONE_HOUR,
    max_signal_duration: DatadogAPIClient::V2::SecurityMonitoringRuleMaxSignalDuration::ONE_DAY,
  }),
  message: "Test rule",
  tags: [],
  is_enabled: true,
})
p api_instance.update_security_monitoring_rule(SECURITY_RULE_ID, body)

Instructions

First install the library and its dependencies and then save the example to example.rb and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" rb "example.rb"
// Update a cloud configuration rule's details returns "OK" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV2::api_security_monitoring::SecurityMonitoringAPI;
use datadog_api_client::datadogV2::model::CloudConfigurationComplianceRuleOptions;
use datadog_api_client::datadogV2::model::CloudConfigurationRegoRule;
use datadog_api_client::datadogV2::model::CloudConfigurationRuleComplianceSignalOptions;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleCase;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleOptions;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleSeverity;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleUpdatePayload;

#[tokio::main]
async fn main() {
    // there is a valid "cloud_configuration_rule" in the system
    let cloud_configuration_rule_id = std::env::var("CLOUD_CONFIGURATION_RULE_ID").unwrap();
    let body =
        SecurityMonitoringRuleUpdatePayload::new()
            .cases(
                vec![
                    SecurityMonitoringRuleCase::new()
                        .notifications(vec![])
                        .status(SecurityMonitoringRuleSeverity::INFO)
                ],
            )
            .compliance_signal_options(
                CloudConfigurationRuleComplianceSignalOptions::new()
                    .user_activation_status(Some(false))
                    .user_group_by_fields(Some(vec![])),
            )
            .is_enabled(false)
            .message("ddd".to_string())
            .name("Example-Security-Monitoring_cloud_updated".to_string())
            .options(
                SecurityMonitoringRuleOptions
                ::new().compliance_rule_options(
                    CloudConfigurationComplianceRuleOptions::new()
                        .rego_rule(
                            CloudConfigurationRegoRule::new(
                                r#"package datadog

import data.datadog.output as dd_output

import future.keywords.contains
import future.keywords.if
import future.keywords.in

milliseconds_in_a_day := ((1000 * 60) * 60) * 24

eval(iam_service_account_key) = "skip" if {
	iam_service_account_key.disabled
} else = "pass" if {
	(iam_service_account_key.resource_seen_at / milliseconds_in_a_day) - (iam_service_account_key.valid_after_time / milliseconds_in_a_day) <= 90
} else = "fail"

# This part remains unchanged for all rules
results contains result if {
	some resource in input.resources[input.main_resource_type]
	result := dd_output.format(resource, eval(resource))
}
"#.to_string(),
                                vec!["gcp_compute_disk".to_string()],
                            ),
                        )
                        .resource_type("gcp_compute_disk".to_string()),
                ),
            )
            .tags(vec![]);
    let configuration = datadog::Configuration::new();
    let api = SecurityMonitoringAPI::with_config(configuration);
    let resp = api
        .update_security_monitoring_rule(cloud_configuration_rule_id.clone(), body)
        .await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}
// Update an existing rule returns "OK" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV2::api_security_monitoring::SecurityMonitoringAPI;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleCase;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleEvaluationWindow;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleKeepAlive;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleMaxSignalDuration;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleOptions;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleQuery;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleQueryAggregation;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleSeverity;
use datadog_api_client::datadogV2::model::SecurityMonitoringRuleUpdatePayload;
use datadog_api_client::datadogV2::model::SecurityMonitoringStandardRuleQuery;

#[tokio::main]
async fn main() {
    // there is a valid "security_rule" in the system
    let security_rule_id = std::env::var("SECURITY_RULE_ID").unwrap();
    let body = SecurityMonitoringRuleUpdatePayload::new()
        .cases(vec![SecurityMonitoringRuleCase::new()
            .condition("a > 0".to_string())
            .name("".to_string())
            .notifications(vec![])
            .status(SecurityMonitoringRuleSeverity::INFO)])
        .filters(vec![])
        .is_enabled(true)
        .message("Test rule".to_string())
        .name("Example-Security-Monitoring-Updated".to_string())
        .options(
            SecurityMonitoringRuleOptions::new()
                .evaluation_window(SecurityMonitoringRuleEvaluationWindow::FIFTEEN_MINUTES)
                .keep_alive(SecurityMonitoringRuleKeepAlive::ONE_HOUR)
                .max_signal_duration(SecurityMonitoringRuleMaxSignalDuration::ONE_DAY),
        )
        .queries(vec![
            SecurityMonitoringRuleQuery::SecurityMonitoringStandardRuleQuery(Box::new(
                SecurityMonitoringStandardRuleQuery::new()
                    .aggregation(SecurityMonitoringRuleQueryAggregation::COUNT)
                    .distinct_fields(vec![])
                    .group_by_fields(vec![])
                    .metrics(vec![])
                    .query("@test:true".to_string()),
            )),
        ])
        .tags(vec![]);
    let configuration = datadog::Configuration::new();
    let api = SecurityMonitoringAPI::with_config(configuration);
    let resp = api
        .update_security_monitoring_rule(security_rule_id.clone(), body)
        .await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}

Instructions

First install the library and its dependencies and then save the example to src/main.rs and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" cargo run
/**
 * Update a cloud configuration rule's details returns "OK" response
 */

import { client, v2 } from "@datadog/datadog-api-client";

const configuration = client.createConfiguration();
const apiInstance = new v2.SecurityMonitoringApi(configuration);

// there is a valid "cloud_configuration_rule" in the system
const CLOUD_CONFIGURATION_RULE_ID = process.env
  .CLOUD_CONFIGURATION_RULE_ID as string;

const params: v2.SecurityMonitoringApiUpdateSecurityMonitoringRuleRequest = {
  body: {
    name: "Example-Security-Monitoring_cloud_updated",
    isEnabled: false,
    cases: [
      {
        status: "info",
        notifications: [],
      },
    ],
    options: {
      complianceRuleOptions: {
        resourceType: "gcp_compute_disk",
        regoRule: {
          policy: `package datadog

import data.datadog.output as dd_output

import future.keywords.contains
import future.keywords.if
import future.keywords.in

milliseconds_in_a_day := ((1000 * 60) * 60) * 24

eval(iam_service_account_key) = "skip" if {
	iam_service_account_key.disabled
} else = "pass" if {
	(iam_service_account_key.resource_seen_at / milliseconds_in_a_day) - (iam_service_account_key.valid_after_time / milliseconds_in_a_day) <= 90
} else = "fail"

# This part remains unchanged for all rules
results contains result if {
	some resource in input.resources[input.main_resource_type]
	result := dd_output.format(resource, eval(resource))
}
`,
          resourceTypes: ["gcp_compute_disk"],
        },
      },
    },
    message: "ddd",
    tags: [],
    complianceSignalOptions: {
      userActivationStatus: false,
      userGroupByFields: [],
    },
  },
  ruleId: CLOUD_CONFIGURATION_RULE_ID,
};

apiInstance
  .updateSecurityMonitoringRule(params)
  .then((data: v2.SecurityMonitoringRuleResponse) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));
/**
 * Update an existing rule returns "OK" response
 */

import { client, v2 } from "@datadog/datadog-api-client";

const configuration = client.createConfiguration();
const apiInstance = new v2.SecurityMonitoringApi(configuration);

// there is a valid "security_rule" in the system
const SECURITY_RULE_ID = process.env.SECURITY_RULE_ID as string;

const params: v2.SecurityMonitoringApiUpdateSecurityMonitoringRuleRequest = {
  body: {
    name: "Example-Security-Monitoring-Updated",
    queries: [
      {
        query: "@test:true",
        aggregation: "count",
        groupByFields: [],
        distinctFields: [],
        metrics: [],
      },
    ],
    filters: [],
    cases: [
      {
        name: "",
        status: "info",
        condition: "a > 0",
        notifications: [],
      },
    ],
    options: {
      evaluationWindow: 900,
      keepAlive: 3600,
      maxSignalDuration: 86400,
    },
    message: "Test rule",
    tags: [],
    isEnabled: true,
  },
  ruleId: SECURITY_RULE_ID,
};

apiInstance
  .updateSecurityMonitoringRule(params)
  .then((data: v2.SecurityMonitoringRuleResponse) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));

Instructions

First install the library and its dependencies and then save the example to example.ts and run following commands:

    
DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" tsc "example.ts"