Content

Terraform集成简单Gitlab?CI方案详解(gitlab-ci-multi-runner)不看后悔

文章摘要

这篇文章描述了一个使用Terraform的完整部署脚本,涉及构建、验证、计划、应用和销毁阶段。脚本配置了使用squid代理和Tencent Cloud密钥的环境,设置了后端配置文件和缓存路径,并使用Hashicorp Terraform工具执行各阶段操作。构建阶段(PHASE: BUILD)和销毁阶段(PHASE: DESTROY)都设置了条件判断,确保只有当`$PHASE=="BUILD"`时才执行相应的命令。脚本还提到了使用quic CLI工具来自动化执行这些命令。

variables: # PHASE: BUILD|DESTROY PHASE: DESTROY # PROXY: http://squiduser:xxzx789@43.134.199.162:3128 # PROXY: http://squiduser:xxzx789@43.154.230.17:3128 REGION: “ap-guangzhou” PLAN_JSON: plan.json BACKEND_CONF: “backend_oss.conf” # before_script: # – apk add –no-cache curl git jq – apk add –no-cache jq – export http_proxy=${SQUID_PROXY} – export https_proxy=${SQUID_PROXY} – export TENCENTCLOUD_SECRET_KEY=${TENCENTCLOUD_SECRET_KEY} – export TENCENTCLOUD_SECRET_ID=${TENCENTCLOUD_SECRET_ID} – export TF_REGISTRY_CLIENT_TIMEOUT=120000 – export CHECKPOINT_TIMEOUT=500000 – export TF_REGISTRY_DISCOVERY_RETRY=5 – alias convert_report=”jq -r ‘([.resource_changes[]?.change.actions?]|flatten)|{“create”:(map(select(.==”create”))|length),”update”:(map(select(.==”update”))|length),”delete”:(map(select(.==”delete”))|length)}'” # 配置缓存 cache: paths: – ${CI_PROJECT_DIR}/.terraform/* stages: – init – validate – plan – deploy Init: image: name: hashicorp/terraform:0.14.0 entrypoint: [“”] stage: init retry: max: 2 when: – script_failure tags: – gitlab-runner-k8s-new script: – terraform version – terraform init -backend-config=${BACKEND_CONF} only: – dev Validate: image: name: hashicorp/terraform:0.14.0 entrypoint: [“”] stage: validate tags: – gitlab-runner-k8s-new retry: 2 script: – terraform init -backend-config=${BACKEND_CONF} – terraform validate – terraform fmt -check -recursive || echo 0 cache: paths: – ${CI_PROJECT_DIR}/.terraform/* policy: pull allow_failure: true Plan: image: name: hashicorp/terraform:0.14.0 entrypoint: [“”] stage: plan retry: 2 tags: – gitlab-runner-k8s-new artifacts: paths: – plan.bin – app_config.zip expire_in: 2 week script: – terraform init -backend-config=${BACKEND_CONF} – terraform plan -input=false -out=plan.bin -var region=${REGION} – terraform show –json “plan.bin” | convert_report > ${PLAN_JSON} – cat ${PLAN_JSON} only: variables: – $PHASE==”BUILD” Apply: image: name: hashicorp/terraform:0.14.0 entrypoint: [“”] when: manual stage: deploy retry: 2 tags: – gitlab-runner-k8s-new script: – terraform init -backend-config=${BACKEND_CONF} – terraform apply -auto-approve -input=false plan.bin only: variables: – $PHASE==”BUILD” environment: name: snunv Destroy: image: name: hashicorp/terraform:0.14.0 entrypoint: [“”] stage: deploy retry: 2 tags: – gitlab-runner-k8s-new script: – terraform init -backend-config=${BACKEND_CONF} – terraform destroy -auto-approve -var region=${REGION} only: variables: – $PHASE==”DESTROY”