-1

I am trying to initialize my backend for the first time via AWS Codebuild. Up until this point I have been able to run the initial deployment. Once the Terraform Apply has been completed I try to initialize the backend and move it to S3. Here is the code post apply running with an active statefile in the directory:

Buildspec Section

- |
    echo "" >> main.tf
    echo "" >> main.tf
    echo "terraform { " >> main.tf
    echo "   backend \"s3\" { " >> main.tf
    echo "  }" >> main.tf
    echo "}" >> main.tf
    echo "yes" | terraform init \
      -backend-config="bucket=${backend_env}" \ 
      -backend-config="key=global/state/${bucketconfig}/terraform.tfstate" \
      -backend-config="region=us-east-1" \
      -backend-config="encrypt=true" \
      -backend-config="kms_key_id=${kmykeyid}" \
      -backend-config="dynamodb_table=iha-${tf_appenv}-${tf_tenant}-db-${bucketconfig}"
- echo "Complete"

Now note everything has worked up until the point where I add the backend configuration. As you also notice I have attempted to add the s3 resource dynamically which works. By running cat main.tf I am able to see that the s3 backend resource has been added to the file.

terraform {
  backend "s3" {

  }
}

I have validated all the variables and made sure all buckets and resources exist. I can't figure out why it's failing. One more note the sample code you see there is in the build spec file and its in a multiline section.

I am not exactly sure what's causing the issue with the command line CLI and I am looking for anyone to point me in the right direction.

Maxamis4
  • 137
  • 8
  • 2
    What is the error? – Marko E Feb 10 '22 at 08:09
  • It just says errror, typically this is an indication that it's a S3 Backend issue – Maxamis4 Feb 10 '22 at 12:17
  • Ok, I have a question then: why not create an empty backend file in your repo? Additionally, I would always use heredoc syntax for adding multiple lines to a file. Moreover, that can be done in a separate step, prior to running init. – Marko E Feb 10 '22 at 15:03
  • Well, I didn't include all the other code but I want it to be a cookie-cutter solution that can be called and not have to be associated with the one repo. In another word, I want it dynamic in order to facilitate other modules. Does that make sense? – Maxamis4 Feb 11 '22 at 00:04

1 Answers1

0

After trying a few things i got this version to work.

echo "yes" | terraform init -backend-config="bucket=${backend_env}" -backend-config="key=global/s3/state/${bucketconfig}/terraform.tfstate" -backend-config="region=us-east-1" -backend-config="encrypt=true" -backend-config="kms_key_id=${kmskeyid}" -backend-config="dynamodb_table=iha-${tf_appenv}-${tf_tenant}-db-${bucketconfig}"

My issue was that the backend would not initialize. I do believe the other syntax works but I am probably sending it through incorrectly. That said this worked. Appreciate the help from others who tried to help with this problem.

Maxamis4
  • 137
  • 8