Should you apply before or after merging?

When making changes to IaC, do you merge a PR then apply, or vice versa?

Hiya,

Do you run terraform apply (or tofu apply) before or after you merge the PR that contains the HCL for the resources?

I've heard this question a bunch over the years. In particular, when I was teaching Terraform courses, this came up a lot. I think there is a definitive answer here.

What I believe and what we practice at Masterpoint: You always apply after merge.

Why? Because applying before merge means that you leave yourself open to the possibility of conflicts and drift.

Here's a simplistic example, with two PRs modifying the same environment and applying before merge (which shows the problem with this approach).

Let's call the author of PR #1 Sam. The author of PR #2 I'll refer to as Tracy.

  1. Both Sam and Tracy have their PRs up. They are are ready for review.

  2. Sam gets their PR reviewed, approved, and it is ready to apply.

  3. Sam applies the changes at the end of their day, but forgets to hit the merge button because their husband is giving them a hard time to come eat dinner.

  4. The next morning, Tracy gets their PR reviewed, approved and it is ready to apply. They apply and then merge PR #2. The problem is what if their apply OVERWRITES the work in the PR from Sam. For example, configuration gets rolled back, settings are not applied. This is bad. Very bad.

  5. Sam wakes up in their timezone and merges PR #1. They go about their day thinking all is good. But it is not; state has drifted. Who knows for how long?

The above problem simply cannot occur when you apply after merge. The code that gets merged gets applied, and you have a nice, orderly sequence of events.

Happy merge-then-applying,

Matt @ Masterpoint

PS We're shifting our focus at Masterpoint to focus on IaC. We'll be focusing on projects that involve Terraform, OpenTofu or Pulumi, so you'll be hearing a lot more about those technologies and approaches.

Respond to this email and say hey if you'd like to chat about how we can help.