diff --git a/.github/actions/terraform-action/README.md b/.github/actions/terraform-action/README.md index 4ac9ec9..c4815e4 100644 --- a/.github/actions/terraform-action/README.md +++ b/.github/actions/terraform-action/README.md @@ -2,7 +2,7 @@ Action to run TF Scaffold Terraform Action #### Prerequisites -Authenticated with AWS Account +Authenticated with AWS Account. The Terraform directory must contain an executable `./bin/terraform.sh`. Python 3 is required to parse non-empty `terraform_args`. #### Context This action allows the workflow to run terraform commands via TF Scaffold @@ -15,9 +15,11 @@ This action allows the workflow to run terraform commands via TF Scaffold - group (required): Terraform group to reference e.g dev. - bucket-prefix (required): AWS Terraform bucket used for TF state. - region (required): AWS region used e.g eu-west-1. -- terraform_version (optional): Terraform Version to install on runner. -- terraform_args (optional): Additional Terraform arguments. -- terraform_directory (optional): Directory location of Terraform +- terraform_version (optional): Terraform version to install (default `1.9.8`). +- terraform_args (optional): Additional Terraform arguments, parsed with shell-style quoting. +- terraform_directory (optional): Directory containing `bin/terraform.sh` (default `.`). +- artifact_name (optional): Extra artifact name suffix (default empty). +- upload_artifact (optional): Upload the output artifact (`'true'` by default; set to `'false'` to disable). #### Outputs N/A @@ -26,7 +28,6 @@ N/A ```yaml - name: Terraform - db uses: dvsa/.github/.github/actions/terraform-action@v7 - working-directory: . with: action: plan environment: dev @@ -38,7 +39,6 @@ N/A - name: Terraform - app uses: dvsa/.github/.github/actions/terraform-action@v7 - working-directory: ./infrastructure with: action: plan environment: dev @@ -47,5 +47,6 @@ N/A bucket-prefix: mot-recalls-tfscaffold region: eu-west-1 project: mot-project + terraform_directory: ./infrastructure terraform_args: "-var lambda_version=1.x.x" ``` diff --git a/.github/actions/terraform-action/action.yml b/.github/actions/terraform-action/action.yml index e053d47..fcc7a55 100644 --- a/.github/actions/terraform-action/action.yml +++ b/.github/actions/terraform-action/action.yml @@ -4,50 +4,38 @@ inputs: action: description: 'Terraform action to run e.g plan' required: true - type: string project: description: 'Terraform project' required: true - type: string environment: description: 'Terraform environment' required: true - type: string component: description: 'Terraform component' required: true - type: string group: description: 'Terraform group' required: true - type: string bucket-prefix: description: 'AWS Terraform bucket used for TF state' required: true - type: string region: description: 'AWS region' required: true - type: string terraform_version: - type: number - default: '1.3.7' + default: '1.9.8' description: Terraform Version to install on runner terraform_args: - type: string default: '' description: Additional Terraform arguments terraform_directory: - type: string default: '.' description: Directory location of Terraform artifact_name: - type: string default: '' description: 'Name of the artifact to upload (defaults to environment-component if empty)' upload_artifact: - type: boolean - default: true + default: 'true' description: 'Whether to upload the artifact or not' runs: @@ -61,18 +49,48 @@ runs: - name: Terraform init and plan id: plan working-directory: ${{ inputs.terraform_directory }} + env: + INPUT_ACTION: ${{ inputs.action }} + INPUT_PROJECT: ${{ inputs.project }} + INPUT_ENVIRONMENT: ${{ inputs.environment }} + INPUT_COMPONENT: ${{ inputs.component }} + INPUT_GROUP: ${{ inputs.group }} + INPUT_BUCKET_PREFIX: ${{ inputs.bucket-prefix }} + INPUT_REGION: ${{ inputs.region }} + INPUT_TERRAFORM_ARGS: ${{ inputs.terraform_args }} run: | - mkdir -p plans/${{ inputs.environment }} - ./bin/terraform.sh --action ${{ inputs.action }} --project ${{ inputs.project }} --environment ${{ inputs.environment }} --component ${{ inputs.component }} --group ${{ inputs.group }} --bucket-prefix ${{ inputs.bucket-prefix }} --region ${{ inputs.region }} --compact-warnings --no-color -- ${{ inputs.terraform_args }} | tee plans/${{ inputs.environment }}/${{ inputs.component }}-plan.txt + set -o pipefail + if [[ ! -x ./bin/terraform.sh || ! -f ./bin/terraform.sh ]]; then + echo "::error::./bin/terraform.sh is missing or not executable in the Terraform directory." + exit 1 + fi + args=() + if [[ -n "$INPUT_TERRAFORM_ARGS" ]]; then + parsed_args=$(python3 -c 'import json, os, shlex; print(json.dumps(shlex.split(os.environ["INPUT_TERRAFORM_ARGS"])))') + while IFS= read -r -d '' arg; do + args+=("$arg") + done < <(python3 -c 'import json, sys; [sys.stdout.buffer.write(arg.encode() + b"\0") for arg in json.loads(sys.argv[1])]' "$parsed_args") + fi + mkdir -p "plans/$INPUT_ENVIRONMENT" + ./bin/terraform.sh \ + --action "$INPUT_ACTION" \ + --project "$INPUT_PROJECT" \ + --environment "$INPUT_ENVIRONMENT" \ + --component "$INPUT_COMPONENT" \ + --group "$INPUT_GROUP" \ + --bucket-prefix "$INPUT_BUCKET_PREFIX" \ + --region "$INPUT_REGION" \ + --compact-warnings --no-color -- "${args[@]}" \ + | tee "plans/$INPUT_ENVIRONMENT/$INPUT_COMPONENT-plan.txt" shell: bash - name: Get current date id: date - run: echo "date=$(date +'%Y-%m-%d-%H-%M-%S')" >> $GITHUB_OUTPUT + run: echo "date=$(date +'%Y-%m-%d-%H-%M-%S')" >> "$GITHUB_OUTPUT" shell: bash - name: Save Artifact - if: ${{ inputs.upload_artifact }} + if: ${{ inputs.upload_artifact == 'true' }} uses: actions/upload-artifact@v7 with: name: "${{ inputs.artifact_name != '' && format('{0}-{1}-{2}-{3}', inputs.environment, inputs.component, inputs.artifact_name, steps.date.outputs.date) || format('{0}-{1}-{2}', inputs.environment, inputs.component, steps.date.outputs.date) }}" diff --git a/.github/actions/terraform-fmt/README.md b/.github/actions/terraform-fmt/README.md index e312a53..bdc1550 100644 --- a/.github/actions/terraform-fmt/README.md +++ b/.github/actions/terraform-fmt/README.md @@ -8,7 +8,10 @@ N/A The terraform fmt command is used to rewrite Terraform configuration files to a canonical format and style. This command applies a subset of the Terraform language style conventions, along with other minor adjustments for readability. #### Inputs -N/A +- `terraform_version` (optional): Terraform version to install (default `1.9.8`). +- `check` (optional): Report formatting errors without changing files (`'true'` by default). +- `recursive` (optional): Check subdirectories (`'true'` by default). +- `path` (optional): File or directory to format (default current directory). #### Outputs N/A diff --git a/.github/actions/terraform-fmt/action.yml b/.github/actions/terraform-fmt/action.yml index f5c1f9f..691e749 100644 --- a/.github/actions/terraform-fmt/action.yml +++ b/.github/actions/terraform-fmt/action.yml @@ -2,20 +2,18 @@ name: Terraform Format inputs: terraform_version: - type: number - default: '1.3.7' + default: '1.9.8' + description: Terraform version to install check: required: false - type: boolean - default: true + default: 'true' description: Flag whether to only report errors without making changes recursive: required: false - default: true + default: 'true' description: Flag to trigger recursive checks into subfolders of project path path: required: false - type: string description: Target directory in which to run fmt command runs: @@ -24,13 +22,22 @@ runs: - uses: hashicorp/setup-terraform@v3 with: terraform_version: ${{ inputs.terraform_version }} - - run: | - if ${{ inputs.CHECK }} == true; then - echo "CHECK='-check'" >> $GITHUB_ENV - fi - if ${{ inputs.RECURSIVE }} == true; then - echo "RECURSIVE='-recursive'" >> $GITHUB_ENV - fi - shell: bash - - run: terraform fmt ${{ env.CHECK }} ${{ env.RECURSIVE }} ${{ inputs.path }} + terraform_wrapper: false + - name: Format Terraform + env: + INPUT_CHECK: ${{ inputs.check }} + INPUT_RECURSIVE: ${{ inputs.recursive }} + INPUT_PATH: ${{ inputs.path }} + run: | + args=() + if [[ "$INPUT_CHECK" == 'true' ]]; then + args+=(-check) + fi + if [[ "$INPUT_RECURSIVE" == 'true' ]]; then + args+=(-recursive) + fi + if [[ -n "$INPUT_PATH" ]]; then + args+=("$INPUT_PATH") + fi + terraform fmt "${args[@]}" shell: bash diff --git a/.github/actions/terraform-workspace/README.md b/.github/actions/terraform-workspace/README.md index 7feb896..2c3deb8 100644 --- a/.github/actions/terraform-workspace/README.md +++ b/.github/actions/terraform-workspace/README.md @@ -2,7 +2,8 @@ Action to create Terraform Namespace #### Prerequisites -N/A +The Terraform configuration must already be initialized and its backend accessible. +The checkout step preserves untracked files, including `.terraform`, from earlier steps. #### Context Creates TF workspace with either github actor name or if provided a unique name e.g uat1 @@ -12,11 +13,12 @@ Each Terraform configuration has an associated backend that defines how Terrafor The persistent data stored in the backend belongs to a workspace. The backend initially has only one workspace containing one Terraform state associated with that configuration. Some backends support multiple named workspaces, allowing multiple states to be associated with a single configuration. The configuration still has only one backend, but you can deploy multiple distinct instances of that configuration without configuring a new backend or changing authentication credentials. #### Inputs -- terraform_version (optional): Terraform Version to install on runner. -- terraform_workspace_name (optional): Name for Terraform Workspace e.g dev01 or uat01. +- terraform_version (optional): Terraform version to install (default `1.9.8`). +- terraform_workspace_name (optional): Workspace name, defaulting to the GitHub actor when empty. +- terraform_directory (optional): Directory containing the initialized configuration (default `.`). #### Outputs -N/A +The selected workspace name is exported as `WORKSPACE` for subsequent steps. #### Usage ```yaml @@ -24,7 +26,7 @@ N/A uses: dvsa/.github/.github/actions/terraform-workspace@v7 with: terraform_workspace_name: ${{ inputs.terraform_workspace_name }} - terraform_version: 1.3.7 + terraform_version: '1.9.8' - name: TF workspace uses: dvsa/.github/.github/actions/terraform-workspace@v7 diff --git a/.github/actions/terraform-workspace/action.yml b/.github/actions/terraform-workspace/action.yml index fc1595a..12c1c4b 100644 --- a/.github/actions/terraform-workspace/action.yml +++ b/.github/actions/terraform-workspace/action.yml @@ -2,31 +2,31 @@ name: Terraform Workspace inputs: terraform_version: - type: number - default: '1.3.7' - description: Terraform Version to install on runner + default: '1.9.8' + description: Terraform version to install on runner terraform_workspace_name: - type: string - description: Name for Teraform Workspace e.g dev01 or uat01 + description: Name for Terraform workspace, e.g. dev01 or uat01 + terraform_directory: + default: '.' + description: Directory containing the initialized Terraform configuration runs: using: 'composite' steps: - - uses: actions/checkout@v7 - - uses: hashicorp/setup-terraform@v3 - with: - terraform_version: ${{ inputs.terraform_version }} - - - name: Create Terraform Workspace Default - if: ${{ inputs.terraform_workspace_name == null }} - run: | - terraform workspace select "${{ github.actor }}" || terraform workspace new "${{ github.actor }}" - echo "WORKSPACE=${{ github.actor }}" >> $GITHUB_ENV - shell: bash - - - name: Create Terraform Workspace - if: ${{ inputs.terraform_workspace_name != null }} - run: | - terraform workspace select "${{ inputs.terraform_workspace_name }}" || terraform workspace new "${{ inputs.terraform_workspace_name }}" - echo "WORKSPACE=${{ inputs.terraform_workspace_name }}" >> $GITHUB_ENV - shell: bash + - uses: actions/checkout@v7 + with: + clean: false + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: ${{ inputs.terraform_version }} + terraform_wrapper: false + - name: Select or create Terraform workspace + working-directory: ${{ inputs.terraform_directory }} + env: + INPUT_WORKSPACE: ${{ inputs.terraform_workspace_name }} + ACTOR: ${{ github.actor }} + run: | + workspace="${INPUT_WORKSPACE:-$ACTOR}" + terraform workspace select "$workspace" || terraform workspace new "$workspace" + echo "WORKSPACE=$workspace" >> "$GITHUB_ENV" + shell: bash diff --git a/.github/workflows/terraform-static-full.yaml b/.github/workflows/terraform-static-full.yaml index e1b5155..1e52024 100644 --- a/.github/workflows/terraform-static-full.yaml +++ b/.github/workflows/terraform-static-full.yaml @@ -2,52 +2,123 @@ name: terraform-static-full on: workflow_call: - + inputs: + terraform_version: + description: Terraform version to install + type: string + default: latest + tflint_version: + description: TFLint version to install + type: string + default: latest + run_validate: + description: Validate all Terraform directories + type: boolean + default: false workflow_dispatch: + inputs: + terraform_version: + description: Terraform version to install + type: string + default: latest + tflint_version: + description: TFLint version to install + type: string + default: latest + run_validate: + description: Validate all Terraform directories + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: terraform-static-full-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true jobs: terraform-checkov: name: Checkov Scan - permissions: - contents: read - actions: read runs-on: ubuntu-latest + timeout-minutes: 30 steps: - uses: actions/checkout@v7 - name: Checkov Scan uses: bridgecrewio/checkov-action@v12 with: output_format: cli - quiet: true # display only failed checks - download_external_modules: true # downloads and checks external modules + quiet: true + download_external_modules: true terraform-fmt: name: Format Terraform runs-on: ubuntu-latest - defaults: - run: - working-directory: ./ + timeout-minutes: 15 steps: - uses: actions/checkout@v7 - name: Run tf format - - run: terraform fmt -check -no-color -recursive - - run: | - echo "### Failing files:" >> $GITHUB_STEP_SUMMARY - terraform fmt -check -no-color -recursive | tee -a $GITHUB_STEP_SUMMARY + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: ${{ inputs.terraform_version }} + terraform_wrapper: false + - name: Check formatting + run: | + set -o pipefail + echo "### Failing files:" >> "$GITHUB_STEP_SUMMARY" + terraform fmt -check -diff -no-color -recursive | tee -a "$GITHUB_STEP_SUMMARY" terraform-lint: name: Lint Terraform runs-on: ubuntu-latest - defaults: - run: - working-directory: ./ + timeout-minutes: 20 + env: + GITHUB_TOKEN: ${{ github.token }} steps: - uses: actions/checkout@v7 - uses: actions/cache@v6 name: Cache plugin dir with: path: ~/.tflint.d/plugins - key: tflint-${{ hashFiles('.tflint.hcl') }} + key: tflint-${{ runner.os }}-${{ hashFiles('.tflint.hcl') }} - uses: terraform-linters/setup-tflint@v6 - - run: tflint --init --recursive --config=$(realpath .tflint.hcl) - - run: tflint --recursive --config=$(realpath .tflint.hcl) + with: + tflint_version: ${{ inputs.tflint_version }} + - name: Select TFLint configuration + run: | + if [[ -f .tflint.hcl ]]; then + config="$GITHUB_WORKSPACE/.tflint.hcl" + else + config="$RUNNER_TEMP/tflint-fallback.hcl" + printf 'plugin "terraform" {\n enabled = true\n preset = "recommended"\n}\n' > "$config" + fi + echo "TFLINT_CONFIG=$config" >> "$GITHUB_ENV" + - run: tflint --init --recursive --config="$TFLINT_CONFIG" + - run: tflint --recursive --config="$TFLINT_CONFIG" + + terraform-validate: + name: Validate Terraform + if: ${{ inputs.run_validate }} + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: ${{ inputs.terraform_version }} + terraform_wrapper: false + - name: Validate Terraform directories + run: | + status=0 + declare -A seen=() + while IFS= read -r -d '' file; do + dir="${file%/*}" + if [[ -n "${seen[$dir]:-}" ]]; then + continue + fi + seen["$dir"]=1 + echo "Validating $dir" + if ! (cd "$dir" && terraform init -backend=false -input=false && terraform validate); then + status=1 + fi + done < <(find . -type d -name .terraform -prune -o -type f -name '*.tf' -print0) + exit "$status" diff --git a/.github/workflows/terraform-static.yaml b/.github/workflows/terraform-static.yaml index 3b05f50..a25ac18 100644 --- a/.github/workflows/terraform-static.yaml +++ b/.github/workflows/terraform-static.yaml @@ -2,89 +2,192 @@ name: terraform-static on: workflow_call: + inputs: + terraform_version: + description: Terraform version to install + type: string + default: latest + tflint_version: + description: TFLint version to install + type: string + default: latest + run_validate: + description: Validate affected Terraform directories + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: terraform-static-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true jobs: terraform-checkov: name: Checkov Scan - permissions: - contents: read - actions: read runs-on: ubuntu-latest + timeout-minutes: 30 steps: - uses: actions/checkout@v7 - name: Checkov Scan uses: bridgecrewio/checkov-action@v12 with: output_format: cli - quiet: true # display only failed checks - download_external_modules: true # downloads and checks external modules + quiet: true + download_external_modules: true check-changed-files: - runs-on: ubuntu-latest name: Checking Modified Files + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + tf_files: ${{ steps.select.outputs.tf_files }} + tf_dirs: ${{ steps.select.outputs.tf_dirs }} steps: - uses: actions/checkout@v7 - - name: Get changed files + - name: Get changed Terraform files id: changed-files uses: tj-actions/changed-files@v47 - - name: List all changed files - id: list-changed-files + with: + files: '**/*.tf' + json: true + escape_json: false + safe_output: false + - name: Select existing files and affected directories + id: select env: - ALL_CHANGED_FILES: ${{ steps.changed-files.outputs.all_changed_files }} - # Loop though files, get terraform files and reformat for tflint + CHANGED_FILES: ${{ steps.changed-files.outputs.all_modified_files }} run: | - echo "### Modified files:" >> $GITHUB_STEP_SUMMARY - export tf_files="" - export tf_files_filtered="" - for file in ${ALL_CHANGED_FILES}; do - echo "$file" >> $GITHUB_STEP_SUMMARY - if echo "$file" | grep -q ".*\.tf$" ; then - tf_files+="${file} " - tf_files_filtered+="--filter=${file} " - fi - done - echo "tf_files=$tf_files" >> $GITHUB_OUTPUT - echo "tf_files_filtered=$tf_files_filtered" >> $GITHUB_OUTPUT + python3 <<'PY' + import json + import os - - outputs: - tf_files: ${{ steps.list-changed-files.outputs.tf_files }} - tf_files_filtered: ${{ steps.list-changed-files.outputs.tf_files_filtered }} + changed = json.loads(os.environ["CHANGED_FILES"]) + files = [path for path in changed if os.path.isfile(path)] + dirs = sorted({ + os.path.dirname(path) or "." + for path in changed + if os.path.isdir(os.path.dirname(path) or ".") + and any(name.endswith(".tf") and os.path.isfile(os.path.join(os.path.dirname(path) or ".", name)) + for name in os.listdir(os.path.dirname(path) or ".")) + }) + with open(os.environ["GITHUB_OUTPUT"], "a") as output: + print(f"tf_files={json.dumps(files)}", file=output) + print(f"tf_dirs={json.dumps(dirs)}", file=output) + PY terraform-fmt: name: Format Terraform - if: ${{ needs.check-changed-files.outputs.tf_files != '' }} - needs: - - check-changed-files + if: ${{ needs.check-changed-files.outputs.tf_files != '[]' }} + needs: check-changed-files runs-on: ubuntu-latest - defaults: - run: - working-directory: ./ + timeout-minutes: 15 steps: - uses: actions/checkout@v7 - - run: terraform fmt -check -no-color -recursive ${{ needs.check-changed-files.outputs.tf_files }} - - if: failure() - name: Output to summary - run: | - echo "### Failing files:" >> $GITHUB_STEP_SUMMARY - terraform fmt -check -no-color -recursive ${{ needs.check-changed-files.outputs.tf_files }} | tee -a $GITHUB_STEP_SUMMARY + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: ${{ inputs.terraform_version }} + terraform_wrapper: false + - name: Check formatting + env: + TF_FILES: ${{ needs.check-changed-files.outputs.tf_files }} + run: | + status=0 + while IFS= read -r -d '' file; do + if ! terraform fmt -check -diff -no-color "./$file"; then + if (( status == 0 )); then + echo "### Failing files:" >> "$GITHUB_STEP_SUMMARY" + fi + printf '%s\n' "- \`$file\`" >> "$GITHUB_STEP_SUMMARY" + status=1 + fi + done < <(jq -j '.[] | ., "\u0000"' <<< "$TF_FILES") + exit "$status" terraform-lint: name: Lint Terraform - if: ${{ needs.check-changed-files.outputs.tf_files_filtered != '' }} - needs: - - check-changed-files + if: ${{ needs.check-changed-files.outputs.tf_files != '[]' }} + needs: check-changed-files runs-on: ubuntu-latest - defaults: - run: - working-directory: ./ + timeout-minutes: 20 + env: + GITHUB_TOKEN: ${{ github.token }} steps: - uses: actions/checkout@v7 - uses: actions/cache@v6 name: Cache plugin dir with: path: ~/.tflint.d/plugins - key: tflint-${{ hashFiles('.tflint.hcl') }} + key: tflint-${{ runner.os }}-${{ hashFiles('.tflint.hcl') }} - uses: terraform-linters/setup-tflint@v6 - - run: tflint --init --recursive --config=$(realpath .tflint.hcl) - - run: tflint --recursive --config=$(realpath .tflint.hcl) ${{ needs.check-changed-files.outputs.tf_files_filtered }} + with: + tflint_version: ${{ inputs.tflint_version }} + - name: Select TFLint configuration + run: | + if [[ -f .tflint.hcl ]]; then + config="$GITHUB_WORKSPACE/.tflint.hcl" + else + config="$RUNNER_TEMP/tflint-fallback.hcl" + printf 'plugin "terraform" {\n enabled = true\n preset = "recommended"\n}\n' > "$config" + fi + echo "TFLINT_CONFIG=$config" >> "$GITHUB_ENV" + - run: tflint --init --recursive --config="$TFLINT_CONFIG" + - name: Lint changed Terraform files + env: + TF_FILES: ${{ needs.check-changed-files.outputs.tf_files }} + run: | + # Recursive TFLint resolves --filter relative to each scanned directory. + status=0 + tflint --recursive --format=json --config="$TFLINT_CONFIG" > "$RUNNER_TEMP/tflint-results.json" || status=$? + if (( status != 0 && status != 2 )); then + cat "$RUNNER_TEMP/tflint-results.json" + exit "$status" + fi + TFLINT_STATUS="$status" python3 <<'PY' + import json + import os + import sys + + files = {os.path.normpath(path) for path in json.loads(os.environ["TF_FILES"])} + dirs = {os.path.dirname(path) or "." for path in files} + with open(os.path.join(os.environ["RUNNER_TEMP"], "tflint-results.json")) as result: + report = json.load(result) + selected = [] + for issue in report["issues"]: + location = issue["range"] + path = os.path.normpath(location["filename"]) + if path in files or (location["start"]["line"] == 0 and (os.path.dirname(path) or ".") in dirs): + selected.append(issue) + rule = issue["rule"] + print(f'{rule["severity"]}: {issue["message"]} ({rule["name"]})') + print(f' {location["filename"]}:{location["start"]["line"]}') + print(f' {rule["link"]}') + if selected and os.environ["TFLINT_STATUS"] == "2": + sys.exit(2) + PY + + terraform-validate: + name: Validate Terraform + if: ${{ inputs.run_validate && needs.check-changed-files.outputs.tf_dirs != '[]' }} + needs: check-changed-files + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: ${{ inputs.terraform_version }} + terraform_wrapper: false + - name: Validate affected directories + env: + TF_DIRS: ${{ needs.check-changed-files.outputs.tf_dirs }} + run: | + status=0 + while IFS= read -r -d '' dir; do + echo "Validating $dir" + if ! (cd -- "$dir" && terraform init -backend=false -input=false && terraform validate); then + status=1 + fi + done < <(jq -j '.[] | ., "\u0000"' <<< "$TF_DIRS") + exit "$status" diff --git a/README.md b/README.md index 2caf044..07b1141 100644 --- a/README.md +++ b/README.md @@ -454,29 +454,17 @@ IDE integration matches those on the Snyk website. ``` ## The Terraform `terraform-static.yaml` workflow -### Background - -This workflow can be used to check against known configuration vulnerabilities, formatting and linting issues within the terraform code. It will also scan any containers (incl. dev containers) that exist within that repo. - -This is configured to run on PR to help with reviews of the terraform code quality, and it does not need any inputs. They Checkov scan and changed file scan run in parrallel. - -From a security scan perspective the Checkov scans will scan recursively any configuration files from the root of the repo. It may inadvertantly scan any other files that fall within the remit of the checkov scans as well. - -The repo will detect any changed files in the PR and anything with a .tf extension it will run terraform fmt -check as well as tflint. Through a quirk of tflint it will actually scan the entire directory even if --filter is used and output any global errors (e.g. invalid input errors). Any global errors will override any file based filters, these will need to be corrected before any other advisories can be seen. - -To preven this automatically running the on pull request configuration has been commented out. This will need uncommenting prior to use. - -### Steps - - - Checkov Scan - - Checkout Project - - Checkout branch from GitHub. - - Run Checkov scan from `.` highlighting critical vulnerabilities - - - Check modified files - - Check PR for for modified files and then check for any files with tf extention - - Run terraform fmt against modified files - - Run tflint recursively and filters on findings for modified files +Checks changed `.tf` files with `terraform fmt` and TFLint, and scans the whole +repository with Checkov. TFLint can still report directory-wide errors even when +findings are filtered to changed files. Optionally validates affected directories, +including directories with deleted `.tf` files if Terraform files remain. + +TFLint uses the root `.tflint.hcl` when present. Otherwise, the workflow creates a +temporary configuration enabling the built-in `terraform` plugin's `recommended` +preset. Both workflows install Terraform and TFLint, and cache TFLint plugins. +Validation runs `terraform init -backend=false -input=false` and `terraform validate` +in each directory; it may require network access, credentials for private modules, +and compatible provider and Terraform versions. ### Secrets @@ -484,29 +472,15 @@ None ### Inputs -None +- `terraform_version` (string, default `latest`): Terraform version. +- `tflint_version` (string, default `latest`): TFLint version. +- `run_validate` (boolean, default `false`): Validate affected Terraform directories. ## The Terraform `terraform-static-full.yaml` workflow -### Background - -This workflow follows a similar function as the terraform-static.yaml workflow but does not only run on the changes files in the repo but runs globally against all configuration files. - -### Steps - - Checkov Scan - - Checkout Project - - Checkout branch from GitHub. - - Terraform fmt check - - Checkout Project - - Checkout branch from GitHub. - - Run Terraform fmt action - - Run terraform fmt recursively check from `.` highlighting formatting issues - - tflint check - - Checkout Project - - Checkout branch from GitHub. - - Run tflint action - - Run tflint recursively check from `.` highlighting lint issues issues - +Runs Checkov, Terraform formatting and TFLint across the whole repository. It uses +the same TFLint fallback as the changed-files workflow. Optional validation runs +in every directory containing `.tf` files, excluding `.terraform` directories. ### Secrets @@ -514,17 +488,32 @@ None ### Inputs -When called form the project repositories the owners will need to specify a schedule. This will need to be specified in the 'on' trigger as part of the workflow (example provided below for every Monday at 0600). +- `terraform_version` (string, default `latest`): Terraform version. +- `tflint_version` (string, default `latest`): TFLint version. +- `run_validate` (boolean, default `false`): Validate every Terraform directory. -```YAML +These inputs are also available when dispatching the full workflow manually. +The composite Terraform actions default to Terraform `1.9.8`; see their +individual READMEs for action inputs. +For a scheduled caller, configure the trigger in the calling workflow. For example, +to run at 06:00 UTC every Monday: + +```yaml name: terraform-static-full on: schedule: - if: github.repository != 'dvsa/.github' - - cron: '* 6 * * mon' + - cron: '0 6 * * mon' + workflow_dispatch: + +permissions: + contents: read +jobs: + terraform-static: + if: github.repository != 'dvsa/.github' + uses: dvsa/.github/.github/workflows/terraform-static-full.yaml@v7 ``` ## The Java `java-security.yaml` workflow has the following steps: diff --git a/workflow-templates/terraform-static-full.properties.json b/workflow-templates/terraform-static-full.properties.json index 749aae5..d7b28bb 100644 --- a/workflow-templates/terraform-static-full.properties.json +++ b/workflow-templates/terraform-static-full.properties.json @@ -1,6 +1,6 @@ { "name": "DVSA Terraform Static Full Workflow", - "description": "Runs a tflint and tf format against any and all .tf files in the repo on a scheduled basis (0600 every Monday morning). Checkov will run against the entire repo on a scheduled basis (0600 every Monday morning)", + "description": "Checks all Terraform files with fmt and TFLint and scans the repository with Checkov, at 06:00 UTC every Monday or manually. Validation is optional.", "categories": [ "Terraform" ] diff --git a/workflow-templates/terraform-static-full.yaml b/workflow-templates/terraform-static-full.yaml index 16eec11..a44bbe8 100644 --- a/workflow-templates/terraform-static-full.yaml +++ b/workflow-templates/terraform-static-full.yaml @@ -2,7 +2,11 @@ name: terraform-static-full on: schedule: - - cron: '* 6 * * mon' + - cron: '0 6 * * mon' + workflow_dispatch: + +permissions: + contents: read jobs: terraform-static: diff --git a/workflow-templates/terraform-static.properties.json b/workflow-templates/terraform-static.properties.json index 69f0cd2..2853257 100644 --- a/workflow-templates/terraform-static.properties.json +++ b/workflow-templates/terraform-static.properties.json @@ -1,6 +1,6 @@ { "name": "DVSA Terraform Static Workflow", - "description": "Runs a tflint and tf format against any changed .tf files in the PR. Checkov will run against the entire repo each time a PR is created/altered", + "description": "Checks changed Terraform files with fmt and TFLint and scans the repository with Checkov. Validation is optional.", "categories": [ "Terraform" ] diff --git a/workflow-templates/terraform-static.yaml b/workflow-templates/terraform-static.yaml index c671873..c1cb8fe 100644 --- a/workflow-templates/terraform-static.yaml +++ b/workflow-templates/terraform-static.yaml @@ -2,6 +2,10 @@ name: terraform-static on: pull_request: + workflow_dispatch: + +permissions: + contents: read jobs: terraform-static: