Enforcing Required Tags on Terraform Resources with Spacelift
Enforcing Required Tags on Terraform Resources for Consistent Infrastructure Management
Table of contents
No headings in the article.
Spacelift is a powerful platform that helps manage infrastructure as code (IaC) deployments. As part of its policy enforcement capabilities, Spacelift allows you to define custom plan policies to ensure compliance and consistency across your infrastructure. In this blog post, we will explore how to enforce required tags on Terraform resources using a plan policy in Spacelift.
Policy Overview:
The goal of our plan policy is to ensure that specific tags are present on all Terraform resources in our deployments. To achieve this, we will define a set of required tags and use a deny rule to detect resources that do not have all the required tags. Let's take a closer look at the policy code:
package spacelift
required_tags := {"Name"}
deny["Required Name tag missing"] {
resource := input.terraform.resource_changes[_]
tags := resource.change.after.tags_all
count(tags) > 0
missing_tags := {tag | required_tags[tag]; not tags[tag]}
count(missing_tags) > 0
}
sample = true
Explanation:
We define a set called
required_tags
which contains the tags that must be present on the resources. In our example, we have "Name", "env", and "owner" as required tags.The deny rule is triggered when a resource does not have all the required tags. It generates an error message indicating the resource address and the missing tags.
Inside the deny rule, we extract the resource being evaluated using the
resource
variable.We retrieve the tags of the resource after the change using the
tags
variable.We added the condition
count(tags) > 0
before evaluating the missing tags. This condition ensures that themissing_tags
set is only computed if there are tags present in thetags
set.The
missing_tags
set comprehension filters the required tags and selects only those that are missing from the resource tags.Finally, we check if the count of
missing_tags
is greater than 0, indicating that the resource is missing at least one required tag.
In conclusion, the provided plan policy in Spacelift enables you to enforce required tags on Terraform resources. This enhances consistency, improves resource management, and simplifies governance in your infrastructure deployments. Utilizing Spacelift and the Rego language empowers you to easily enforce a range of policies tailored to your specific needs.
Reference :
https://www.openpolicyagent.org/docs/latest/
https://github.com/spacelift-io/spacelift-policies-example-library/