简体   繁体   中英

How to integrate terraform in GitLab CI/CD

I have terraform scripts that creates resources. Each script is in different folder for the separation of concern. When I manually apply these script, I navigate to each folder and then use terraform apply.

1>cd c:\tf\kms\terraform apply
2>cd c:\tf\roles\terraform apply
3>cd c:\tf\lambda\terraform apply

for each apply I review the plan and then type yes to apply changes.

Now I have to make this part of GitLab CI/CD. But what I am missing here, in pipeline how do I apply changes? because apply will need manual interaction to type yes

Terraform has -auto-approve flag but I think that is very dangerous.

I would suggest a three-stage pipeline:

  • Stage 1. Validate the terraform config (terraform validate, tflint, regula or conftest)
  • Stage 2. Generate a plan
  • Stage 3. Apply the changes

Stages 1 and 2 should be automatic when a checkin is pushed, stage three would need an authorised human to press a button after reviewing the plan.

There are edge cases that you would need to be careful about, and you need to design the pipelines so that it's not possible to run in parallel. I would recommend that you also use a pull request process so that only after someone has approved the changes and merged the PR can the new Terraform be applied but that is up to you really.

It's quite important that the apply (stage 3) applies the plan as reported in stage 2 rather than regenerating the plan at that point otherwise it would be possible for the apply stage to do something different from the plan stage (if the underlying infrastructure changes for some reason). For this reason, you might also want to make the plan time out if it's not applied within the next hour, the pipeline forces you to rerun the plan.

There is also the question of state, where it is stored and who has access to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM