@@ -119,7 +119,19 @@ func (r *TerraformUnusedDeclarationsRule) declarations(runner *terraform.Runner)
119119 {
120120 Type : "variable" ,
121121 LabelNames : []string {"name" },
122- Body : & hclext.BodySchema {},
122+ Body : & hclext.BodySchema {
123+ Blocks : []hclext.BlockSchema {
124+ {
125+ Type : "validation" ,
126+ Body : & hclext.BodySchema {
127+ Attributes : []hclext.AttributeSchema {
128+ {Name : "condition" },
129+ {Name : "error_message" },
130+ },
131+ },
132+ },
133+ },
134+ },
123135 },
124136 {
125137 Type : "data" ,
@@ -150,9 +162,21 @@ func (r *TerraformUnusedDeclarationsRule) declarations(runner *terraform.Runner)
150162}
151163
152164func (r * TerraformUnusedDeclarationsRule ) checkForRefsInExpr (expr hcl.Expression , decl * declarations ) {
165+ ReferenceLoop:
153166 for _ , ref := range lang .ReferencesInExpr (expr ) {
154167 switch sub := ref .Subject .(type ) {
155168 case addrs.InputVariable :
169+ // Input variables can refer to themselves as var.NAME inside validation blocks.
170+ // Do not mark such expressions as used, skip to next reference.
171+ if varBlock , exists := decl .Variables [sub .Name ]; exists {
172+ for _ , validationBlock := range varBlock .Body .Blocks {
173+ for _ , attr := range validationBlock .Body .Attributes {
174+ if attr .Expr .Range ().Overlaps (expr .Range ()) {
175+ continue ReferenceLoop
176+ }
177+ }
178+ }
179+ }
156180 delete (decl .Variables , sub .Name )
157181 case addrs.LocalValue :
158182 delete (decl .Locals , sub .Name )
0 commit comments