使用 terraform 初始设置 terraform 后端 [英] Initial setup of terraform backend using terraform

查看:36
本文介绍了使用 terraform 初始设置 terraform 后端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 terraform,我希望能够使用 AWS S3 作为我的后端来存储我的项目状态.

I'm just getting started with terraform and I'd like to be able to use AWS S3 as my backend for storing the state of my projects.

terraform {
    backend "s3" {
      bucket = "tfstate"
      key = "app-state"
      region = "us-east-1"
    }
}

我觉得用 terraform 为后端存储基础设施设置我的 S3 存储桶、IAM 组和策略是明智的.

I feel like it is sensible to setup my S3 bucket, IAM groups and polices for the backend storage infrastructure with terraform as well.

如果我在应用初始 terraform 基础设施之前设置了后端状态,它会合理地抱怨后端存储桶尚未创建.所以,我的问题变成了,如何使用 terraform 设置我的 terraform 后端,同时保持 terraform 跟踪后端的状态.看起来像是嵌套娃娃问题.

If I setup my backend state before I apply my initial terraform infrastructure, it reasonably complains that the backend bucket is not yet created. So, my question becomes, how do I setup my terraform backend with terraform, while keeping my state for the backend tracked by terraform. Seems like a nested dolls problem.

我对如何围绕此编写脚本有一些想法,例如,检查存储桶是否存在或是否设置了某个状态,然后引导 terraform,最后将 terraform tfstate 从本地文件系统复制到 s3首轮.但在走这条艰辛的道路之前,我想我会确保我没有遗漏一些明显的东西.

I have some thoughts about how to script around this, for example, checking to see if the bucket exists or some state has been set, then bootstrapping terraform and finally copying the terraform tfstate up to s3 from the local file system after the first run. But before going down this laborious path, I thought I'd make sure I wasn't missing something obvious.

推荐答案

为了使用 terraform 远程状态进行设置,我通常在我的 dev 和 prod terraform 文件夹中有一个名为 remote-state 的单独文件夹.

To set this up using terraform remote state, I usually have a separate folder called remote-state within my dev and prod terraform folder.

以下 main.tf 文件将为您发布的内容设置远程状态:

The following main.tf file will set up your remote state for what you posted:

provider "aws" {
  region = "us-east-1"
}

resource "aws_s3_bucket" "terraform_state" {
  bucket = "tfstate"

  versioning {
    enabled = true
  }

  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_dynamodb_table" "terraform_state_lock" {
  name           = "app-state"
  read_capacity  = 1
  write_capacity = 1
  hash_key       = "LockID"

  attribute {
    name = "LockID"
    type = "S"
  }
}

然后使用cd remote-state进入这个文件夹,并运行terraform init &&terraform apply - 这应该只需要运行一次.您可以在存储桶和 dynamodb 表名中添加一些内容以分隔不同的环境.

Then get into this folder using cd remote-state, and run terraform init && terraform apply - this should only need to be run once. You might add something to bucket and dynamodb table name to separate your different environments.

这篇关于使用 terraform 初始设置 terraform 后端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆