Introduction
This guide provides instructions on how to write HashiCorp Sentinel policies that correctly evaluate Terraform configurations containing aliased providers.
Problem
When a Sentinel policy does not account for aliased providers, it may attempt to access a provider configuration that does not exist. This results in an undefined value, causing the policy check to fail unexpectedly.
Expected Outcome
You will be able to run Sentinel policy checks successfully against Terraform configurations that use aliased providers.
Use Case
This is necessary when your Terraform configuration defines multiple configurations for the same provider using the alias meta-argument, and you need Sentinel policies to inspect resources from all provider instances.
Procedure
To ensure your policy can handle aliased providers, you must iterate over the tfconfig.providers collection, which contains all provider configurations, including aliased ones.
-
Understand the Provider Data Structure.
When provider aliases are used, the
tfconfigimport exposes them in a nested structure. The following example shows a Terraform configuration with twoawsprovider aliases,primaryandreplica.{ "aws": { "alias": { "primary": { "config": { "region": "us-east-1" } }, "replica": { "config": { "region": "us-west-2" } } } } } -
Modify the Sentinel Policy to Iterate Providers.
Update your policy to use the
tfconfig.providerscollection. This allows you to filter for all instances of a specific provider by name, regardless of their aliases.The following example demonstrates how to find all
awsprovider configurations.import "tfconfig/v2" as tfconfig ## Filter for all provider configurations where the name is "aws". aws_providers = filter tfconfig.providers as _, provider { provider.name is "aws" } ## Example: A rule that validates the region for all AWS providers. main = rule { all aws_providers as _, p { p.config.region in ["us-east-1", "us-west-2"] } }
By filtering the tfconfig.providers collection, your policy can dynamically inspect every aliased provider instance, preventing undefined errors and ensuring correct policy evaluation.
Additional Information
- For more details on the data available, refer to the Sentinel
tfconfigImport Documentation.