我正在研究下面的 GitHub Actions 工作流程,并惊讶地发现
terraform apply terraform.tfplan
正在工作,尽管未执行完整的初始化 (terraform init -backend=false
)。
这让我更深入地了解
terraform init
和 terraform plan
命令。
-backend=false
选项记录如下:
为此禁用后端或 Terraform Cloud 初始化 配置并使用之前初始化的内容。
这到底是什么意思?这不是假设
terraform init
已经在配置上运行了吗?那么为什么我要使用 -backend=false
再次运行它呢?
查看生成的计划,我发现它包括
.terraform.lock.hcl
锁定文件和(二进制)tfplan 文件中的 S3 后端配置:
➜ tfplan unzip terraform.tfplan
Archive: terraform.tfplan
inflating: tfplan
inflating: tfstate
inflating: tfstate-prev
inflating: tfconfig/m-/providers.tf
inflating: tfconfig/m-/main.tf
inflating: tfconfig/modules.json
inflating: .terraform.lock.hcl
在
terraform plan
文档中,没有说明生成的计划包括后端配置和锁定文件,因此terraform apply
可以在其上运行而无需执行完整的初始化(即仅下载模块)?我应该避免依赖这个吗?
https://developer.hashicorp.com/terraform/cli/commands/plan
GitHub Actions 工作流程:
....
terraform-plan:
name: terraform-plan
runs-on: ubuntu-latest
timeout-minutes: 30
defaults:
run:
working-directory: terraform
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: recursive
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
aws-region: eu-west-1
role-to-assume: arn:aws:iam::729187411107:role/github-oidc-role
role-duration-seconds: 3600
role-session-name: github-${{ github.sha }}
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.5.7
- name: Terraform Init
run: |
terraform init \
-backend-config="bucket=terraform-approve-before-apply-tfstate" \
-backend-config="key=terraform.tfstate" \
-backend-config="region=eu-west-1"
- name: Terraform Plan
run: terraform plan -out=terraform.tfplan
- name: Upload Terraform Plan
uses: actions/upload-artifact@v4
with:
name: tfplan
path: |
terraform/terraform.tfplan
terraform/.terraform.lock.hcl
if-no-files-found: error
needs: terraform-validate
terraform-apply:
name: terraform-apply
runs-on: ubuntu-latest
timeout-minutes: 30
environment: deploy
defaults:
run:
working-directory: terraform
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: recursive
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
aws-region: eu-west-1
role-to-assume: arn:aws:iam::729187411107:role/github-oidc-role
role-duration-seconds: 3600
role-session-name: github-${{ github.sha }}
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.5.7
- name: Terraform Init
run: terraform init -backend=false
- name: Download Terraform Plan
uses: actions/download-artifact@v4
with:
name: tfplan
path: terraform
- name: Terraform Apply
run: terraform apply terraform.tfplan
needs: terraform-plan
Terraform init 只做了几件事:
如果您运行此命令
-backend=false
,它会使用可用的命令跳过后端初始化。
当然,如果有 .terraform.lock.hcl 它会重用它而不是创建一个新的。
但是仍然需要一些其他步骤来运行进一步的命令。