The core::contains_substring function
The core::contains_substring function searches the given string for the given substring. It returns true if the substring is found, and false otherwise.
Signature
core::contains_substring(str, substr)
Arguments
| Argument | Required | Type | Description |
|---|---|---|---|
str | Yes | String | The string to search within. |
substr | Yes | String | The substring to search for. |
Return value
Returns true if the str argument contains the value of the substr argument, false otherwise.
Examples
The following examples demonstrate the use of substring checking for specific use cases.
Validate strings in configuration
In the following example, the core::contains_substring function checks if a description value contains the specified string.
resource_policy "aws_security_group" "description_requirements" {
enforce {
condition = core::contains_substring(attrs.description, "Managed by Terraform")
error_message = "Security group description must include 'Managed by Terraform'"
}
}
Check resource tags for environment substring
In the following example, the core::contains_substring function validates that resource names include an environment indicator.
resource_policy "aws_instance" "environment_in_name" {
locals {
has_dev = core::contains_substring(attrs.tags.Name, "dev")
has_staging = core::contains_substring(attrs.tags.Name, "staging")
has_prod = core::contains_substring(attrs.tags.Name, "prod")
has_valid_env = local.has_dev || local.has_staging || local.has_prod
}
enforce {
condition = local.has_valid_env
error_message = "Instance name must contain one of: dev, staging, prod"
}
}
Check for prohibited substrings in resource name
In the following example, the core::contains_substring function ensures resource names don't contain prohibited terms.
resource_policy "aws_iam_role" "no_admin_in_name" {
locals {
name_lower = core::lower(attrs.name)
has_admin = core::contains_substring(local.name_lower, "admin")
has_root = core::contains_substring(local.name_lower, "root")
has_superuser = core::contains_substring(local.name_lower, "superuser")
has_prohibited = local.has_admin || local.has_root || local.has_superuser
}
enforce {
condition = !local.has_prohibited
error_message = "IAM role name cannot contain prohibited terms: admin, root, superuser"
}
}
Check for case-insensitive substring
In the following example, the policy performs case-insensitive substring matching by converting the string to search to lowercase before passing it to the core::contains_substring function.
resource_policy "aws_s3_bucket" "case_insensitive_check" {
locals {
bucket_lower = core::lower(attrs.bucket)
contains_backup = core::contains_substring(local.bucket_lower, "backup")
}
enforce {
condition = local.contains_backup
error_message = "Bucket name must contain 'backup' (case-insensitive). Current: ${attrs.bucket}"
}
}