We are going to design an infrastructure as code (IaC) review process that includes:
- Module versioning
- Automated policy checks
- Drift detection
- Peer reviews
- Staging rollouts
- Rollback procedures with audit trails
We assume we are using a common IaC tool (like Terraform) and a CI/CD system (like GitHub Actions, GitLab CI, Jenkins, etc.)
Let's break down each component:
-
Module Versioning:
- Use a versioning scheme for modules (e.g., semantic versioning).
- Store modules in a registry (like Terraform Module Registry, GitHub, etc.)
- In the root module, specify the module source with a version constraint (e.g.,
version = "~> 1.0").
-
Automated Policy Checks:
- Use policy as code tools (like Open Policy Agent, Terraform Sentinel, etc.) to enforce policies.
- Integrate policy checks in the CI pipeline (e.g., during plan stage).
- Policies can be about security, cost, tagging, etc.
-
Drift Detection:
- Regularly run
terraform plan (or equivalent) to detect drift between state and actual infrastructure.
- Can be scheduled or triggered on events.
- Report drift and require manual approval for correction.
-
Peer Reviews:
- Require at least one peer review for changes in IaC (via pull/merge requests).
- Use CI to automatically run linting, policy checks, and plan generation for review.
- Reviewers should check the plan for unexpected changes.
-
Staging Rollouts:
- Use a multi-stage environment (dev, staging, prod).
- Apply changes to staging first, run tests, then promote to prod.
- Can use feature flags or canary deployments for services.
-
Rollback Procedures with Audit Trails:
- Keep a history of state files and IaC code versions.
- In case of failure, revert to previous known good state and code version.
- Ensure every change is logged (who, what, when) and the rollback is also logged.
Implementation Steps:
A. Repository Structure:
- Separate repositories for modules and root modules? Or monorepo?
- Example:
infra/
modules/
network/
versions.tf
main.tf
variables.tf
environments/
dev/
main.tf (calls modules with specific versions)
staging/
main.tf
prod/
main.tf
B. CI/CD Pipeline:
For a pull request (PR) to the environment repository (e.g., changing dev environment):
1. Lint the code (e.g., `terraform fmt -check`, `tflint`).
2. Initialize and validate Terraform.
3. Run policy checks (using Sentinel or OPA).
4. Generate a Terraform plan and post it as a comment on the PR.
5. Require at least one peer approval (and optionally, an approval from a specific team for prod).
For merging to main (and deploying to an environment):
1. On merge to main (or specific branch for environment), trigger a pipeline for that environment.
2. For staging:
- Apply the change to staging (after manual approval?).
- Run integration tests (if applicable).
- If staging passes, then allow promotion to prod (via another PR or manual trigger).
For prod:
- Require a manual approval step (or automatic after staging passes and after a certain time).
- Apply to prod.
- Run post-deployment tests.
Rollback:
- If prod deployment fails, run a pipeline that applies the previous state (using the previous code version and state).
- The rollback should be triggered manually and require approvals.
C. Drift Detection:
- Schedule a daily (or hourly) job for each environment that runs terraform plan -detailed-exitcode.
- If drift is detected (exit code 2), create an issue or notify a channel.
D. Audit Trails:
- Use version control (Git) for code and a remote state backend (like S3 with versioning) for state files.
- Every plan and apply in CI should log the user (or service account) and the commit SHA.
- Consider using a tool like Terraform Cloud/Enterprise which has built-in audit logs.
E. Additional Considerations:
- Use workspaces for environments? Or separate state per environment? (We used separate directories for environments, which is one way. Workspaces are another.)
- Use a remote state backend with locking (e.g., S3 with DynamoDB lock).
- Use variables for environment-specific values (or tfvars files).
Example GitHub Actions Workflow for PR:
name: Terraform PR Check
on:
pull_request:
paths:
- 'environments/**'
jobs:
terraform:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: hashicorp/setup-terraform@v1
- name: Terraform Format
run: terraform fmt -check
- name: Terraform Init
run: terraform init
- name: Terraform Validate
run: terraform validate
- name: Terraform Plan
id: plan
run: terraform plan -no-color
- name: Comment PR
uses: actions/github-script@v3
with:
script: |
github.api.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '```\n' + steps.plan.outputs.stdout + '\n```'
})
Example for applying to staging on push to staging branch:
name: Terraform Apply Staging
on:
push:
branches:
- staging
jobs:
terraform:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: hashicorp/setup-terraform@v1
- name: Terraform Init
run: terraform init
- name: Terraform Apply
run: terraform apply -auto-approve
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
Note: For prod, we might want a manual approval step. We can use GitHub Environments with required reviewers.
F. Rollback:
We can have a separate workflow that applies the previous state. However, note that Terraform state and code must be in sync.
One approach:
- When we apply, we tag the commit (or create a release) and back up the state file (with versioning).
- In case of rollback, we check out the previous tag and apply.
Alternatively, we can use Terraform workspaces and just run terraform apply with the previous state (if we have state versioning, we can retrieve the previous state).
But note: if the infrastructure has changed outside of Terraform (drift), then rollback might not be straightforward.
Best practice is to avoid manual changes and use Terraform for everything. Then rollback is just applying the previous code.
However, if we must rollback, we can:
- Identify the last known good commit (or tag).
- Checkout that commit in the environment repository.
- Use the state file from that time (if we have state versioning, we can get the one from that time).
- Run
terraform apply (which should be a no-op if the state matches the infrastructure at that time, but if there were changes in between, it will revert them).
But note: if the infrastructure changed due to the last deployment and then we rollback, we are effectively destroying the new resources and recreating the old ones? Not exactly: Terraform will try to make the infrastructure match the configuration and state of the old commit.
However, if we have state versioning, we can also do:
terraform force-unlock (if locked) and then use an older state file.
But it's better to use the code and state from the same commit.
We can design the rollback workflow to:
- Take a parameter (the commit SHA to rollback to, or a tag, or a previous run number).
- Checkout that commit.
- Use the state file from that commit (if stored) or from the remote state (and we can use state versions to get the state from that time).
However, if we are using a remote state backend that supports versioning (like S3), we can:
1. List the state versions for that environment.
2. Choose the state version that corresponds to the desired rollback (by the time of the apply, or by the serial number).
But note: the state file might not be exactly the one from that commit if there were subsequent applies with the same code? Actually, each apply updates the state.
So for a rollback, we want the state and code from the same point in time.
We can store the state file as an artifact in the CI for each apply? Then we can retrieve the state from that artifact.
Alternatively, we can use Terraform Cloud/Enterprise which has state versioning and we can use the state from a specific run.
Given the complexity, it might be easier to:
- Always use the same code and state for an environment at a given time.
- When we apply, we record the commit SHA and the state version (or just the state file) in a database or as a tag.
Then for rollback:
- We have a script that:
1. Checks out the code at the desired commit (say, the one before the bad deployment).
2. Downloads the state file from that deployment (if we stored it) or from the remote state at that serial (if we can map the serial to the commit).
3. Runs `terraform apply` with that state and code.
However, note that if the state file is from an older version of the module, we might need to run terraform init -upgrade? Not necessarily if we are rolling back to the same code version.
But if we have updated the module version in the root module, then rolling back the root module might require a different module version.
This is why module versioning is important: we must be able to use the same module version that was used at that time.
So we should pin module versions. Then when we roll back the root module, we are using the same module version as before.
Steps for rollback:
1. Identify the last good deployment (by commit SHA or by time).
2. Checkout the root module at that commit.
3. Ensure the module versions are the same (if they are pinned, they will be).
4. Use the state file from that deployment (if we have it) or from the remote state at the serial number that corresponds to that deployment.
How to get the state file from a specific deployment?
Option 1: In the apply step, we save the state file as an artifact and record the commit SHA and the artifact location.
Option 2: Use the remote state backend's versioning and record the serial number (or version ID) for that apply.
Then for rollback:
- If using Option 1: download the state artifact, set the `TF_STATE` environment variable or place it in the working directory and run `terraform apply` (with the same backend configuration, it will use that state file).
- If using Option 2: we can use the remote state backend's CLI to get a specific version. For example, with S3, we can use `aws s3 cp` to get the state file at a specific version.
However, note that if we are using a remote state backend that is configured in the Terraform code, then when we run terraform init it will set up the backend and then terraform apply will use the latest state by default. We want to use an older state.
We can do:
- Run `terraform init` with the same backend configuration.
- Then, before applying, replace the current state file with the older one? But that might break if the state file is in a different format (due to Terraform version changes).
Alternatively, we can use the -state flag to specify the state file for the plan and apply.
Steps for rollback (using Option 1):
1. Checkout the code at the good commit.
2. Download the state file from the artifact (let's call it `terraform.tfstate.rollback`).
3. Run:
terraform init
terraform apply -state=terraform.tfstate.rollback
But note: the -state flag only changes the state file used for the operation, but after apply, it will write to the state file specified by the backend? Actually, the backend configuration in the code will override the state file location. So we must also change the backend configuration to point to the same backend? Or we can use the -state flag and then after apply, the state will be saved to the backend? Not exactly.
The -state flag only changes the state file used for the operation, but the backend is still configured and will store the state. So we are reading from the old state file and then writing to the backend? That would cause the backend to be updated with the state from the rollback apply, which is what we want.
However, if we are using a remote backend (like S3), then we are reading from a local file and then writing to S3? That might be acceptable.
But note: the state file we are using for the rollback must be compatible with the current Terraform version and the module versions.
Given the complexity, it might be better to use Terraform Cloud/Enterprise which has built-in rollback functionality (by running a prior successful run).
Since we are designing a generic process, let's assume we are using a remote state backend that does not have built-in versioning for rollback (like S3 without versioning). Then we must manage state versions ourselves.
Alternatively, we can use the following:
In the apply step (in CI), we do:
terraform apply -auto-approve
and then we copy the state file from the backend to an artifact? But the state file is stored in the backend, so we can download it after the apply and store it as an artifact.
Then for rollback:
We download the state artifact from the good deployment, and then we run:
terraform apply -state=downloaded_state_file
But note: the backend configuration in the code will still try to store the state in the backend. We don't want to change the backend configuration? Actually, we want to update the backend with the rolled back state.
So:
Step 1: Checkout the code at the good commit.
Step 2: Download the state file from the artifact (say, `good_state.tfstate`).
Step 3: Run `terraform init` (with the same backend configuration as in the code).
Step 4: Run `terraform apply -state=good_state.tfstate`
This will:
- Use the configuration from the good commit.
- Use the state from the good deployment (which is stored in `good_state.tfstate`).
- Then, after the apply, the state will be stored in the backend (because we ran `terraform init` which sets up the backend). But wait, the `-state` flag only changes the state file for reading and writing during the command, but the backend is still used for storing the state? Actually, when we run `terraform apply` with `-state`, it will read from that state file and then write the new state to that same state file, and then the backend is not updated? Let me check:
From the Terraform docs:
-state=path
Path to the state file to use. Defaults to "terraform.tfstate" in the working directory. This can also be specified via the TF_STATE environment variable.
So if we specify -state, then Terraform will use that state file and not the backend? Actually, the backend configuration is used for storing the state remotely, but if we specify -state then it overrides the state file used for the operation and also for storing?
The backend is configured in the terraform init step. When we run terraform init, it sets up the backend and then the state is stored in the backend. But when we run terraform apply with -state, it uses that state file and then writes the result to that state file? And does it also update the backend?
According to the docs:
The -state flag changes the path of the local state file, but note that Terraform will still use the configured backend to store the state remotely, and the local state file will be updated to match the remote state at the start of the operation.
So if we run:
terraform init
terraform apply -state=good_state.tfstate
Then:
- `terraform init` will set up the backend and download the remote state to the local state file (by default `terraform.tfstate`).
- Then `terraform apply` will read the state from `good_state.tfstate` (which we provided) and then write the new state to `good_state.tfstate`.
- But the backend state is not updated by `terraform apply`? Actually, the backend is updated by `terraform apply` only if the state file is the one that the backend is configured to use?
This is confusing.
Let me clarify:
When we run terraform init, it configures the backend and then the state operations (plan, apply) will use the backend. However, the -state flag overrides the state file for that particular command. But the backend is still the remote storage. So:
terraform init -> sets up backend, and if there's a remote state, it downloads it to the local state file (by default `terraform.tfstate`).
terraform apply -state=good_state.tfstate -> uses the state file `good_state.tfstate` for the operation, but does it update the backend?
The Terraform docs say:
The -state flag only affects the local state file that Terraform uses to track state during the current command. It does not change the backend configuration.
So after terraform apply, the remote state is not updated?
Actually, the backend is only used for storing the state when we run terraform apply without -state?
I think we must avoid using -state if we want to update the backend. Instead, we should use the backend's state and just have the state file we want to use be the one that the backend is configured to use.
So for rollback, we want to:
- Use the backend configuration (which points to the remote state).
- But we want to use a specific version of the state from the backend.
If the backend supports versioning (like S3 with versioning), we can:
- Temporarily change the backend configuration to point to a specific version? Not directly.
Alternatively, we can:
- Download the specific state version from the backend (using the backend's API) and then set the `TF_STATE` environment variable to that file? But then we are not using the backend for storage during the apply? We want to update the backend with the rolled back state.
So the steps:
1. Checkout the code at the good commit.
2. Download the state file from the backend at the desired version (using the backend's CLI or API). Let's call it `good_state.tfstate`.
3. Run `terraform init` (which will set up the backend and download the latest state to `terraform.tfstate`). But we don't want the latest, we want the old one.
4. Then, we replace the `terraform.tfstate` with `good_state.tfstate`? But then we are not using the backend for reading?
Alternatively, we can:
- Use the `-state` flag for the plan and apply, but then we must also update the backend?
Actually, the backend is only used for storing the state when we run terraform apply without -state. If we use -state, then the state is only stored in the file we specify and not in the backend?
This is not clear.
Given the complexity, and since we are designing a process, we might rely on Terraform Cloud/Enterprise which has a built-in rollback feature (by running a prior successful run).
If we are using open-source Terraform with a remote state backend that does not have versioning (or we don't want to use versioning), then we can:
- In the apply step, we store the state file as an artifact (and we know the commit SHA).
- For rollback, we check out the commit, download the state artifact, and then run:
terraform init
terraform apply -state=good_state.tfstate
and then after the apply, we manually upload the new state file (which is now the rolled back state) to the backend?
But note: the backend configuration in the code might be set to a different location. We want the backend to be updated with the rolled back state.
Alternatively, we can avoid using the backend for the rollback and just use the state file? But then subsequent runs will use the backend and might overwrite.
Given the complexity, I think the best practice is:
- Use a remote state backend that supports versioning (like S3 with versioning) and keep every version.
- Then, for rollback, we can:
Step 1: Checkout the code at the good commit.
Step 2: Run `terraform init` (which will set up the backend and by default download the latest state). But we don't want the latest, we want the state at the time of the good commit.
How to get the state at a specific time?
We can record the state version (or the S3 version ID) at each apply. Then:
terraform init -backend-config="bucket=mybucket" -backend-config="key=path/to/state" -backend-config="version_id=<the_version_id>"
But Terraform does not support specifying the version ID in the backend config. Instead, we can set the `TF_STATE` environment variable to a local file that we download from S3 at that version.
So:
aws s3api get-object --bucket mybucket --key path/to/state --version-id <version_id> good_state.tfstate
export TF_STATE=good_state.tfstate
terraform init
terraform apply
But note: `terraform init` will still try to download the state from the backend (without version) and then we are overriding with `TF_STATE`? Actually, the `TF_STATE` environment variable is used by Terraform to read the state, but when we run `terraform apply` it will write to the state file specified by `TF_STATE`? And then the backend is not updated?
We want to update the backend with the rolled back state.
So after we run `terraform apply` with `TF_STATE` set, the state file `good_state.tfstate` is updated. Then we need to upload that state file to the backend (to the latest version).
Alternatively, we can:
terraform apply -state=good_state.tfstate
and then:
aws s3 cp good_state.tfstate s3://mybucket/path/to/state
But then we are bypassing the backend. This is not recommended because the backend might have additional features (like locking).
Given the complexity, I think we should use Terraform Cloud/Enterprise for production if possible, because it handles state versioning and rollbacks natively.
If we are using open-source Terraform, we might design a rollback procedure that:
- Uses the same backend (with versioning enabled) and we record the version ID of the state after each apply.
- For rollback, we:
1. Checkout the code at the good commit.
2. Download the state file at the recorded version ID (for that commit) to a local file.
3. Run `terraform init` (which will set up the backend but we are going to use the local state file for the operation?).
4. Then run `terraform apply -state=local_state_file` and then after the apply, we upload the new state file (which is now the rolled back state) to the backend? But then we are updating the backend to a new version (the rolled back state) and we lose the version history?
Alternatively, we can:
- Use the backend's versioning and just run `terraform apply` without `-state` but how do we tell Terraform to use a specific version of the state? We can't.
So the only safe way with open-source Terraform and a versioned backend (like S3) is:
- To roll back, we must:
a. Download the state file at the desired version (the good one).
b. Run `terraform apply` with that state file (using `-state`).
c. Then, we must update the backend to that state file? But the backend already has the state at that version (if we are rolling back to an older version, we are effectively creating a new version that is the same as the old one?).
But note: if we run `terraform apply` with `-state`, it will update the local state file and then we can upload it to the backend (which will create a new version). Then the backend will have the rolled back state as the latest version.
However, if we want to keep the version history, we can just use the existing version? But then the backend's latest version will be the rolled back state, and the previous (bad) state is still there in an older version.
This is acceptable.
Steps for rollback (with S3 backend):
# Assume we have recorded the S3 version ID for the good state in a variable GOOD_STATE_VERSION
# Checkout the code at the good commit
git checkout <good_commit>
# Download the good state
aws s3api get-object --bucket mybucket --key path/to/state --version-id $GOOD_STATE_VERSION good_state.tfstate
# Initialize Terraform (this will set up the backend, but we are going to use the local state file for the apply)
terraform init
# Apply using the good state file
terraform apply -state=good_state.tfstate -auto-approve
# Now, the good_state.tfstate is updated with the changes from the apply (which should be none if the code and state match the infrastructure at that time). But if there were changes in between, we are reverting them.
# Then, we upload the updated state to the backend (this will create a new version in S3)
aws s3 cp good_state.tfstate s3://mybucket/path/to/state
But wait, what if the infrastructure changed between the good state and now? Then the apply will make changes to revert to the good state. And then we upload that state to the backend.
However, note that the backend configuration in the code might not be used when we upload with `aws s3 cp`. We are just copying the file. So the backend's state is updated, but Terraform doesn't know about it? Actually, the next time we run `terraform plan` or `apply` without `-state`, it will download the latest state from the backend (which is the rolled back state). So it should be consistent.
But we are bypassing the backend's locking and versioning? When we upload with `aws s3 cp`, we are not using the Terraform backend's API. So we might break the state versioning?
The better way is to use the Terraform backend's `terraform state push` command? But that command is deprecated.
Given the complexity, I think we should avoid rollbacks that require state manipulation and instead rely on reapplying the previous configuration and letting Terraform figure out the changes.
However, if we have drifted, then we must use the state from the previous deployment to avoid destroying resources.
Given the time, we might design a simpler rollback:
- We record the commit SHA and the state version (or the state file) for each successful apply.
- For rollback, we:
1. Checkout the code at the previous good commit.
2. Run `terraform init` (which will download the latest state from the backend, which is the bad state).
3. Then, we replace the downloaded state with the good state file (the one we recorded).
4. Then run `terraform apply` (without `-state` because we replaced the state file in the working directory?).
But note: the backend is configured and the state file in the working directory is the one we downloaded from the backend. We replace it with the good state. Then we run `terraform apply` and it will use the good state (which is in the working directory) and then update the backend?
Yes, because when we run `terraform apply` without `-state`, it uses the state file in the working directory (which is the good state we replaced) and then updates the backend.
Steps:
# Checkout the good commit
git checkout <good_commit>
# Initialize (downloads the latest state from the backend to terraform.tfstate)
terraform init
# Replace the downloaded state with the good state (which we have stored as an artifact)
cp good_state.tfstate terraform.tfstate
# Apply
terraform apply -auto-approve
This will:
- Use the configuration from the good commit.
- Use the state from the good deployment (we replaced the state file).
- Then, during apply, Terraform will see the difference between the good state and the current infrastructure (which is the result of the bad deployment) and will make changes to revert to the good state.
And then after apply, the state in the working directory (which is the good state) will be uploaded to the backend?
Yes, because we ran `terraform apply` without `-state` and the backend is configured. It will upload the state to the backend.
But note: we replaced the state file in the working directory, so the backend will be updated with the good state? Actually, after the apply, the state file in the working directory will be updated (if there were changes) and then uploaded to the backend.
This should work.
However, we must ensure that the good state file is compatible with the good commit's Terraform version and module versions.
So we must store the state file and the code together.
We can store the state file as an artifact in the CI for each successful apply, and record the commit SHA and the artifact location.
Then for rollback, we:
- Checkout the good commit.
- Download the state artifact for that commit.
- Replace the state file in the working directory with that artifact.
- Run `terraform apply`.
But note: the state file we download must be the one that was generated by the same version of Terraform and the same module versions? It should be, because we are using the same commit.
This seems feasible.
G. Summary of Rollback Procedure:
Pre-requisites:
- Every successful apply in the CI pipeline stores the state file as an artifact and records the commit SHA and the artifact location (or version).
Rollback steps:
1. Identify the last good deployment (by commit SHA or by time). Let's say we have a list of successful deployments with:
- Commit SHA
- State artifact URL (or S3 key)
2. Checkout the code at that commit SHA.
3. Download the state file from the artifact.
4. Run `terraform init` (to set up the backend and download the current state, but we are going to replace it).
5. Replace the `terraform.tfstate` file (or the state file in the working directory) with the downloaded state file.
6. Run `terraform apply -auto-approve` (or with manual approval).
7. This will update the infrastructure to match the configuration and state of the good commit, and then update the backend with the new state (which should be the same as the good state if no changes occurred, or updated if there were external changes).
Note: This procedure assumes that the infrastructure has not changed between the good deployment and the rollback (except for the changes we are rolling back). If there were other changes (drift) then the rollback will also revert those.
Also, note that if the bad deployment made changes that are not reversible (like deleted resources that were recreated with different names), then rollback might fail.
Therefore, it's important to have good change management and avoid manual changes.
H. Putting it all together:
We have:
- Module versioning: by specifying version in the root module.
- Automated policy checks: in the PR pipeline.
- Drift detection: scheduled job that runs `terraform plan` and reports.
- Peer reviews: via PR approvals.
- Staging rollouts: by having separate environments and promoting from staging to prod.
- Rollback: by reapplying a previous commit with its state.
We must also consider:
- Secrets management: use environment variables or a secrets manager (like AWS Secrets Manager) and never store in code.
- Variables: use tfvars files or environment variables for environment-specific values.
Example repository structure:
infra/
.github/workflows/
pr-check.yml
apply-staging.yml
apply-prod.yml
drift-detection.yml
rollback.yml (manual trigger)
modules/
network/
main.tf
variables.tf
outputs.tf
compute/
...
environments/
dev/
main.tf
variables.tfdev
staging/
main.tf
variables.tfstaging
prod/
main.tf
variables.tfprod
In the environment's main.tf, we call modules with specific versions:
module "network" {
source = "../modules/network"
version = "1.2.3"
...
}
And we use a versions.tf in the root to enforce Terraform version.
For drift detection:
name: Drift Detection
on:
schedule:
- cron: '0 0 * * *' # daily
jobs:
drift:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: hashicorp/setup-terraform@v1
- name: Terraform Init
run: terraform init
- name: Terraform Plan
id: plan
run: terraform plan -detailed-exitcode
- name: Check for drift
run: |
if [ ${{ steps.plan.outputs.exit-code }} -eq 2 ]; then
echo "Drift detected!"
# Send notification or create issue
fi
For rollback, we can have a workflow that is manually triggered and takes the commit SHA and the state artifact URL as inputs? Or we can have a script that looks up the last successful deploy.
Given the complexity of the rollback, we might want to have a separate tool or script that manages the state versions and rollback.
Alternatively, we can use Terraform Cloud which has a simple rollback button.
Since the question asks for an implementation, we'll provide a high-level design and not the full code for every step.
Let's write a sample rollback script (to be run in the CI or manually) that does:
#!/bin/bash
set -e
ENVIRONMENT=$1
COMMIT_SHA=$2
# Assume we have a way to get the state artifact for the given environment and commit.
# For example, we stored the state file in an S3 bucket with the key: states/<environment>/<commit_sha>.tfstate
STATE_ARTIFACT="s3://my-terraform-states/${ENVIRONMENT}/${COMMIT_SHA}.tfstate"
# Checkout the commit
git checkout $COMMIT_SHA
# Change to the environment directory
cd environments/$ENVIRONMENT
# Initialize Terraform
terraform init
# Download the state file
aws s3 cp $STATE_ARTIFACT terraform.tfstate
# Apply
terraform apply -auto-approve
But note: we are replacing the state file that was downloaded by terraform init? Actually, terraform init downloads the state from the backend (if configured) to terraform.tfstate. Then we overwrite it with the good state. Then we run terraform apply which uses that state.
And then after apply, the state will be uploaded to the backend (because we ran terraform apply without -state and the backend is configured). So the backend will have the new state (which should be the same as the good state if no changes, or updated if there were drift).
This should work.
However, we must ensure that the backend configuration in the code is the same as the one used in the original apply? It should be, because we are using the same code (just a different commit). But if the backend configuration changed between commits, then we might have a problem.
Therefore, we must also version the backend configuration? Or ensure that the backend configuration is the same for all commits?
We can store the backend configuration in the code (with variables) and make sure it doesn't change. Or we can have a separate backend configuration file that is the same for all environments and versions.
Given the complexity, it might be better to have a fixed backend configuration (like a specific S3 bucket and key pattern) and not change it.
In summary, we have designed a process that covers:
1. Module versioning: by pinning versions in the root module.
2. Automated policy checks: using Sentinel or OPA in the PR pipeline.
3. Drift detection: scheduled job.
4. Peer reviews: via PR approvals.
5. Staging rollouts: separate environments and promoting from staging to prod.
6. Rollback: by reapplying a previous commit with its state.
We have also provided example GitHub Actions workflows for PR checks and drift detection, and a rollback script.
Note: This is a high-level design and must be adapted to the specific tools and environment.
Additional considerations:
- Use of Terraform workspaces vs. separate directories: we used separate directories for environments. Workspaces are another way, but they have their own complexities (like state isolation and variable management). Separate directories are simpler for some.
- Use of a mono-repo vs. multiple repos: we used a mono-repo for all environments and modules. This makes it easy to version modules and have a single pipeline. However, for large organizations, multiple repos might be needed.
- Security: ensure that the CI runners have the necessary permissions and that secrets are stored in a secure way (like GitHub Secrets or AWS Secrets Manager).
- Testing: we did not include testing of the infrastructure (like integration tests). We can add a step after applying to staging to run tests (e.g., using a tool like InSpec, or simple curl checks). If tests fail, we block promotion to prod.
We hope this design is helpful.
I'll design a comprehensive Infrastructure as Code (IaC) review process that integrates all your requirements. Here's a production-ready implementation strategy:
Overall Architecture
graph TD
A[Developer] --> B[Feature Branch]
B --> C[Pull Request]
C --> D[Automated Pipeline]
D --> E{Checks Pass?}
E -->|Yes| F[Merge to Main]
E -->|No| G[Feedback]
F --> H[Staging Deployment]
H --> I[Integration Tests]
I --> J{Staging Approval}
J -->|Yes| K[Prod Deployment Canary]
K --> L[Full Prod Rollout]
L --> M[Monitor & Audit]
M --> N[Rollback if Needed]
subgraph "Policy & Versioning"
O[Module Registry] --> P[Semantic Versioning]
Q[OPA/Sentinel Policies] --> R[Automated Checks]
end
subgraph "State Management"
S[Terraform Cloud/Enterprise] --> T[State Versioning]
U[Drift Detection] --> V[Scheduled Runs]
end
subgraph "Audit"
W[Git History] --> X[Complete Trail]
Y[CI/CD Logs] --> Z[Execution Records]
end
1. Module Versioning System
Registry Setup
# terraform.tf (root module)
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
# Optional: Terraform Cloud/Enterprise for remote state/run tasks
cloud {
organization = "my-org"
workspaces {
name = "production"
}
}
}
# Module source with version constraints
module "vpc" {
source = "app.terraform.io/my-org/vpc/aws"
version = "~> 2.3.0" # Semantic versioning constraint
vpc_cidr = "10.0.0.0/16"
# ... other inputs
}
Implementation:
- Private Module Registry: Terraform Cloud/Enterprise, GitHub Packages, or Artifactory
- Versioning Strategy: Semantic Versioning (MAJOR.MINOR.PATCH)
- Dependency Lock File: Commit
terraform.lock.hcl to lock provider versions
- Module Testing: Each module has its own CI pipeline that runs:
terraform validate
terraform plan with example configurations
- Security scanning (Checkov, tfsec)
- Published only when all checks pass
2. Automated Policy Checks
Policy-as-Code Stack
# .github/workflows/policy-check.yml
name: Policy Validation
on: [pull_request]
jobs:
policy-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Terraform
uses: hashicorp/setup-terraform@v2
with:
terraform_version: 1.5.0
# OPA/Conftest for general policies
- name: Run OPA Policies
run: |
conftest test --policy policies/ --all-namespaces .
# Sentinel for Terraform Cloud/Enterprise
- name: Run Sentinel Checks
uses: hashicorp/sentinel-action@v1
with:
tf_plan: tfplan.json
policies: sentinel/
#专项检查
- name: Security Scan
uses: bridgecrewio/checkov-action@main
with:
directory: .
skip_check: CKV_AWS_23 # Example skip
- name: Cost Estimation
run: |
terraform plan -out=tfplan
infracost breakdown --path=tfplan --format=json > cost.json
# Fail if cost exceeds threshold
Policy Categories:
- Security: No public S3 buckets, encryption enabled, least privilege IAM
- Compliance: Region restrictions, tagging standards, backup requirements
- Cost: Max instance sizes, reserved instances usage, egress costs
- Operational: Proper monitoring, backup strategies, DR configurations
3. Drift Detection
Scheduled Drift Detection
# drift-detection.tf
resource "null_resource" "drift_detection" {
triggers = {
always_run = timestamp()
}
provisioner "local-exec" {
command = <<EOT
# Initialize in separate workspace
terraform workspace select drift-detection || terraform workspace new drift-detection
# Refresh state
terraform refresh
# Generate plan and check for changes
terraform plan -detailed-exitcode -out=drift-plan
EXIT_CODE=$?
if [ $EXIT_CODE -eq 2 ]; then
echo "DRIFT DETECTED!"
# Send alert
curl -X POST -H 'Content-type: application/json' \
--data '{"text":"Drift detected in ${var.environment}"}' \
${SLACK_WEBHOOK_URL}
# Create ticket
# terraform show -json drift-plan > drift.json
# jq -r '.resource_changes[] | "\(.address) changed from \(.change.before) to \(.change.after)"' drift.json
fi
EOT
interpreter = ["bash", "-c"]
}
# Run daily at 2 AM
cron_schedule = "0 2 * * *"
}
Implementation:
- Terraform Cloud/Enterprise: Built-in drift detection with notifications
- AWS Config Rules: For AWS-native drift detection
- Custom Scripts: For non-Terraform resources or cross-cloud
- Alerting: Slack/Teams/PagerDuty notifications with change details
4. Peer Review Process
PR Template (.github/pull_request_template.md)
## Infrastructure Change Checklist
### Required:
- [ ] Terraform plan included (attach plan output)
- [ ] All modules use approved versions
- [ ] No hardcoded secrets (used SSM/Secrets Manager)
- [ ] Tagging strategy followed (cost-center, env, owner)
- [ ] Security group rules minimized
- [ ] Backup/retention policies defined for data resources
- [ ] Post-apply verification steps documented
### Changes Impact:
- [ ] Production impact assessment completed
- [ ] Rollback procedure documented
- [ ] Maintenance window required? (Yes/No)
- [ ] Dependent services notified?
### Security:
- [ ] IAM changes reviewed by Security team
- [ ] Network changes reviewed by Network team
- [ ] Data store changes reviewed by Data team
### Testing:
- [ ] Staging tested successfully
- [ ] Integration tests passed
- [ ] Performance benchmarks met (if applicable)
Review Requirements:
# Required reviewers by change type
reviewers:
iam: ["security-team", "infra-lead"]
network: ["network-team", "infra-lead"]
database: ["dba-team", "infra-lead"]
compute: ["devops-team"]
# Auto-assignment based on changed files
automerge:
enabled: false
required_reviews: 2
dismiss_stale_reviews: true
require_code_owner_reviews: true
5. Staging Rollouts
Multi-Stage Pipeline
# .github/workflows/deploy.yml
name: Progressive Delivery
on:
push:
branches: [main]
jobs:
deploy-staging:
runs-on: ubuntu-latest
environment: staging
steps:
- uses: actions/checkout@v4
- name: Terraform Init & Plan
run: |
terraform init -backend-config="bucket=${{ secrets.TF_STATE_BUCKET }}"
terraform plan -out=tfplan
- name: Manual Approval
uses: peter-evans/slash-command-dispatch@v2
with:
token: ${{ secrets.PAT }}
reaction-token: ${{ secrets.GITHUB_TOKEN }}
command: '/approve-staging'
permission: 'write'
- name: Apply to Staging
if: success()
run: terraform apply -auto-approve tfplan
- name: Integration Tests
run: |
# Run smoke tests
./scripts/test-staging.sh
- name: Promote to Prod Approval
uses: peter-evans/slash-command-dispatch@v2
with:
command: '/promote-prod'
deploy-prod-canary:
needs: deploy-staging
runs-on: ubuntu-latest
environment: production-canary
if: ${{ github.event_name == 'workflow_dispatch' }}
steps:
- uses: actions/checkout@v4
- name: Deploy to Canary
run: |
terraform apply -var="canary_percent=10" -auto-approve
- name: Monitor Canary
run: |
./scripts/monitor-canary.sh 15m
deploy-prod-full:
needs: deploy-prod-canary
runs-on: ubuntu-latest
environment: production
if: success()
steps:
- uses: actions/checkout@v4
- name: Deploy to Full Production
run: terraform apply -auto-approve
Rollout Strategy:
- Blue/Green: Deploy parallel environment, switch load balancer
- Canary: 5% → 25% → 100% traffic shift with monitoring
- Feature Flags: Use tools like LaunchDarkly for gradual activation
- Auto-Rollback Triggers:
- Error rate > 1% for 5 minutes
- Latency p99 > 2x baseline
- Application availability < 99.9%
6. Rollback Procedures with Audit Trails
Terraform State Management
# backend.tf - Versioned state storage
terraform {
backend "s3" {
bucket = "my-terraform-states-${var.environment}"
key = "state/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks-${var.environment}"
encrypt = true
versioning = true # Enable S3 versioning
}
}
Rollback Script
#!/usr/bin/env bash
# rollback.sh - Atomic rollback with audit trail
set -euo pipefail
ENVIRONMENT=$1
TARGET_REVISION=$2 # Git SHA or Terraform state version
echo "Starting rollback for ${ENVIRONMENT} to ${TARGET_REVISION}"
# 1. Audit trail entry
aws dynamodb put-item \
--table-name terraform-audit \
--item '{
"timestamp": {"S": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"},
"action": {"S": "ROLLBACK_START"},
"environment": {"S": "'${ENVIRONMENT}'"},
"target_revision": {"S": "'${TARGET_REVISION}'"},
"initiated_by": {"S": "'${GITHUB_ACTOR:-unknown}'"},
"pull_request": {"S": "'${PR_NUMBER:-n/a}'"}
}'
# 2. Get previous state version
STATE_VERSION=$(aws s3api list-object-versions \
--bucket "my-terraform-states-${ENVIRONMENT}" \
--prefix "state/terraform.tfstate" \
--query "sort_by(Versions[?IsLatest==false], &LastModified)[-1].VersionId" \
--output text)
# 3. Checkout target revision
git checkout ${TARGET_REVISION}
# 4. Restore state
aws s3api get-object \
--bucket "my-terraform-states-${ENVIRONMENT}" \
--key "state/terraform.tfstate" \
--version-id ${STATE_VERSION} \
terraform.tfstate
# 5. Execute rollback
terraform apply -auto-approve
# 6. Capture rollback plan for audit
terraform plan -out=rollback-plan-${ENVIRONMENT}-$(date +%s).tfplan
# 7. Final audit entry
aws dynamodb put-item \
--table-name terraform-audit \
--item '{
"timestamp": {"S": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'"},
"action": {"S": "ROLLBACK_COMPLETE"},
"environment": {"S": "'${ENVIRONMENT}'"},
"state_version": {"S": "'${STATE_VERSION}'"},
"plan_file": {"S": "rollback-plan-${ENVIRONMENT}-$(date +%s).tfplan"}
}'
echo "Rollback completed successfully"
Audit Trail Database Schema (DynamoDB):
{
"timestamp": "2024-01-15T10:30:00Z",
"action": "APPLY|ROLLBACK|DRIFT_DETECTED",
"environment": "production",
"git_sha": "a1b2c3d4",
"terraform_version": "1.5.0",
"state_version": "v1.2.3",
"initiated_by": "user@example.com",
"pull_request": "123",
"changes": [
{
"resource": "aws_instance.web",
"action": "update",
"before": {"instance_type": "t2.micro"},
"after": {"instance_type": "t3.medium"}
}
],
"approvals": ["reviewer1", "reviewer2"],
"duration_seconds": 45,
"error_message": null
}
Complete Implementation Checklist
Prerequisites Setup:
CI/CD Pipeline Stages:
- Validate:
terraform fmt, terraform validate, tflint
- Plan: Generate plan, upload as artifact, cost estimation
- Policy Check: OPA/Sentinel/Checkov
- Security Scan: tfsec, Trivy
- Approval: Required reviewers, SLA timers
- Apply: Staging → Canary → Production
- Verify: Integration tests, smoke tests
- Audit: Log all actions to database
Rollback Triggers (Automated):
- Health check failures (Application Load Balancer 5xx errors)
- CloudWatch Alarms (CPU > 90%, Memory > 90%)
- Deployment duration > threshold
- Post-deployment test failures
Documentation Requirements:
- Runbooks: Step-by-step rollback procedures
- Architecture Diagrams: Current state with dependencies
- Contact Matrix: Who to page for each service
- Change Calendar: Scheduled maintenance windows
Sample GitHub Actions Configuration
# .github/workflows/terraform.yml
name: Infrastructure CI/CD
on:
pull_request:
paths:
- 'infra/**'
- 'modules/**'
push:
branches: [main, staging]
env:
TF_VERSION: '1.5.0'
WORKSPACE: ${{ github.ref == 'refs/heads/main' && 'production' || github.ref_name }}
jobs:
terraform:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
pull-requests: write
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # For git blame/history
- name: Setup Terraform
uses: hashicorp/setup-terraform@v2
with:
terraform_version: ${{ env.TF_VERSION }}
- name: Setup AWS Credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: us-east-1
# Linting & Validation
- name: Format Check
run: terraform fmt -check -recursive
- name: Validate
run: terraform validate
- name: TFLint
uses: terraform-linters/setup-tflint@v4
with:
tflint_version: latest
run: tflint --init && tflint
# Plan Generation
- name: Terraform Init
run: terraform init -backend-config="bucket=${{ secrets.TF_STATE_BUCKET }}"
- name: Terraform Plan
id: plan
run: |
terraform plan -out=tfplan -input=false
terraform show -json tfplan > tfplan.json
- name: Comment PR with Plan
if: github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
script: |
const output = `#### Terraform Plan 📦\`\`\`\n${process.env.PLAN}\`\`\`\n`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: output
})
# Policy & Security Checks
- name: Run OPA Policies
run: conftest test --policy policies/ --all-namespaces .
- name: Security Scan
uses: bridgecrewio/checkov-action@main
with:
directory: .
quiet: true
- name: Cost Estimation
uses: infracost/actions@v2
with:
api-key: ${{ secrets.INFRACOST_API_KEY }}
path: tfplan.json
currency: USD
# Apply (only on main/staging)
- name: Terraform Apply
if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/staging'
run: terraform apply -auto-approve tfplan
env:
# Required approvals already given via branch protection
TF_INPUT: false
Monitoring & Alerting Setup
# CloudWatch Alarms for deployments
Resources:
DeploymentFailureAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: terraform-deployment-failure
MetricName: TerraformApplyErrors
Namespace: Custom/Terraform
Statistic: Sum
Period: 300
EvaluationPeriods: 1
Threshold: 1
ComparisonOperator: GreaterThanOrEqualToThreshold
AlarmActions:
- !Ref SNSTopic
DriftDetectionAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName: infrastructure-drift-detected
MetricName: DriftDetected
Namespace: Custom/Terraform
Statistic: Sum
Period: 3600
EvaluationPeriods: 1
Threshold: 1
ComparisonOperator: GreaterThanOrEqualToThreshold
Key Success Metrics
- Lead Time: PR → Merge (target < 4 hours for non-critical)
- Change Failure Rate: < 15% (failed deployments/total deployments)
- Mean Time to Recovery (MTTR): < 30 minutes for rollbacks
- Policy Violations: 0 high-severity in production
- Drift Detection: < 1% of resources with drift
- Audit Completeness: 100% of changes logged
Recommended Tools Stack
| Category | Primary Tool | Alternatives |
|---|
| IaC | Terraform | Pulumi, Crossplane |
| Policy | OPA/Conftest | Sentinel, Checkov |
| Registry | Terraform Cloud | GitHub Packages, Artifactory |
| CI/CD | GitHub Actions | GitLab CI, Jenkins |
| Drift Detection | Custom Scripts | AWS Config, Cloud Custodian |
| Secrets | AWS Secrets Manager | HashiCorp Vault, Azure Key Vault |
| Monitoring | CloudWatch | Datadog, New Relic |
| Audit | DynamoDB + CloudTrail | Elasticsearch, Splunk |
This implementation provides:
- ✅ Complete audit trail (Git + state history + DynamoDB)
- ✅ Automated rollback with state versioning
- ✅ Progressive delivery with canary deployments
- ✅ Policy-as-code enforcement
- ✅ Drift detection with alerting
- ✅ Peer review with required approvers
- ✅ Module versioning with semantic constraints
Would you like me to elaborate on any specific component or provide additional implementation details for your specific cloud provider?