0

I am trying to add custom validation for the variables in my terraform script for S3 bucket. But i am facing an error that is mentioned as below:

Reference to undeclared input variable

  on main.tf line 2, in resource "aws_s3_bucket" "gouth_bucket_1_apr_2021":
   2:   bucket = var.bucket #"terraform-s3-bucket"

An input variable with the name "bucket" has not been declared. This variable
can be declared with a variable "bucket" {} block."

Can anyone help me on the same.please let me know which file needs the necessary changes and how.

Thanks in Advance

Below is my code :

main.tf :

    resource "aws_s3_bucket" "gouth_bucket_1_apr_2021" {
      bucket = var.bucket 
      acl = "private"
      tags= var.tags
    }
s3.tfvars :

    bucket = "first-bucket-gouth"
    
    #Variables of Tags
    tags= {
    name = "s3bucket",
    account_id = "1234567",
    owner = "[email protected]",
    os= "windows",
    backup = "N",
    application = "abc",
    description = "s3 bucket",
    env = "dev",
    ticketid = "101",
    marketami = "NA",
    patching = "NA",
    dc = "bangalore"
    }
validation.tf :

    variable "tags" {
        type = map(string)
        
        validation {
            condition = length(var.tags["env"]) > 0
            error_message = "Environment tag is required !!"
        }
        validation {
            condition = length(var.tags["owner"]) > 0
            error_message = "Owner tag is required !!"
        }
        validation {
            condition = length(var.tags["dc"]) > 0
            error_message = "DC tag is required !!"
        }
        validation {
            condition = can(var.tags["account_id"])
            error_message = "Acoount ID tag is required!!"
        }
    
    }

1
  • 1
    There is nothing wrong with the code you posted. Please make sure your question is fully representative of your actual error and code. Commented Apr 6, 2021 at 10:20

1 Answer 1

1

I can see two potential issues.

  1. You are referencing var.bucket in your resource, but you are not defining a variable for it anywhere in your definition. This could simply look like:
variable "bucket" {}
  1. You may not be picking up your tfvars file, if you are running Terraform with the tfvars file as an option like so terraform plan -var-file=s3.tfvars then thats ok, or you can rename your tfvars file to something.auto.tfvars or terraform.tfvars to get automatically used. (See > https://www.terraform.io/docs/language/values/variables.html#variable-definitions-tfvars-files)

I hope this answers your question.

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

Comments

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.