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

查看:82
本文介绍了使用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-此程序只需运行一次.您可以在bucket和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天全站免登陆