1

I've the file structure below, terraform CLI is not using the runtime variable value in S3 file's content. It's always defaulting to 0 value.


Structure:

terraform
    main.tf
    api/
        variables.tf
        s3.tf

main.tf

module "api" {
  source = "./api"

  providers = {
    aws = "aws.us-east-1"
  }
}

variables.tf

variable "build-number" {
  description = "jenkins build number"
  type        = "string"
  default = "0"
}

s3.tf

resource "aws_s3_bucket_object" "api-build-version" {
  bucket = "api-code"
  key    = "build-version"
  content = "${var.build-number}"
  etag = "${md5("${var.build-number}")}"
}
terraform plan -var "build-number=2" -target aws_s3_bucket_object.api-build-version

My Terraform version is v0.11.8

1 Answer 1

2

In your structure, your variable is only under the API module

    terraform
        main.tf
        api/
            variables.tf
            s3.tf

You need that same variable at the root, add it to the main.tf or own file and then pass it on like this:

module "api" {
  source = "./api"

  build-number = "${var.build-number}"

  providers = {
    aws = "aws.us-east-1"
  }
}

All the sub-folders are modules in terraform, variables are not global... you do to declare variables on every level, and if they are identical you can do a symlink to one file to reduce copy-paste.


If it was just a flat structure you would not need that,
try this if you want:

variable "build-number" {
  type    = "string"
  default = "0"
}

output "test" {
  value = "${var.build-number}"
}

terraform apply -var "build-number=2"

That outputs the correct variable value

Sign up to request clarification or add additional context in comments.

3 Comments

You should remove the first part of this answer because it isn't helpful now that the question has been edited to show that the user wasn't passing the variable to the module correctly.
With your suggestion, its working only if I also copy variables.tf file to same level as main.tf. This is strange and needs 2 copies of the same variables file. terraform.io/docs/configuration/… apparently limits assigning values to root level variables and does not offer overriding module level variables.
@sumanj That is the way terraform works, all the folders are modules that is why you use the source = "./api" everything under that is "sandboxed" variables are not global... you do not need to copy the variable file just the var you need, and if they are identical you can do a symlink

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.