The core::getdatasource function
The core::getdatasource function returns a data source of the specified type that matches the given configuration. Terraform policy passes the data source configuration to the provider, and returns a matching data source object. Since this function returns a single data source, you must include configuration as needed to specify a single data source. Refer to the provider documentation for the specified data source type to learn more.
Signature
core::getdatasource(data_source_type, config)
Arguments
| Argument | Required | Type | Description |
|---|---|---|---|
data_source_type | Yes | String | The type of data source to retrieve (For example: "aws_lambda_function", "aws_ami"). |
config | Yes | Object | An object representing the data source configuration. Terraform policy validates the object against the data source schema and uses ???? to fetch the data source from the provider. |
Return value
Returns a single data source object that matches the specified type and configuration. The object contains the data source's attributes as returned by the provider, including computed attributes.
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."
}
}