Yes, in Terraform, you can check for unused variables using the following methods:
1. Using terraform validate
Terraform has a built-in validation command that can sometimes catch unused variables.
terraform validate
However, this may not always detect unused variables.
2. Using tflint
(Recommended)
TFLint is a linter for Terraform that can detect unused variables.
Install TFLint:
brew install tflint # macOS
choco install tflint # Windows
Run TFLint:
tflint --enable-rule=terraform_unused_declarations
This will list all unused variables in your Terraform configuration.
3. Using terraform console
If you want to manually inspect the variables, you can run:
terraform console
Then check if a variable exists in var
:
var.variable_name
If the variable does not exist, it may be unused.
4. Using grep
or rg
(Ripgrep)
If you suspect unused variables in a file, you can manually check by searching for their usage.
Grep:
grep -r "variable" .
Ripgrep (Faster):
rg "variable" .
Then cross-check the variables defined in variables.tf
but never referenced in main.tf
or modules/
.
5. Using terraform graph
(Advanced)
Run:
terraform graph | grep var.
This will show all referenced variables. If a variable is not appearing, it might be unused.
Best Practice
Always review your variables.tf
and remove any variables that are no longer needed. Automate this check using TFLint in CI/CD pipelines.
Would you like a script to automate checking for unused variables?