Giter Club home page Giter Club logo

terraform-plan's Introduction

Terraform Plan GitHub Action

Runs terraform plan on your project and posts a comment with the changes on a Pull Request (PR). It runs the following commands:

terraform init
terraform validate
terraform fmt --check
terraform plan -out=plan.tfplan
terraform show -json plan.tfplan 

This action does not install Terraform or Terragrunt, but can be installed using Terraform tools setup action. You can see how it's used in the pr-test.yaml workflow.

Settings

Use the following to control the action:

Setting Description Default
allow-failure Allow the action to fail false
comment Add comment with changes to the PR true
comment-delete Delete previous comments made by the bot on the PR false
comment-title The title to give the PR comment Plan changes
conftest-character-limit Character limit for Conftest output 2000
conftest-checks Location of custom conftest check definitions git::https://github.com/cds-snc/opa_checks.git//aws_terraform
directory Directory with the *.tf files to validate .
github-token GitHub Token used to add comment to PR (required to add comments).
plan-character-limit Character limit for Terraform plan output 30000
terraform-init Custom Terraform init args
terragrunt Use Terragrunt instead of Terraform false
skip-conftest Skip the Conftest step false
skip-fmt Skip the Terraform format check false
skip-plan Skip the Terraform plan for projects without a remote state false

Examples

# Setup Terraform, Terragrunt, and Conftest
- name: Setup terraform tools
  uses: cds-snc/terraform-tools-setup@v1

# Run Terraform plan and add a comment with changes on the PR
- name: Terraform plan
  uses: cds-snc/terraform-plan
  with:
    github-token: ${{ secrets.GITHUB_TOKEN }}

# Use Terragrunt, allow failure and set a custom PR comment title
- name: Terraform plan
  uses: cds-snc/terraform-plan
  with:
    allow-failure: true
    comment-title: Custom comment title
    github-token: ${{ secrets.GITHUB_TOKEN }}
    terragrunt: true

# Run on a sub project folder, deleting previous PR comments made by the action
- name: Terraform plan
  uses: cds-snc/terraform-plan
  with:
    directory: ./infra
    comment-delete: true
    github-token: ${{ secrets.GITHUB_TOKEN }}

# Run Terraform plan with no PR comment
# Plan will still availabe in the workflow logs
- name: Terraform plan
  uses: cds-snc/terraform-plan
  with:
    add-comment: false

# Run Terraform plan custom Terraform init args
- name: Terraform plan
  uses: cds-snc/terraform-plan
  with:
    github-token: ${{ secrets.GITHUB_TOKEN }}
    terraform-init: |
      -backend-config="bucket=your-state-bucket-name"
      -backend-config="region=ca-central-1"

Contributing

To setup your local dev environment:

npm install
npm run prepare

Husky provides a pre-commit hook that builds the dist/index.js used by the action. To test locally, nektos/act works well.

Policy

Open Policy Agent is used to check the terraform plan for changes. Policies are written in Rego and then compiled into a WebAssembly module using npm run policy.

terraform-plan's People

Contributors

calvinrodo avatar dsamojlenko avatar gcharest avatar maxneuvians avatar mohdnr avatar patheard avatar r3pli avatar renovate-cds[bot] avatar renovate[bot] avatar snyk-bot avatar sre-read-write[bot] avatar timarney avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

terraform-plan's Issues

Enhancement: Skip Plan

For the new account factory for terraform repos we are unable to run a tf plan because their isn't a specific backend to be able to run against, however there is still a need for init, validate, and format, and so this action is still useful

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Pending Approval

These branches will be created by Renovate only once you click their checkbox below.

  • chore(deps): update actions/checkout action to v4
  • chore(deps): update terraform aws to v5
  • fix(deps): update dependency @actions/github to v6
  • ๐Ÿ” Create all pending approval PRs at once ๐Ÿ”

Pending Status Checks

These updates await pending status checks. To force their creation now, click the checkbox below.

  • chore(deps): update dependency @vercel/ncc to v0.38.1

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yaml
  • actions/checkout v3.6.0@f43a0e5ff2bd294095638e18286ca9a3d1956744
  • actions/setup-node v3.8.1@5e21ff4d9bc1a8cf6de233a3057d20ec6b3fb69d
  • actions/cache v3.3.2@704facf57e6136b1bc63b828d79edcd491f0ee84
.github/workflows/labels.yml
  • cds-snc/sre-labels v1
.github/workflows/pr-test.yaml
  • actions/checkout v3.6.0@f43a0e5ff2bd294095638e18286ca9a3d1956744
  • cds-snc/terraform-tools-setup v1
  • actions/github-script v6.4.1@d7906e4ad0b1822421a7e6a35d5ca353c962f410
  • actions/checkout v3.6.0@f43a0e5ff2bd294095638e18286ca9a3d1956744
  • cds-snc/terraform-tools-setup v1
npm
package.json
  • @actions/core ^1.8.1
  • @actions/github ^5.0.1
  • @open-policy-agent/opa-wasm ^1.6.1
  • nunjucks ^3.2.3
  • @vercel/ncc 0.38.0
  • eslint 8.51.0
  • eslint-config-prettier 9.0.0
  • eslint-plugin-security 1.7.1
  • husky 8.0.3
  • jest 29.7.0
  • jest-when 3.6.0
  • mock-fs ^5.2.0
  • prettier 3.0.3
terraform
test/changes/changes.tf
  • test ~> 3.5.0
  • hashicorp/terraform >= 1.0.0
test/conftest-deny/conftest-deny.tf
  • aws ~> 4.15
  • hashicorp/terraform >= 1.0.0
test/format-error/format-error.tf
  • test ~> 3.5.0
  • hashicorp/terraform >= 1.0.0
test/init-fail/init-fail.tf
  • hashicorp/terraform >= 1.0.0
test/invalid/invalid.tf
  • test ~> 3.5.0
  • hashicorp/terraform >= 1.0.0
test/no-changes/no-changes.tf
  • test ~> 3.5.0
  • hashicorp/terraform >= 1.0.0
test/skip-conftest/skip-conftest.tf
  • test ~> 3.5.0
  • hashicorp/terraform >= 1.0.0
test/skip-plan/skip-plan.tf
  • test ~> 3.5.0
  • hashicorp/terraform >= 1.0.0
test/truncate-plan/truncate-plan.tf
  • aws ~> 4.15
  • hashicorp/terraform >= 1.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

Duplicate PR comments even with comment-delete enabled

We've noticed that even with comment-delete: true, we still get duplicate PR comments for the same plans:

Screenshot 2024-03-13 at 1 04 59โ€ฏPM

In the logs, there is no mention of Deleting comment which we'd expect if that code path was being hit correctly. So either it isn't ever getting to the deleteComment() function, or the comments.find() comes back empty.

[Enhancement] Drift Detection Mode

Add an option that will do the following:

  • Disable PR Commenting (as it will be run as a cron job in a repo)
  • Report the drift to a webhook for alerting

[feature] Implement `skip-fmt` input

Hi,

It'd be useful to have skip-fmt (similar to skip-plan) input. If it's true then terraform fmt --check is not execute so it does not check the code formatting and, as result, does not fail a workflow run.
Please see screenshot
image

Update documentation

Now that we have some external views on this project we really need to updated the documentation on how to use it.

Bug: Terraform commands with large output fail with `spawnSync /bin/sh ENOBUFS`

Summary

When one of the Terraform commands produces over 200kb of output, a spawnSync /bin/sh ENOBUFS error is thrown and the command fails.

Problem is explained in this StackOverflow answer:

The problem is that execSync mode execute the command within a shell with a limited buffer (200 Kb) used to forward the execution output. Moreover, the default shell execution option is "pipe", which means that the output must be forwarded to the parent.

Enhancement: Make it easier to see that init failed

Instead of having to look at the github action to see that the init failed it should render a message like

โœ… Terraform Init: Success
โŒ Terraform Init: Failed

And then display the error in a <details> section

Pre-Commit hook modifies files resulting in a second commit needed.

At the moment if we do a commit and the policy files are recompiled or the format is fixed we have to do a second commit after the first with the changes from the git commit hook.

This is an awkward workflow as we are constantly doing two commits when one should work.

Would be nice to either stage the changes from the hook automatically or change it to a test forcing the user to run the changes through NPM command line.

Bug: Terraform plan failing with a Terragrunt project

The format step in the action is reporting failures, possibly related to a project structure that has no *.tf files in the directories being planned.

PR and Pipeline run with failure.

terragrunt fmt --check

time=2021-07-08T13:42:25Z level=error msg=Hit multiple errors:
Hit multiple errors:
exit status 3
Command failed with exit code 3
time=2021-07-08T13:42:25Z level=error msg=Hit multiple errors:
Hit multiple errors:
exit status 3

Bug: Nunjucks comment template not found in remote repos

Summary

The code currently reads the the Nunjucks template from ./src/templates/comment.njk but this fails on remote repos using the action (it attempts to read the template from the repo repo).

Todo

  • Include comment.njk template from action repo

Remove OPA to get changed values.

This is not really needed and the compiling to wasm is not deterministic and is causing extra friction with external contributors.

We should just remove this and replace it with something that parses the plan json directly.

Trouble accessing SSH within devcontainer

Issue

Current VS Code's devcontainer config with SSH mounts causes an issue to pull/push to GH repo, whether connected to GH CLI or not.

Appears to only be affecting 1 user out of the 3 main users - the key known difference in the setup would be OS version since the device was upgraded during the day to macOS Ventura (13.0).

This thread seems to indicate there could be an issue with OpenSSH installed via Brew but further testing would be required to confirm.

Current setup

Device

Model Name: MacBook Pro
Model Identifier: MacBookPro16,1
Processor Name: 6-Core Intel Core i7
Processor Speed: 2.6 GHz
System Version: macOS 13.0 (22A380)
Kernel Version: Darwin 22.1.0

VS Code

Version: 1.72.2 (Universal)
Commit: d045a5eda657f4d7b676dedbfa7aab8207f8a075
Date: 2022-10-12T22:16:30.254Z
Electron: 19.0.17
Chromium: 102.0.5005.167
Node.js: 16.14.2
V8: 10.2.154.15-electron.0
OS: Darwin x64 22.1.0
Sandboxed: No

Error message screenshot

image

PR Format comment should be sanitized

If the terraform --fmt check command fails, make sure the Format comment text only contains *.tf filenames. It's possible for other command failure output to end up in the results.fmt.output.

Related #33

Bug: terraform show output failing to parse as JSON

cds-snc/forms-terraform#34 is getting the following error when using the action:

SyntaxError: Unexpected token c in JSON at position 1
    at JSON.parse (<anonymous>)
    at action (/home/runner/work/_actions/cds-snc/terraform-plan/v1.0.4/webpack:/terraform-plan/src/action.js:76:1)
    at /home/runner/work/_actions/cds-snc/terraform-plan/v1.0.4/webpack:/terraform-plan/src/index.js:16:1
    at /home/runner/work/_actions/cds-snc/terraform-plan/v1.0.4/dist/index.js:15326:3
    at Object.<anonymous> (/home/runner/work/_actions/cds-snc/terraform-plan/v1.0.4/dist/index.js:15329:12)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)

Action run with the failure:
https://github.com/cds-snc/forms-staging-terraform/runs/2955722574?check_suite_focus=true

RDS validation check OPA

error creating RDS cluster: InvalidParameterValue: MasterUsername admin cannot be used as it is a reserved word used by the engine

Able to run terraform plan without conftest

Is it possible to run terraform plan without conftest?

# Setup Terraform, Terragrunt, and Conftest
- name: Setup terraform tools
  uses: cds-snc/terraform-tools-setup@v1
  env:
    #   CONFTEST_VERSION: 0.30.0
    TERRAFORM_VERSION: 1.4.6
    TERRAGRUNT_VERSION: 0.45.10
  #   TF_SUMMARIZE_VERSION: 0.2.3

- name: Terragrunt plan
  uses: cds-snc/terraform-plan@v3
  with:
    directory: ./terraform
    comment-delete: "true"
    github-token: "${{ secrets.GITHUB_TOKEN }}"
    terragrunt: "true"

Resulting in failing pipelines;

Plan changes

โœ…   Terraform Init: success
โœ…   Terraform Validate: success
โœ…   Terraform Format: success
โœ…   Terraform Plan: success
โŒ   Conftest: failed

Plan: 5 to add, 0 to change, 0 to destroy

Show summary
Show plan
Show Conftest results

Restrict action to terraform version > 0.14.x

  • Fail the action if run on a terraform version that doesn't support sensitive
  • push a new build for v1, and for v2 that will add a message to the plan outlining that it's deprecated and stating why.
  • push a new v3 build.

Bug: failure to print command error output

This action run has the following error:

 terragrunt init -no-color 

TypeError: Cannot read property 'toString' of null
    at execCommand (/home/runner/work/_actions/cds-snc/terraform-plan/v1/webpack:/terraform-plan/src/command.js:26:1)
Error: Unhandled error: TypeError: Cannot read property 'toString' of null
    at action (/home/runner/work/_actions/cds-snc/terraform-plan/v1/webpack:/terraform-plan/src/action.js:63:1)
    at /home/runner/work/_actions/cds-snc/terraform-plan/v1/webpack:/terraform-plan/src/index.js:16:1
   ...

The cause is on line 26 in command.js where it tries to output the error message:

  } catch (error) {
    exitCode = error.status;
    output = `${error.stdout.toString("utf8")}${error.stderr.toString("utf8")}`;
    console.log(`Command failed: exit code ${exitCode}`);
  }

Checks should be added to make sure error.stdout and error.stderr are not null.

Enhancement: Make it easier to see that validation failed.

Make it easier to see that validation failed by commenting directly into the PR instead of forcing them to look at the action page.

โœ… Terraform Validate success
โŒ Terraform Validate failure

Display the output in a <detail> tag

Enhancement: add Terraform/Terragrunt update check

Summary

Add a version update check to the action that does the following:

  1. Checks the current latest version of Terraform/Terragrunt.
  2. Checks the versions installed and in use by the GitHub workflow.
  3. Adds a comment (non-blocking) to the PR if there is an update available.

The purpose of this will be to remind the team to update their versions of Terraform/Terragrunt.

Related

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Pending Approval

These branches will be created by Renovate only once you click their checkbox below.

  • chore(deps): update linters (major) (eslint, eslint-plugin-security)

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): lock file maintenance

Pending Status Checks

These updates await pending status checks. To force their creation now, click the checkbox below.

  • chore(deps): update dependency prettier to v3.3.1

Detected dependencies

devcontainer
.devcontainer/devcontainer.json
  • mcr.microsoft.com/vscode/devcontainers/base bullseye@sha256:9f76ab65f8aeb02e5e33cba37311fa3ac0a653e91e247db12e11d690566a446f
github-actions
.github/workflows/ci.yaml
  • actions/checkout v4.1.6@a5ac7e51b41094c92402da3b24376905380afc29
  • actions/setup-node v4.0.2@60edb5dd545a775178f52524783378180af0d1f8
  • actions/cache v4.0.2@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9
.github/workflows/labels.yml
  • cds-snc/sre-labels v1
.github/workflows/pr-test.yaml
  • actions/checkout v4.1.6@a5ac7e51b41094c92402da3b24376905380afc29
  • cds-snc/terraform-tools-setup v1
  • aws-actions/configure-aws-credentials v4.0.2@e3dd6a429d7300a6a4c196c26e071d42e0343502
  • actions/github-script v7.0.1@60a0d83039c74a4aee543508d2ffcb1c3799cdea
  • actions/checkout v4.1.6@a5ac7e51b41094c92402da3b24376905380afc29
  • cds-snc/terraform-tools-setup v1
npm
package.json
  • @actions/core ^1.8.1
  • @actions/github ^6.0.0
  • @open-policy-agent/opa-wasm ^1.6.1
  • nunjucks ^3.2.3
  • @vercel/ncc 0.38.1
  • eslint 8.57.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-security 2.1.1
  • husky 9.0.11
  • jest 29.7.0
  • jest-when 3.6.0
  • mock-fs ^5.2.0
  • prettier 3.2.5
terraform
test/changes/changes.tf
  • test ~> 3.6.0
  • hashicorp/terraform >= 1.0.0
test/conftest-deny/conftest-deny.tf
  • aws ~> 5.0
  • hashicorp/terraform >= 1.0.0
test/format-error/format-error.tf
  • test ~> 3.6.0
  • hashicorp/terraform >= 1.0.0
test/import/import.tf
  • aws ~> 5.0
  • hashicorp/terraform >= 1.0.0
test/init-fail/init-fail.tf
  • hashicorp/terraform >= 1.0.0
test/invalid/invalid.tf
  • test ~> 3.6.0
  • hashicorp/terraform >= 1.0.0
test/no-changes/no-changes.tf
  • test ~> 3.6.0
  • hashicorp/terraform >= 1.0.0
test/skip-conftest/skip-conftest.tf
  • test ~> 3.6.0
  • hashicorp/terraform >= 1.0.0
test/skip-fmt/skip-fmt.tf
  • test ~> 3.6.0
  • hashicorp/terraform >= 1.0.0
test/skip-plan/skip-plan.tf
  • test ~> 3.6.0
  • hashicorp/terraform >= 1.0.0
test/truncate-plan/truncate-plan.tf
  • aws ~> 5.0
  • hashicorp/terraform >= 1.0.0

Enhancement: do not allow Terraform version `< 0.14.x`

Summary

Terraform v0.14 released the sensitive input variable feature, which prevents variable values from being output in the plan.

Since this action outputs plan results, we should not allow it to run if the Terraform version is < 0.14 to prevent accidental secret leakage in the PR comment.

โš ๏ธ Note

To avoid breaking existing use of the action, this will result in a new major version of the action.

Enhancement: calculate large blast radius changes

Summary

If a TF plan includes a large number of changes, include a warning in the PR comment. This "large number of changes" should have a default value and also be configurable.

The use-case this is attempting to fix is to alert PR reviewers that something unexpected may be occurring.

Gateway validity check for OPA

In aws_api_gateway_integration you can specify a type (https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/api_gateway_integration#type). TF plan does not validate the uri based on the type, (https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/api_gateway_integration#uri

Required if type is AWS, AWS_PROXY, HTTP or HTTP_PROXY. For HTTP integrations, the URI must be a fully formed, encoded HTTP(S) URL according to the RFC-3986 specification . For AWS integrations, the URI should be of the form arn:aws:apigateway:{region}:{subdomain.service|service}:{path|action}/{service_api}. region, subdomain and service are used to determine the right endpoint. e.g. arn:aws:apigateway:eu-west-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-west-1:012345678901:function:my-func/invocations. For private integrations, the URI parameter is not used for routing requests to your endpoint, but is used for setting the Host header and for certificate validation.

It would be nice if the OPA could do that check :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.