Custom Rego Policies

Custom Rego policies let you write attribute-level checks in Rego, the policy language of Open Policy Agent (OPA). Cloud Exposure runs the policy against every resource of the type you select, and creates a finding for each resource that fails.

Why Write a Policy in Rego

Rego covers four needs that the other custom policy types can't.

Fine-grained control over a resource's own configuration. Templates assemble a policy from predefined parameters, so a condition that needs string matching, CIDR math, date arithmetic, or nested logic has nowhere to go. In Rego you write that condition directly against the resource's JSON, so the policy matches your real rule instead of the closest available approximation.

Adapt a built-in Rego policy to your environment. A built-in policy can't anticipate every architecture, and the findings it raises on a pattern you deliberately chose are noise your team learns to ignore. Import the built-in policy's code, change the threshold or add the exception your environment needs, disable the original, and the noise stops without losing the check.

Reuse your team's existing OPA skills. If your team has standardized on OPA for policy as code, the same language, the same review habits, and the same people apply here. There is no proprietary syntax to learn first.

Policy-as-code control. A Rego policy is code, so you can keep it in your own repository alongside your other OPA policies, review a change there, and bring the reviewed version into Cloud Exposure.

Note: A Rego policy evaluates a single resource type, one resource at a time, using the cloud provider's raw JSON for that resource. It can't reference another resource. For a condition that spans several resources, use an Explorer query instead.

The Rego Editor

The editor has five areas: the policy details on the left (Name, Description, Severity, Remediation, and Status), the Resource Type picker, the code editor and its toolbar, Test Data on the right, and Output below the code.

The toolbar buttons appear as icons above the code. Hover over an icon to see its name.

Icon Name What It Does
Open folder Import Rego from existing policy Lists the built-in and custom Rego policies, with their provider and resource type. Select a policy to preview its code, and then click Select to copy the code into the editor. See Tune a Built-In Policy.
Magic wand Format Reformats the code in standard OPA style.
Function symbol Helper Functions Opens the Helper Functions panel. Helper functions are built-in functions for common checks.
Counterclockwise arrow Reset Replaces the code with the starter template and discards your current code.

The editor checks your code as you type and marks errors in place. To run a test without clicking Run, press Cmd+Enter (Mac) or Ctrl+Enter (Windows).

Create Your First Rego Policy

This walkthrough creates a policy that fails any AWS S3 bucket without versioning enabled.

To create your first Rego policy:

  1. In the Organization dropdown, select the folder or account that the policy applies to. You can't change the scope once you start creating the policy, and the policy applies to that scope and everything below it. The Resource Type list shows only types from this scope, so select a scope that includes AWS accounts.
  2. In the left navigation pane, click Policies > Cloud Policies, and then select the Custom tab.
  3. Click + Create Custom Policy, and then select Rego.
  4. In Resource Type, select S3 Bucket. The editor opens with the starter template, and Test Data loads a sample bucket from your environment.
  5. In Test Data, locate the field to check in the sample bucket's JSON. For versioning, the field is Versioning.VersioningConfiguration.Status.
  6. Replace the starter template with the following policy:

    Copy

    Rego

    package tenable

    import rego.v1

    default result := "pass"

    property_path := ["Versioning", "VersioningConfiguration", "Status"]

    result := "fail" if {
        not input.Versioning.VersioningConfiguration.Status == "Enabled"
    }
  7. In the Output section, click Run. The output shows Pass or Fail for the sample bucket.
  8. To confirm that the policy can fail, change "Status": "Enabled" to "Status": "Suspended" in Test Data, and then click Run again. The output shows Fail and highlights the Status field.
  9. Select Batch, and then click Run to evaluate the policy against up to 1,000 buckets in your scope. Confirm that the results match what you expect.
  10. Enter a meaningful name, such as S3 bucket versioning is not enabled, and an optional description.
  11. Assign the policy a severity, which determines the severity level of any findings triggered by the policy.
  12. (Optional) Enter custom remediation steps to provide clear guidance for security teams.
  13. In the Status section, select Enabled or Disabled. A disabled policy is created but doesn't evaluate resources or create findings until you enable it.
  14. When finished, click Create. The policy's findings appear after the next data sync.

Policy Structure

Every Rego policy needs the two header lines and a result rule. The editor doesn't run or save a policy whose header is missing.

Part Required What It Does
package tenable Yes Must be the first line.
import rego.v1 Yes Must follow the package line. As part of Rego v1, rules use if, and set membership uses in and contains.
result Yes Set it to exactly "pass", "fail", or "skip". Any other value produces an error.
default result := "pass" Recommended Gives a resource a result when no other rule matches. Without it, a resource that matches no rule has no result.
property_path Optional The path to the field that the policy checks, as a list of keys and array indexes. The editor and the finding highlight this field.

Cloud Exposure compiles policies in OPA strict mode, which turns common authoring mistakes into errors rather than letting them through: an unused variable or import, a rule that shadows input or data, or a deprecated built-in function all fail compilation. You can't save or run a policy until it compiles cleanly and every required field is set.

The Starter Template

When you select a resource type, the editor opens with this template. Fill in the fail condition and the property path.

Copy

Rego

# Author a custom policy on a resource's raw JSON. Each matching resource type is evaluated.
# Set 'result' to one of these strings:
# 1. "pass" – Assessment passes; no finding generated.
# 2. "fail" – Assessment fails; a finding is generated.
# 3. "skip" – Resource left unevaluated and excluded.
#
#  Tip: instead of writing everything yourself, hit the button above to pull a
#  ready-made example from the built-in Rego policy library and build from there.

package tenable

import rego.v1

# List each step of the property's path in the JSON as comma-separated entries below,
# e.g. ["properties", "encryption", "encrypted"] for a nested "encrypted" field.
property_path := [""]

default result := "pass"

result := "fail" if {
    # Insert the criteria that cause this policy to fail. The example below produces a failed assessment whenever the value at the property path evaluates to true.
    # object.get(input, property_path, null) == true
}
Note: You can always use the Reset button to go back to the starter template.

Reuse the Property Path in the Condition

To avoid typing the path twice, read the value with object.get and the same property_path. If the path doesn't exist, object.get returns the default you pass instead of stopping the rule.

Copy

Rego

property_path := ["Versioning", "VersioningConfiguration", "Status"]

result := "fail" if {
    object.get(input, property_path, null) != "Enabled"
}

Report Several Failing Fields

When a resource can fail in more than one place, collect each failing field in a set and fail when the set isn't empty. Each entry carries its own property_path, so the policy highlights every failing field.

Copy

Rego

package tenable

import rego.v1

default result := "pass"

result := "fail" if {
    count(failures) > 0
}

# Any subject alternative name that is a wildcard
failures contains {"property_path": ["SubjectAlternativeNameSummaries", i]} if {
    some i, name in input.SubjectAlternativeNameSummaries
    startswith(name, "*.")
}

# The main domain name is a wildcard
failures contains {"property_path": ["DomainName"]} if {
    startswith(input.DomainName, "*.")
}
Note: Comments start with # and are allowed anywhere in the policy.

The Policy Input

input is the resource exactly as the cloud provider's API returns it to Cloud Exposure. Field names and types follow the provider, not the Cloud Exposure resource model.

Casing varies between services of the same provider, so always check the JSON in test data before you write a condition.

Find the Field Names

  • In the editor: select Single in Test Data and open a resource of the selected type. The JSON shown there is the input that your policy receives.
  • In the inventory: open the resource and select the JSON tab.
  • In a built-in policy: click Import Rego from existing policy and open a built-in policy for the same resource type to see which fields it reads.

Rules to Keep in Mind

  • Field names are case-sensitive. input.versioning and input.Versioning are different fields.
  • Check several resources, not one. Optional fields appear only on the resources where they're set. Use Batch to see how the policy handles resources that don't have the field.
  • A missing field doesn't cause an error. A condition that reads a field that doesn't exist doesn't match, so that rule doesn't apply and the resource gets the default result. The exception is not: not input.Logging.Enabled == true is true when the field is missing. To make the outcome clear, read optional fields with object.get and a default value, for example object.get(input, ["Logging", "Enabled"], false), and decide whether a missing field should pass, fail, or skip.
  • Missing is not the same as null. A field can exist with the value null. To check that a path exists, use object.get(input, path, set()) != set(), which returns the empty set only when the path is missing.
  • Values aren't always the type you expect. Some providers return booleans as strings, such as "true", and numbers or timestamps as strings, such as "1799064000.000". Use data.infrastructure.is_true for booleans and to_number for numeric strings. EC2 JSON can also wrap lists in an item key, and return a one-entry list as a single object.
  • Secrets are masked in test data. The editor shows secret values as placeholders and tests against what it shows. In production, the policy sees the real values. To test a condition that depends on a secret, edit the JSON in Test Data.

Common Patterns

Each example is a complete policy that you can paste into the editor and adapt. The field names come from AWS raw JSON, so check them against your own test data first.

A Field Must Have a Specific Value

Write the fail condition with not, so that a resource where the field is missing also fails. A condition such as input.KeyRotationEnabled != true doesn't match when the field is missing, so that resource would pass.

Resource type: AWS KMS Key. Customer-managed keys report KeyRotationEnabled.

Copy

Rego

package tenable

import rego.v1

default result := "pass"

property_path := ["KeyRotationEnabled"]

# Fails when rotation is off or the field is missing
result := "fail" if {
    not data.infrastructure.is_true(input.KeyRotationEnabled)
}

Check Whether a Field Exists

Use object.get(input, path, set()) != set(). Because object.get returns its default when the path is missing, and JSON never contains an empty set, the check is true for every field that exists, including one set to null. Comparing with null instead can't distinguish a missing field from a field set to null.

Resource type: AWS S3 Bucket. The logging configuration is under LoggingStatus. When logging is on, LoggingStatus holds a LoggingEnabled object; when logging is off, LoggingEnabled is missing.

This example skips buckets whose logging configuration couldn't be read, and fails buckets where logging is off.

Copy

Rego

package tenable

import rego.v1

default result := "pass"

property_path := ["LoggingStatus", "LoggingEnabled"]

# True when the path exists, even if its value is null
path_exists(path) if {
    object.get(input, path, set()) != set()
}

# Skip buckets whose logging configuration couldn't be read
result := "skip" if {
    not path_exists(["LoggingStatus"])
} else := "fail" if {
    # Logging is off when LoggingEnabled is missing, null, or empty
    data.infrastructure.is_null_or_empty(object.get(input, property_path, null))
}

Evaluate Only Some Resources

Return "skip" for resources that the policy doesn't apply to, so that they don't count as passed. Chain the rules with else so that skip is evaluated first.

Resource type: AWS KMS Key. Only keys with imported key material, where Origin is EXTERNAL, have a ValidTo field. This example fails those keys when they expire within 90 days.

You can also assign each path to its own variable and combine them in property_path, so that the policy highlights both fields.

Copy

Rego

package tenable

import rego.v1

default result := "pass"

origin_property_path := ["Origin"]

valid_to_property_path := ["ValidTo"]

property_path := [origin_property_path, valid_to_property_path]

result := "fail" if {
    object.get(input, origin_property_path, null) == "EXTERNAL"
    object.get(input, valid_to_property_path, null) != null
    # ValidTo is a string of epoch seconds, for example "1799064000.000", so compare in seconds
    to_number(object.get(input, valid_to_property_path, null)) < time.now_ns() / 1000000000 + data.infrastructure.get_days_ns(90) / 1000000000
}

Any Item in a List Matches

Use some ... in to loop over an array. The rule matches if any item matches.

Resource type: AWS Security Group. EC2 returns camelCase JSON, can wrap lists in an item key, and can return a one-entry list as a single object. The items function handles all of these shapes, and to_number handles ports returned as strings. This example fails a security group that allows SSH from anywhere.

Copy

Rego

package tenable

import rego.v1

default result := "pass"

property_path := ["ipPermissions"]

# EC2 JSON can wrap lists in "item", and a one-entry list can be a single object
as_list(x) := x if {
    is_array(x)
} else := [x] if {
    is_object(x)
} else := []

items(x) := as_list(x.item) if {
    is_object(x)
    object.get(x, "item", null) != null
} else := as_list(x)

# Fails when any inbound rule allows port 22 from anywhere
result := "fail" if {
    some permission in items(object.get(input, "ipPermissions", []))
    to_number(permission.fromPort) <= 22
    to_number(permission.toPort) >= 22
    some ip_range in items(object.get(permission, "ipRanges", []))
    ip_range.cidrIp == "0.0.0.0/0"
}

A rule whose ipProtocol is "-1" allows all ports and has no fromPort, so this policy doesn't catch it. Add a second rule if you need to cover that case.

Every Item in a List Must Match

Use every to require a condition on all items.

Resource type: AWS Image (AMI). EC2 returns the mappings under blockDeviceMapping, possibly wrapped in item, with encryption at ebs.encrypted, often as the string "true". Mappings without ebs, which are instance store, are ignored. Don't use this policy on AWS Instance: an instance's mappings don't include encrypted, which belongs to the attached volume.

Copy

Rego

package tenable

import rego.v1

default result := "pass"

property_path := ["blockDeviceMapping"]

# EC2 JSON can wrap lists in "item", and a one-entry list can be a single object
as_list(x) := x if {
    is_array(x)
} else := [x] if {
    is_object(x)
} else := []

items(x) := as_list(x.item) if {
    is_object(x)
    object.get(x, "item", null) != null
} else := as_list(x)

# EBS mappings only; instance-store mappings have no "ebs"
ebs_mappings := [mapping |
    some mapping in items(object.get(input, "blockDeviceMapping", []))
    object.get(mapping, "ebs", null) != null
]

all_encrypted if {
    every mapping in ebs_mappings {
        data.infrastructure.is_true(object.get(mapping.ebs, "encrypted", false))
    }
}

result := "fail" if {
    not all_encrypted
}

A Required Tag with an Allowed Value

Resource type: AWS Instance. EC2 returns tags under tagSet, possibly wrapped in item, as lowercase key and value pairs. Other AWS services use other shapes: many return Tags with Key and Value, and an S3 bucket's tags are at Tagging.Tagging.TagSet with Key and Value. Check the JSON before you reuse this policy for another type, and replace owner and @acme.com with the tag key and domain that your organization uses.

Two rules can both set "fail", which is not a conflict.

Copy

Rego

package tenable

import rego.v1

default result := "pass"

property_path := ["tagSet"]

# EC2 JSON can wrap lists in "item", and a one-entry list can be a single object
as_list(x) := x if {
    is_array(x)
} else := [x] if {
    is_object(x)
} else := []

items(x) := as_list(x.item) if {
    is_object(x)
    object.get(x, "item", null) != null
} else := as_list(x)

owners := [tag.value |
    some tag in items(object.get(input, "tagSet", []))
    data.infrastructure.equals_ignore_case(tag.key, "owner")
]

# No owner tag
result := "fail" if {
    count(owners) == 0
}

# Owner isn't an @acme.com address
result := "fail" if {
    some owner in owners
    not endswith(lower(owner), "@acme.com")
}

Naming Conventions and String Matching

Use the OPA string functions startswith, endswith, contains, and lower, and regex.match for patterns.

Resource type: AWS S3 Bucket. The bucket name is in Name. This example fails buckets whose name doesn't follow <team>-<env>-<name>, where the environment is dev, stg, or prod. Replace the pattern with your own naming convention.

Copy

Rego

package tenable

import rego.v1

default result := "pass"

property_path := ["Name"]

# A missing name reads as "" and fails the pattern
result := "fail" if {
    not regex.match(`^[a-z0-9]+-(dev|stg|prod)-[a-z0-9-]+$`, object.get(input, "Name", ""))
}

IP Ranges Outside an Allowed List

Use net.cidr_contains for CIDR math.

Resource type: AWS Security Group. This example fails a security group that allows inbound traffic from any range outside your private networks, and uses the same items function as Any Item in a List Matches.

Copy

Rego

package tenable

import rego.v1

default result := "pass"

property_path := ["ipPermissions"]

allowed_ranges := ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]

# EC2 JSON can wrap lists in "item", and a one-entry list can be a single object
as_list(x) := x if {
    is_array(x)
} else := [x] if {
    is_object(x)
} else := []

items(x) := as_list(x.item) if {
    is_object(x)
    object.get(x, "item", null) != null
} else := as_list(x)

in_allowed_range(cidr) if {
    some allowed in allowed_ranges
    net.cidr_contains(allowed, cidr)
}

# Fails when any inbound rule allows a range outside the private networks
result := "fail" if {
    some permission in items(object.get(input, "ipPermissions", []))
    some ip_range in items(object.get(permission, "ipRanges", []))
    not in_allowed_range(ip_range.cidrIp)
}

Dates and Ages

Compare times in nanoseconds. time.now_ns() is the current time, time.parse_rfc3339_ns converts an ISO 8601 timestamp, and data.infrastructure.get_days_ns(n) is n days.

Resource type: AWS IAM User or AWS IAM Role, whose CreateDate is an ISO 8601 timestamp. This example fails users or roles created more than 90 days ago.

Copy

Rego

package tenable

import rego.v1

default result := "pass"

property_path := ["CreateDate"]

result := "fail" if {
    created_ns := time.parse_rfc3339_ns(input.CreateDate)
    time.now_ns() - created_ns > data.infrastructure.get_days_ns(90)
}

For the full list of OPA built-in functions, see the OPA policy reference. Functions that reach outside the policy, such as http.send, aren't available.

Helper Functions

A helper function is a small, pre-built piece of logic that you call from a policy instead of writing it yourself. Checking whether a value is null, empty, or differs from another only by capitalization normally takes several lines of Rego; a helper function wraps that check into a single call.

Important: Always call a helper function with the data.infrastructure. prefix. For example, write data.infrastructure.is_true(input.Enabled), not is_true(input.Enabled). Without the prefix, the policy fails to compile with an undefined function error.

To copy a function with its prefix, click Helper Functions above the Rego editor, and then click Copy next to the function.

Helper Function What It Returns Example
data.infrastructure.equals_ignore_case(value_1, value_2) true when the two values match regardless of capitalization. data.infrastructure.equals_ignore_case(tag.Key, "Owner") matches owner, Owner, and OWNER.
data.infrastructure.get_days_ns(days) The given number of days as nanoseconds. Use it with time.now_ns(). time.now_ns() - created_ns > data.infrastructure.get_days_ns(90) is true when something is older than 90 days.
data.infrastructure.is_false(value) true when the value is false, or the string "false" in any capitalization. data.infrastructure.is_false(input.PublicAccessBlockConfiguration.BlockPublicAcls)
data.infrastructure.is_null_or_empty(value) true when the value is null, "", [], or {}. data.infrastructure.is_null_or_empty(input.tagSet) is true for an instance with no tags.
data.infrastructure.is_true(value) true when the value is true, or the string "true" in any capitalization. data.infrastructure.is_true(mapping.ebs.encrypted) handles both true and "True".

Evaluation Results

Cloud Exposure evaluates the policy against every resource of the selected type in the policy's scope. Each evaluation ends in exactly one state.

State When Effect
Passed result is "pass" No finding.
Failed result is "fail" A finding opens at the policy's severity, or an existing finding stays open.
Skipped result is "skip" The resource falls outside the policy's entry criteria. It counts as not assessed, not as passed, and produces no finding.

Your policy returns pass, fail, or skip.

Use Skip to Scope a Policy

Skip resources that the check doesn't apply to, instead of letting them pass. This matters for compliance: a resource the check doesn't apply to isn't compliant or non-compliant, so it shouldn't count either way. Skipped resources are left out of the policy's evaluated resources, so its results and compliance scores reflect only the resources it actually checks. For example, a policy about imported key material should skip AWS-managed keys; if they passed instead, they would inflate the policy's pass rate.

Avoid Conflicting Results

If one rule sets "skip" and another sets "fail" for the same resource, the evaluation ends in Error. You can avoid this in two ways:

  • Chain the rules with else, as in the examples above. The first matching branch wins.
  • Make the conditions exclusive, for example by adding not skipped to the fail rule.

Two rules that both set "fail" don't conflict.

Test a Policy

Test every policy before you create it. Tests run in the editor only, and don't create findings.

Mode What It Does Use It To
Single Loads one resource's JSON into an editable panel. You can select the resource or edit its JSON. Write the policy, and force a pass or fail by editing values.
Batch Evaluates the policy against the resources of that type in the current scope, up to 1,000. Check how the policy behaves across real resources, including those with missing fields.
Item What It Does
Resource Selects the resource to test in Single mode. Its JSON loads into an editable panel.
Load a random resource Loads a random resource of the selected type.
Reset Discards your edits to the resource JSON and reloads the original.
Scope Narrows a Batch test to a folder or account inside the current scope.
Resource Data Previews the JSON of a resource selected from the Batch list.

To test a policy:

  1. In Test Data, select Single or Batch.
  2. In Single, select a resource from the Resource list. Its JSON appears in the panel. In Batch, optionally narrow the Scope.
  3. In the Output section, click Run. The output groups the resources by Pass, Fail, Skip, and Error.
  4. Select a resource to see its JSON. On a failed resource, the property that failed is highlighted, matching the finding; if that property is missing, its nearest existing parent is highlighted instead. Passing and skipped resources show no highlight. For an error, read the message shown above the JSON and see Troubleshooting.
Note: A Batch run evaluates up to 1,000 resources. When the scope holds more, the output shows Results are limited to 1000 resources. To test a specific set of resources, select a narrower folder or account in Scope. The limit applies to tests only: once created, the policy evaluates every resource in its scope.

Force a Failure

A policy that passes everything may simply never match. To prove that it can fail, edit the JSON in Single so that the resource breaks the rule, and run the test again. For the KMS expiry example, set "Origin": "EXTERNAL" and set "ValidTo" to a date roughly 60 days from today, in epoch seconds. Edits apply to the test only, and don't change the resource.

Testing Tips

  • When the resource type has no resources in your scope, the Resource list is empty. Paste a sample resource JSON payload into the panel instead, and author and test against that. The policy evaluates real resources of that type as soon as they exist.
  • Secret values appear masked in test data. Policies see the real values in production.
  • Run stays disabled until the code compiles and there is a resource or pasted JSON to test on.
  • A test never saves the policy and never creates findings, so you can edit and re-run as often as you like.

Tune a Built-In Policy

When a built-in policy is close to what you need but too noisy or too strict for your environment, copy its logic into a custom policy and change it. This is often faster than writing a policy from scratch.

To tune a built-in policy:

  1. Create a Rego policy, and then click Import Rego from existing policy.
  2. Choose which policies the picker offers:

    • Used on this resource type (default). Only the Rego policies that already evaluate the resource type you selected.
    • All policies. Every Rego policy, whatever its resource type, so that you can start from logic written for a different type and adjust the attributes it references.
  3. Select a policy to preview its code, and then click Select to copy it into the editor. If you haven't selected a resource type yet, the policy's type is selected for you. Only policies written in Rego can be imported; a built-in policy implemented another way becomes available for import only once Tenable migrates it to Rego.
  4. Change the logic. Common changes are a threshold, an exception that skips resources with a specific tag, or an allowed value.
  5. Test the policy with Single and Batch, and then create it.
  6. Disable the original built-in policy, so that the same resources don't produce two findings.

Example. The built-in policy KMS Key is expiring in 30 days or less warns 30 days before imported key material expires, and compares times in seconds using the literal 2592000. If your key rotation process needs 90 days' notice, select AWS KMS Key as the resource type, import the built-in policy, and replace 2592000 with data.infrastructure.get_days_ns(90) / 1000000000. Test it against a sample key, edit the key's JSON in Test Data so that it should fail, run the test again to confirm that it does, and then run it in Batch before you create the policy.

Resource Types and Limits

Which Resource Types You Can Select

The Resource Type list shows only the types that meet both of these conditions:

  • Cloud Exposure stores raw provider JSON for the type. Rego can't evaluate a type without raw JSON.
  • The type belongs to the current scope. In an AWS folder, you see only AWS types. To write a policy for another cloud, change the scope in the Organization dropdown before you open the editor.

Types that span more than one cloud provider aren't supported.

Abstract Resource Types

Some resource types group several kinds of resource. When you select one, the editor shows a notice that the type includes several resource types whose raw JSON schemas may differ, that your code needs to work across all of them, and that resources without raw JSON aren't evaluated.

When you write a policy for an abstract type:

  • Check the JSON of each kind that the policy should cover, using Single test data.
  • Read fields with object.get and a default, so that the policy doesn't stop on a kind that lacks the field.
  • Skip the kinds that the policy doesn't apply to.
  • Test with Batch across all the kinds.

Limits

Limit Value
Policy size 64 KB
Resource types per evaluation One. A policy can't read, look up, or reference another resource. Use an Explorer query for conditions across resources.
Paths Relative paths aren't allowed.
Data A policy can read input and the data.infrastructure helper functions only. Other data, such as data.internal, isn't available.
External calls Built-in functions are limited to an allowlist. Everything outside it is denied, including http.send and opa.runtime, so a policy has no network, file, or process access.
Persistence A policy is a pure evaluation. It can't write or store anything, and debug output such as print and trace is disabled.

Troubleshooting

The editor validates the policy before it runs or saves it, and can show the following messages.

Message Cause Fix
Rego policy must start with 'package tenable' followed by 'import rego.v1' The header is missing, misspelled, or not at the top. Make package tenable the first line and import rego.v1 the next.
Rego policy contains syntax or compilation errors A syntax error, or a call to a function that doesn't exist. Calling a helper function without its prefix causes this. Check the highlighted line. When the message continues <name> is a helper function. Call it as data.infrastructure.<name>(...), add the prefix. Also check that rules use if.
The 'result' rule in rego policy must return fail, pass, or skip result was set to another value, such as "failed", true, or a number. Set result to exactly "pass", "fail", or "skip", in lowercase and in quotes.
Rego policy evaluation failed The policy compiled but failed while evaluating a resource, for example because two rules set result to different values. Chain the rules with else, or make their conditions exclusive. See Avoid Conflicting Results.
Accessing internal data is not allowed The policy text contains data.internal anywhere, including in a comment. Remove every mention of data.internal, comments included.
Relative paths are not allowed in rego policies The policy references a path relative to the current package instead of an absolute one. Write the full path, for example data.infrastructure.is_true rather than a relative reference.
Rego policy must not exceed 64 KB The policy is too long. Remove unused rules and comments, or split the policy into several policies.
Rego policy validation timed out The policy took too long to validate. Simplify it, for example by reducing deeply nested loops.
Test data must be valid JSON The JSON edited in Single test data is malformed. Fix the JSON, or reselect the resource to reload it.
Unknown resource type The resource type is no longer available. Select another resource type.
This resource type spans multiple providers and is not supported The type covers more than one cloud. Select a provider-specific type.
Compilation check failed The editor couldn't complete its check, for example because of a temporary service error. Edit the policy or wait a moment so that the check runs again. If it keeps happening, contact support.
Evaluation failed The test run couldn't complete. Click Run again. If it keeps happening, contact support.

The Policy Passes Every Resource

The fail condition probably never matches. Common causes:

  • A field name with the wrong case, or a path that doesn't exist on these resources. Compare it with the JSON in Single.
  • A comparison of a string with a boolean or a number, such as input.Enabled == true when the value is "true". Use data.infrastructure.is_true.
  • != on a field that is missing. Use not ... == instead.

To check, edit the test JSON so that the resource should fail, and run the test again.

The Policy Fails Every Resource

Check for a fail rule with no conditions, or a negation on a path that never exists. Run the test in Batch and open a few failed resources to compare their JSON.

Manage a Rego Policy

Once created, a Rego-based policy behaves like any other custom policy. Its findings follow the same format, dashboards, reports, automation, ticketing, exclusions, and compliance frameworks, and it uses the same role-based access controls. See Cloud Findings for more information.

  • Find the policy. On the Custom tab, the Type column shows whether a policy is a Query, Template, or Rego policy, and the Scope column shows the folder or account it was created on. You can filter the list by provider, scope, type, and status.
  • See the full result breakdown. The Custom tab shows Scanned Resources and Failed Resources by default. Use the column picker to add Ignored Resources for the complete per-policy picture.
  • Verify the policy is enabled. The Status column carries Enabled and Disabled.
  • View the code. Open the policy from the Custom tab. Its profile shows the Rego code.
  • Edit. Findings update at the next scan. The resource type is fixed once the policy is saved.
  • Enable or disable. You can enable or disable a policy only in the folder or account where you created it; child folders and accounts inherit its status. Disabling a policy closes its open findings.
  • Delete. Deleting a policy removes it from all accounts in its scope, deletes its findings rather than resolving them, and removes the policy from the compliance frameworks, exclusions, and reports that reference it. The deletion is recorded in the audit log and can't be undone.
  • Exclude resources. You can exclude resources from a Rego policy the same way as from any other policy.

Rego FAQ

Q: Can a Rego policy check a relationship between resources, such as an instance and its IAM role?

A: No. A Rego policy sees only one resource's raw JSON. For conditions across resources, such as effective permissions or access to sensitive data, use an Explorer query.

Q: Why doesn't my resource type appear in the list?

A: Either Cloud Exposure doesn't store raw JSON for that type, or the type belongs to a different cloud than the current scope. Change the scope in the Organization dropdown and open the editor again.

Q: Can I change the scope while I'm creating a policy?

A: No. Select the scope before you click + Create Custom Policy.

Q: Can I reuse Rego policies that I already have, for example from OPA Gatekeeper or Conftest?

A: Yes, with changes. Use package tenable and import rego.v1, read the resource from input in the cloud provider's raw JSON format, and set result instead of writing deny or violation rules.

Q: Can I see which resources passed?

A: In the editor, yes: a Batch test lists passed, failed, and skipped resources, for up to 1,000 resources. Once the policy is created, findings show only the resources that failed.

Q: Can I use Rego policies for infrastructure as code scans?

A: No. Custom Rego policies evaluate deployed cloud resources. See IaC Policies for code scans.

Q: Can I manage Rego policies with the API or Terraform?

A: Not at this time. Create and edit them in the Console.

Q: Do Rego findings count in compliance frameworks and reports?

A: Yes. The findings of a Rego policy work like those of any other custom policy. See Compliance.

Q: Where can I learn Rego?

A: See the OPA documentation and the Rego Playground. Remember to add package tenable and import rego.v1 when you bring a policy back.