'Parsing terraform plan output to check for module vs resource block usage

I wanted to add a check to an existing terraform build and deployment pipeline to check that the configuration being written by devs is properly formatted and in line with company syntax

Specifically I want to check to make sure they are not using plain resource blocks in thier config as opposed to module blocks

For example I want to I want to make sure they are using

Module “eks_dev_wus2_app_cluster”

And not

Resource “aws_kubernetes_cluster” “eks_dev_wus2_App_cluster”

Current approach

As I understand it I would need to first convert to json to parse through it

terraform show -no-color -json output.tfplan > output.json

Then I should use the jq tool to parse through the output per this article https://linuxconfig.org/how-to-parse-a-json-file-from-linux-command-line-using-jq

A little fuzzy on how I would go about specifically checking the blocks in the terraform config to confirm whether or not they are resource or module.

Can anyone point me in the right direction?

Is there a better way to get output values? Don’t need an entire solution, just looking to clarify some of the fogginess of approaching this problem



Solution 1:[1]

Under the output format, there is a list called resource_changes. Each change has an address field. To meet your requirement, each address should start with module. This makes the developer responsible only for the modules that they are changing with this terraform plan.

Assuming you already have output.json in place, you could do it like this:

LIST=$(cat output.json| jq -r ".resource_changes[].address")

for ADDRESS in $LIST
do
    if [[ $ADDRESS != "module."* ]]; then
        echo "$ADDRESS is outside of a module"
        exit 1
    fi
done

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan Monego