@@ -11,6 +11,57 @@ import (
1111func warnings (modules terraform.Modules ) hcl.Diagnostics {
1212 var diags hcl.Diagnostics
1313 diags = diags .Extend (unexpandedCountBlocks (modules ))
14+ diags = diags .Extend (unresolvedModules (modules ))
15+
16+ return diags
17+ }
18+
19+ // unresolvedModules does a best effort to try and detect if some modules
20+ // failed to resolve. This is usually because `terraform init` is not run.
21+ func unresolvedModules (modules terraform.Modules ) hcl.Diagnostics {
22+ var diags hcl.Diagnostics
23+ modulesUsed := make (map [string ]bool )
24+ modulesByID := make (map [string ]* terraform.Block )
25+
26+ // There is no easy way to know if a `module` failed to resolve. The failure is
27+ // only logged in the trivy package. No errors are returned to the caller. So
28+ // instead this code will infer a failed resolution by checking if any blocks
29+ // exist that reference each `module` block. This will work as long as the module
30+ // has some content. If a module is completely empty, then it will be detected as
31+ // "not loaded".
32+ blocks := modules .GetBlocks ()
33+ for _ , block := range blocks {
34+ if block .InModule () && block .ModuleBlock () != nil {
35+ modulesUsed [block .ModuleBlock ().ID ()] = true
36+ }
37+
38+ if block .Type () == "module" {
39+ modulesByID [block .ID ()] = block
40+ _ , ok := modulesUsed [block .ID ()]
41+ if ! ok {
42+ modulesUsed [block .ID ()] = false
43+ }
44+ }
45+ }
46+
47+ for id , v := range modulesUsed {
48+ if ! v {
49+ block , ok := modulesByID [id ]
50+ if ok {
51+ label := block .Type ()
52+ for _ , l := range block .Labels () {
53+ label += " " + fmt .Sprintf ("%q" , l )
54+ }
55+
56+ diags = diags .Append (& hcl.Diagnostic {
57+ Severity : hcl .DiagWarning ,
58+ Summary : "Module not loaded. Did you run `terraform init`?" ,
59+ Detail : fmt .Sprintf ("Module '%s' in file %q cannot be resolved. This module will be ignored." , label , block .HCLBlock ().DefRange ),
60+ Subject : & (block .HCLBlock ().DefRange ),
61+ })
62+ }
63+ }
64+ }
1465
1566 return diags
1667}
0 commit comments