Terraform - 每次申请时将文件上传到 S3 [英] Terraform - Upload file to S3 on every apply

查看:23
本文介绍了Terraform - 每次申请时将文件上传到 S3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个文件夹上传到 S3 Bucket.但是当我第一次申请时.它只是上传.但是我这里有两个问题:

I need to upload a folder to S3 Bucket. But when I apply for the first time. It just uploads. But I have two problems here:

  1. 上传的版本输出为空.我希望有一些 version_id,例如 1、2、3
  2. 再次运行 terraform apply 时,提示 Apply complete!资源:添加 0 个,更改 0 个,销毁 0 个.我希望在运行 terraform apply 并创建新版本时一直上传.
  1. uploaded version outputs as null. I would expect some version_id like 1, 2, 3
  2. When running terraform apply again, it says Apply complete! Resources: 0 added, 0 changed, 0 destroyed. I would expect to upload all the times when I run terraform apply and create a new version.

我做错了什么?这是我的 Terraform 配置:

What am I doing wrong? Here is my Terraform config:

resource "aws_s3_bucket" "my_bucket" {
  bucket = "my_bucket_name"

  versioning {
    enabled = true
  }
}

resource "aws_s3_bucket_object" "file_upload" {
  bucket = "my_bucket"
  key    = "my_bucket_key"
  source = "my_files.zip"
}

output "my_bucket_file_version" {
  value = "${aws_s3_bucket_object.file_upload.version_id}"
}

推荐答案

Terraform 仅在检测到配置和远程对象属性之间存在差异时才对远程对象进行更改.到目前为止,在您编写的配置中,配置仅包含文件名.它不包含有关文件内容的任何内容,因此 Terraform 无法对文件更改做出反应.

Terraform only makes changes to the remote objects when it detects a difference between the configuration and the remote object attributes. In the configuration as you've written it so far, the configuration includes only the filename. It includes nothing about the content of the file, so Terraform can't react to the file changing.

要进行后续更改,有几个选项:

To make subsequent changes, there are a few options:

  • 您可以为每个新版本使用不同的本地文件名.
  • 您可以为每个新版本使用不同的远程对象路径.
  • 无论本地文件名或对象路径如何,您都可以使用对象 etag 让 Terraform 识别内容何时发生更改.

在这种情况下,这些中的最后一个似乎最接近您想要的.为此,添加 etag 参数并将其设置为文件的 MD5 哈希:

The final of these seems closest to what you want in this case. To do that, add the etag argument and set it to be an MD5 hash of the file:

resource "aws_s3_bucket_object" "file_upload" {
  bucket = "my_bucket"
  key    = "my_bucket_key"
  source = "${path.module}/my_files.zip"
  etag   = "${filemd5("${path.module}/my_files.zip")}"
}

有了这个额外的参数,Terraform 将检测磁盘上文件的 MD5 哈希值何时与远程存储在 S3 中的不同,并计划相应地更新对象.

With that extra argument in place, Terraform will detect when the MD5 hash of the file on disk is different than that stored remotely in S3 and will plan to update the object accordingly.

(我不确定 version_id 发生了什么.只要在存储桶上启用了版本控制,它就应该工作.)

(I'm not sure what's going on with version_id. It should work as long as versioning is enabled on the bucket.)

这篇关于Terraform - 每次申请时将文件上传到 S3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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