Biju
Biju

Reputation: 1008

How to find list of all tfvars variables which are not used in Terraform code?

s3.tfvars

bucket = "first-bucket"
acl="private"
env = "dev"
owner = "[email protected]"
var1 = "unused variable"

s3.tf

resource "aws_s3_bucket" "abucket" {
  bucket = var.bucket 
  acl = "private"

  tags = {
    Environment = var.env
    Owner = var.owner
  }
}

var1 is not used in my code even though it is declared in tfvars as shown above.

When I run the following command

terraform plan -var-file=s3.tfvars

..., I get the following warning message:

Warning: Value for undeclared variable

The root module does not declare a variable named "var1" but a value was
found in file "s3.tfvars". To use this value, add a "variable" block to the
configuration.

Is there a way to capture this warning as an error? Or is there Any other way to find out list of all unused variables?

Upvotes: 6

Views: 7937

Answers (1)

SomeGuyOnAComputer
SomeGuyOnAComputer

Reputation: 6248

You want to use tflint.

mkdir test/
cd test/
echo 'variable "what" {}' > main.tf

Add .tflint.hcl

rule "terraform_unused_declarations" {
  enabled = true
}
$ tflint --init
$ tflint
1 issue(s) found:

Warning: variable "what" is declared but not used (terraform_unused_declarations)

  on main.tf line 1:
   1: variable "what" {}

Reference: https://github.com/terraform-linters/tflint/blob/v0.28.1/docs/rules/terraform_unused_declarations.md

Upvotes: 11

Related Questions