/
terraform_variable_separate.go
87 lines (76 loc) · 2.31 KB
/
terraform_variable_separate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package rules
import (
"github.com/Azure/tflint-ruleset-basic-ext/project"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/terraform-linters/tflint-plugin-sdk/logger"
"github.com/terraform-linters/tflint-plugin-sdk/tflint"
)
// TerraformVariableSeparateRule checks whether the variables are separated from other types of blocks
type TerraformVariableSeparateRule struct {
tflint.DefaultRule
}
// NewTerraformVariableSeparateRule returns a new rule
func NewTerraformVariableSeparateRule() *TerraformVariableSeparateRule {
return &TerraformVariableSeparateRule{}
}
// Name returns the rule name
func (r *TerraformVariableSeparateRule) Name() string {
return "terraform_variable_separate"
}
// Enabled returns whether the rule is enabled by default
func (r *TerraformVariableSeparateRule) Enabled() bool {
return false
}
// Severity returns the rule severity
func (r *TerraformVariableSeparateRule) Severity() tflint.Severity {
return tflint.NOTICE
}
// Link returns the rule reference link
func (r *TerraformVariableSeparateRule) Link() string {
return project.ReferenceLink(r.Name())
}
// Check checks whether the variables are separated from other types of blocks
func (r *TerraformVariableSeparateRule) Check(runner tflint.Runner) error {
files, err := runner.GetFiles()
if err != nil {
return err
}
for _, file := range files {
if subErr := r.checkVariableSeparate(runner, file); subErr != nil {
err = multierror.Append(err, subErr)
}
}
return err
}
func (r *TerraformVariableSeparateRule) checkVariableSeparate(runner tflint.Runner, file *hcl.File) error {
body, ok := file.Body.(*hclsyntax.Body)
if !ok {
logger.Debug("skip terraform_variable_separate check since it's not hcl file")
return nil
}
blocks := body.Blocks
var firstNonVarBlockRange *hcl.Range
variableDefined := false
for _, block := range blocks {
switch block.Type {
case "variable":
if !variableDefined {
variableDefined = true
}
default:
if firstNonVarBlockRange == nil {
firstNonVarBlockRange = ref(block.DefRange())
}
}
}
if variableDefined && firstNonVarBlockRange != nil {
return runner.EmitIssue(
r,
"Putting variables and other types of blocks in the same file is not recommended",
*firstNonVarBlockRange,
)
}
return nil
}