Skip to content

Commit 0a3a2ae

Browse files
authored
Fix unintended errors when enabling Terraform rules by CLI (#1376)
1 parent 6d02f85 commit 0a3a2ae

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

tflint/runner.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -477,11 +477,15 @@ func (r *Runner) DecodeRuleConfig(ruleName string, val interface{}) error {
477477
if rule, exists := r.config.Rules[ruleName]; exists {
478478
// If you enable the rule through the CLI instead of the file, its hcl.Body will be nil.
479479
if rule.Body == nil {
480-
return errors.New("This rule cannot be enabled with the `--enable-rule` option because it lacks the required configuration")
481-
}
482-
diags := gohcl.DecodeBody(rule.Body, nil, val)
483-
if diags.HasErrors() {
484-
return diags
480+
diags := gohcl.DecodeBody(hcl.EmptyBody(), nil, val)
481+
if diags.HasErrors() {
482+
return errors.New("This rule cannot be enabled with the `--enable-rule` option because it lacks the required configuration")
483+
}
484+
} else {
485+
diags := gohcl.DecodeBody(rule.Body, nil, val)
486+
if diags.HasErrors() {
487+
return diags
488+
}
485489
}
486490
}
487491
return nil

tflint/runner_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,6 +1194,30 @@ func Test_DecodeRuleConfig_emptyBody(t *testing.T) {
11941194
}
11951195
}
11961196

1197+
func Test_DecodeRuleConfig_emptyBodyWithOptional(t *testing.T) {
1198+
type ruleSchema struct {
1199+
Foo string `hcl:"foo,optional"`
1200+
}
1201+
options := ruleSchema{}
1202+
1203+
cfg := EmptyConfig()
1204+
cfg.Rules["test"] = &RuleConfig{
1205+
Name: "test",
1206+
Enabled: true,
1207+
Body: nil,
1208+
}
1209+
1210+
runner := TestRunnerWithConfig(t, map[string]string{}, cfg)
1211+
if err := runner.DecodeRuleConfig("test", &options); err != nil {
1212+
t.Fatalf("Failed to decode rule config: %s", err)
1213+
}
1214+
1215+
expected := ruleSchema{Foo: ""}
1216+
if diff := cmp.Diff(options, expected); diff != "" {
1217+
t.Fatalf("Failed to decode rule config: diff=%s", diff)
1218+
}
1219+
}
1220+
11971221
func Test_listVarRefs(t *testing.T) {
11981222
cases := []struct {
11991223
Name string

0 commit comments

Comments
 (0)