我通过gitlab创建资源,但无法删除它们。一开始,我将计划输出到artifacts以在apply中应用它。然后创建资源,创建后我想删除它们。但删除它们是不行的,不可能像计划一样将它们输出到out,如果我只是在终端中输入destroy,作业运行成功,但删除了0个资源。我的.gitlab-ci.yaml是这样的
stages:
- validate
- plan
- apply
- destroy
before_script:
- rm -rf .terraform
- export AWS_ACCESS_KEY_ID
- export AWS_SECRET_ACCESS_KEY
- terraform init
validate:
stage: validate
script:
- terraform validate
tags:
- shell-runner
plan:
stage: plan
script:
- terraform plan -out "planfile"
dependencies:
- validate
artifacts:
paths:
- "planfile"
tags:
- shell-runner
apply:
stage: apply
script:
- terraform apply -input=false -auto-approve
dependencies:
- plan
tags:
- shell-runner
when: manual
destroy:
stage: destroy
script:
- terraform destroy -state="planfile" -auto-approve
tags:
- shell-runner
when: manual
您混淆了 Terraform 状态 与 Terraform 计划。
Terraform 状态是一个集中文件,用于存储有关所有基础设施的信息。
Terraform 计划是一个临时文件,仅包含计划更改。
请正确设置Terraform状态位置,并且在销毁时不要将计划文件设置为状态文件。您需要任何后端类型,但
local
。
我找到了解决方案之一 + 可以通过 s3 存储桶完成 https://docs.gitlab.com/ee/user/infrastruct/iac/terraform_state.html
stages:
- validate
- plan
- apply
image:
name: hashicorp/terraform:light
entrypoint:
- '/usr/bin/env'
- 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
before_script:
- export HCLOUD_TOKEN=${HCLOUD_TOKEN}
- rm -rf .terraform
- terraform --version
- terraform init
validate:
stage: validate
script:
- terraform validate
plan:
stage: plan
script:
- terraform plan -out "planfile" --var-file=secret.tfvars
dependencies:
- validate
artifacts:
paths:
- planfile
apply:
stage: apply
script:
- terraform apply -input=false "planfile"
dependencies:
- plan
when: manual
destroy:
stage: destroy
script:
- terraform init
- terraform destroy -auto-approve
when: manual
dependencies:
- apply