Maxamis4
Maxamis4

Reputation: 188

AWS Codebuild Buildspec Terraform init backend error

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.

Upvotes: -1

Views: 453

Answers (1)

Maxamis4
Maxamis4

Reputation: 188

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.

Upvotes: 0

Related Questions