The core::getdatasource function
The core::getdatasource function returns a data source of the specified type that matches the filter. Terraform policy passes the filtering attributes to the provider, and returns a matching data source from the provider. Since this function returns a single data source, you must use filters if needed to specify a single data source.
Signature
core::getdatasource(data_source_type, filter)
Arguments
| Argument | Required | Type | Description |
|---|---|---|---|
data_source_type | Yes | String | The type of data source to retrieve (For example: "aws_lambda_function", "aws_ami"). |
filter | Yes | Map | A map of attribute names and values to filter the data source. Used to identify a specific data source. |
Return value
Returns a single data source object that matches the specified type and filter. The object contains the data source's attributes as returned by the provider.
Examples
The following examples demonstrate the use of data sources for specific use cases.
Retrieve a Lambda function by name
In the following example, the core::getdatasource function retrieves an AWS Lambda function with the given name.
locals {
function = core::getdatasource("aws_lambda_function", {
function_name = "example-function"
})
}
resource_policy "aws_lambda_permission" "function_exists" {
enforce {
condition = local.function != null
error_message = "Lambda function 'example-function' must exist before creating permissions."
}
}
Retrieve an AMI by filter
In the following example, the core::getdatasource function retrieves an AWS AMI that matches the filter.
locals {
amazon_linux_ami = core::getdatasource("aws_ami", {
most_recent = true
owners = ["amazon"]
filter = {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
})
}
resource_policy "aws_instance" "approved_ami" {
enforce {
condition = attrs.ami == local.amazon_linux_ami.id
error_message = "Instance must use the approved Amazon Linux 2 AMI: ${local.amazon_linux_ami.id}"
}
}
Use with conditional logic
In the following example, the core::getdatasource function retrieves an AWS KMS key that matches the filter, if any.
locals {
# Try to retrieve a KMS key
kms_key = core::try(
core::getdatasource("aws_kms_key", {
key_id = "alias/my-key"
}),
null
)
has_kms_key = local.kms_key != null
}
resource_policy "aws_ebs_volume" "encryption_check" {
enforce {
condition = attrs.encrypted == true
error_message = "EBS volumes must be encrypted."
}
enforce {
condition = !local.has_kms_key || attrs.kms_key_id == local.kms_key.id
error_message = "EBS volumes must use the organization's KMS key when available."
}
}