chew224
chew224

Reputation: 501

Terraform GCP: Just upload file name with google_storage_bucket_object

I want to upload files from my local file system to a new GCP Storage Bucket. I want to create a new directory in the storage bucket for the local files to reside in.

I can do this successfully, however Terraform creates the the full local file path in the Storage Bucket. I just want to create the GCP bucket, create new directories in the GCP bucket, and upload the local files.

variable "bucket_name" {
  default = "my-bucket-gfsdfdye32421"
}
variable "my_files" {
  default = ["local/docs/red.txt", "local/docs/blue.txt"]
}


resource "google_storage_bucket" "bucket" {
  name          = "${var.bucket_name}"
  force_destroy = true
}

resource "google_storage_bucket_object" "default" {
  count  = "${length(var.my_files)}"
  name   = "new_gcp_dir/${element(var.my_files, count.index)}"
  source = "${element(var.my_files, count.index)}"
  bucket = "${google_storage_bucket.bucket.name}"
}

The above code creates the following file structure in my GCP Bucket:

my-bucket / new_gcp_dir / local / docs / red.txt
my-bucket / new_gcp_dir / local / docs / blue.txt

I would like the GCP file structure to look like this instead:

my-bucket / new_gcp_dir / red.txt
my-bucket / new_gcp_dir / blue.txt

Upvotes: 1

Views: 2959

Answers (1)

Lockszmith
Lockszmith

Reputation: 2550

I assume you've resolved this already, but I'm posting an answer in case someone else finds this useful.

The reason you get local/ added to the path lies with the list you're providing.

Moving the local/ part as a literal in the source argument of the google_storage_bucket_object instance. Below is the code I'm proposing to solve this:

variable "bucket_name" {
  default = "my-bucket-gfsdfdye32421"
}
variable "my_files" {
  # removed `/local` from the elements in the list
  default = ["docs/red.txt", "docs/blue.txt"]
}

resource "google_storage_bucket" "bucket" {
  name          = "${var.bucket_name}"
  force_destroy = true
}

resource "google_storage_bucket_object" "default" {
  count  = "${length(var.my_files)}"
  name   = "new_gcp_dir/${element(var.my_files, count.index)}"
  # Add local/ as a literal prefixing the elements from the list
  source = "local/${element(var.my_files, count.index)}"
  bucket = "${google_storage_bucket.bucket.name}"
}

Upvotes: 2

Related Questions