iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💭

Extracting update differences of terraform local modules with terraform-config-inspect

に公開

Reading the code from https://github.com/suzuki-shunsuke/tfactionn, I reimplemented the part that extracts module update diffs (js/src/list-module-callers/index.ts) using a shell script to verify my understanding.
It's essentially reinventing the wheel with no practical use, but it was interesting.
It helped me understand the behavior of https://github.com/torana-us/tfdir, an OSS I contributed to at a previous job.

Why?

Consider a Terraform repository structured like this:

.
|-- environments
|   `--prd
|   |  |--app     # Application settings (EC2, etc.)
|   |  `--network # Network settings (VPC, subnet, etc.)
|   `--stg
|      |--app
|      `--network
`-- modules
    |--app
    |--iam       # IAM used by app
    `--network

We want to run plan/apply for the prd and stg environments at different times.
Also, when updating only the prd environment, we don't want the stg environment's plan/apply to run, and when updating prd/app, we don't want prd/network to run plan/apply.
For changes under the environments directory, we can simply use git diff to target only the updated directories.
However, when changes occur under the modules directory, we want to run plan/apply only for the environments that call the updated module.

hashicorp/terraform-config-inspect

https://github.com/hashicorp/terraform-config-inspect is easy to install using aquaproj/aqua.
Below is a sample aqua.yml.
Since there are no GitHub Releases, specify the commit hash as the version.

---
# yaml-language-server: $schema=https://raw.githubusercontent.com/aquaproj/aqua/main/json-schema/aqua-yaml.json
# aqua - Declarative CLI Version Manager
# https://aquaproj.github.io/
# checksum:
#   enabled: true
#   require_checksum: true
#   supported_envs:
#   - all
registries:
- type: standard
  ref: v4.397.0 # renovate: depName=aquaproj/aqua-registry
  packages:
- name: hashicorp/terraform-config-inspect
  version: "e8a84eebd3e740ab8dc37d5c8f843523e7d49e8d"

Here's the output:

❯ terraform-config-inspect --json environments/prd/network | jq -r '.module_calls'
{
  "network": {
    "name": "network",
    "source": "../../../modules/network",
    "pos": {
      "filename": "environments/prd/network/network.tf",
      "line": 1
    }
  }
}

From the caller's perspective, this tells us where the module's directory is located.
What we actually need is the caller's directory from the module's perspective, so a bit of ingenuity is required.

# 1. Find all Terraform files
❯ find ./environments -type f -name "*.tf" \
    # 2. Get directory list
    | cut -d'/' -f2,3,4 \
    # 3. Remove duplicates
    | sort -u \
    # 4. Run terraform-config-inspect per directory, filter for local modules, and map caller directory to module directory
    | xargs -I{} bash -c "terraform-config-inspect --json {} | jq -r '.module_calls | flatten | .[].source' | sort -u | grep '^../' | sed -e 's;../../../;;' | awk -v dir={} '{print dir, \$1}'"
        jq -r '.module_calls // {} | to_entries[] | .value.source | select(startswith("./") or startswith("../"))' "$temp_output" > module_map 2>/dev/null || true

❯ cat module_map
environments/prd/app modules/app
environments/prd/network modules/network
environments/stg/app modules/app
environments/stg/network modules/network

tfaction also handles cases where modules call other nested modules.

❯ find ./modules -type f -name "*.tf" \
    | cut -d'/' -f2,3 \
    | sort -u \
    | xargs -I{} bash -c "terraform-config-inspect --json {} | jq -r '.module_calls | flatten | .[].source' | sort -u | grep '^../' | sed -e 's;../;modules/;' | awk -v dir={} '{print dir, \$1}'" \
    > module_called_module

❯ cat module_called_module
modules/app modules/iam

❯ while read -r calling called; do
    awk -v calling="$calling" -v called="$called" \
      '$2==calling{print $1, called}' module_map >> nested_module
  done < module_called_module

❯ cat module_map nested_module
environments/prd/app modules/app
environments/prd/network modules/network
environments/stg/app modules/app
environments/stg/network modules/network
environments/prd/app modules/iam
environments/stg/app modules/iam

Combine the above into list-called-module.bash:

#!/usr/bin/env bash
set -euo pipefail
find ./environments -type f -name "*.tf" \
  # 2. Get directory list
  | cut -d'/' -f2,3,4 \
  # 3. Remove duplicates
  | sort -u \
  # 4. Run terraform-config-inspect per directory, filter for local modules, and map caller directory to module directory
  | xargs -I{} bash -c "terraform-config-inspect --json {} | jq -r '.module_calls | flatten | .[].source' | sort -u | grep '^../' | sed -e 's;../../../;;' | awk -v dir={} '{print dir, \$1}'"
      jq -r '.module_calls // {} | to_entries[] | .value.source | select(startswith("./") or startswith("../"))' "$temp_output" > module_map 2>/dev/null || true
find ./modules -type f -name "*.tf" \
  | cut -d'/' -f2,3 \
  | sort -u \
  | xargs -I{} bash -c "terraform-config-inspect --json {} | jq -r '.module_calls | flatten | .[].source' | sort -u | grep '^../' | sed -e 's;../;modules/;' | awk -v dir={} '{print dir, \$1}'" \
  > module_called_module
while read -r calling called; do
  awk -v calling="$calling" -v called="$called" \
    '$2==calling{print $1, called}' module_map >> nested_module
done < module_called_module

Integration into GitHub Actions

Using the module_map and nested_module files, we run plan / apply only when there is an update diff.
Get the Git diff and match it against the module_map / nested_module files to determine which directories to plan.
The following example is for AWS, but the approach is the same for other Cloud Providers.

name: terraform plan stg
on:
  pull_request:
    branches:
      - stg
    paths:
      - '*.tf'
jobs:
  terraform-dir:
    name: Get diff dirs
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
      pull-requests: write
    timeout-minutes: 3
    outputs:
      diff-dirs: ${{ steps.diff-dirs.outputs.diff-dirs }}
    steps:
      - name: Checkout
        uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4
        with:
          fetch-depth: 0
      - uses: aquaproj/aqua-installer@6ce1f8848ec8e61f14d57bd5d7597057a6dd187c # v3.0.1
        with:
          aqua_version: v2.30.0
      - name: Generate module map
        id: module-map
        shell: bash
        run: |
          ./list-called-module.bash
          cat nested_module >> module_map
      - name: Get diff dirs
        id: diff-dirs
        shell: bash
        run:
          if [[ $(git diff \
                    --diff-filter=d \
                    --name-only origin/${{ github.base_ref }} HEAD \
                    -- modules \
                    | wc -l) -ne 0 ]]; then
            # If there is a diff under the modules directory
            touch module_diff

            git diff \
              --diff-filter=d \
              --name-only origin/${{ github.base_ref }} HEAD \
              -- modules \
              | xargs dirname \
              | sort -u \
              | xargs -I{} bash -c \
                "awk -v dir={} '\$2 == dir{print \$1}' <module_map >> module_diff"
            diff_dirs=$(git diff \
                          --diff-filter=d \
                          --name-only origin/${{ github.base_ref }} HEAD \
                          -- environments \
                          | cut -d'/' -f1,2,3 \
                          | cat - module_diff \
                          | sort -u \
                          | xargs \
                          | tr -d '\n' \
                          | jq -csR 'split(" ")')
          else
            # If there is no diff under the modules directory
            diff_dirs=$(git diff \
                          --diff-filter=d \
                          --name-only origin/${{ github.base_ref }} HEAD \
                          -- environments \
                          | cut -d'/' -f1,2,3 \
                          | sort -u \
                          | xargs \
                          | tr -d '\n' \
                          | jq -csR 'split(" ")')
          fi
          echo "diff-dirs=$diff_dirs" >> "$GITHUB_OUTPUT"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
  terraform:
    needs: [terraform-dir]
    name: Terraform plan
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
      pull-requests: write
    environment:
      name: staging
    strategy:
      matrix:
        dir: ${{ fromJson(needs.terraform-dir.outputs.diff-dirs) }}
    steps:
      - name: Checkout
        timeout-minutes: 3
        uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4
        with:
          fetch-depth: 0
      - name: Set up AWS credentials
        timeout-minutes: 3
        uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_KEY }}
          aws-region: ap-northeast-1
      - uses: aquaproj/aqua-installer@6ce1f8848ec8e61f14d57bd5d7597057a6dd187c # v3.0.1
        timeout-minutes: 3
        with:
          aqua_version: v2.30.0
      - name: Terraform plan
        timeout-minutes: 10
        run: |
          tfcmt -var "target:${{ matrix.dir }}/$env" plan -patch -skip-no-changes -- \
            ./run.sh ${{ matrix.dir }} "$env" plan
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          env: ${{ vars.ENV }}

This allows us to plan only the diffs.

Summary

Honestly, just use tfaction. If needed, you can probably use only the diff detection part?
As you can see from reading this, it was quite challenging to do it all with shell scripts + jq.

Discussion