Hugo
Hugo

Reputation: 2444

Manually trigger Github Actions workflow after another workflow successfully runs

I'm trying to create CI that does the following:

  1. Run terraform plan -out=plan.out to generate a Terraform plan.
  2. After looking at the Terraform plan output in Github actions, I can manually run another job or workflow that calls terraform apply plan.out with the previously generated plan. I want to manually run this automation after the other automation has successfully run, dependent on the previous automation's success, using an artifact from the previous automation.

I've looked online for some examples of this but all the examples of this I can find just run terraform apply without actually allowing someone to verify the plan output.

Is this something that's possible to do in Github Actions?

Upvotes: 0

Views: 2606

Answers (2)

Hugo
Hugo

Reputation: 2444

My solution ended up being the following:

When the PR is approved and merged, a Terraform plan is created and pushed to an S3 bucket with the commit hash in the path. Then when the apply workflow is triggered via workflow dispatch it looks for a plan for the commit hash of the code it's running and applies it.

Using pull requests as suggested wasn't the right solution for me because of the following:

  1. How do you know that the plan that was run for the pull request was run with the latest changes on the base branch? The plan could be invalid in this case. The way I solved this was by having the plan workflow run on push of a specific branch that corresponds to the environment being Terraformed. This way the plan is always generated for the state the Terraform says the specific environment should be in.

  2. How do you know that an apply is applying the exact plan that was generated for the pull request? All the examples I saw actually ended up re-running the plan in the apply workflow, which breaks the intended use of Terraform plans. The way I solved this was by having the apply workflow look for a specific commit hash in cloud storage.

Upvotes: 1

rethab
rethab

Reputation: 8413

This can be done using protected environments' required reviewers: https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment#required-reviewers

What you would do is setup an environment e.g. production and add yourself as reviewer.

In your workflow, you would then add the environments like so:

jobs:
  plan:
    steps:
      - run: terraform plan
  apply:
    environment: production
    steps:
      - run: terraform apply

This means that as soon as the workflow reaches the job apply, it is going to stop and you'll need to manually click a button to approve.

Upvotes: 1

Related Questions