github.com/khulnasoft-lab/defsec@v1.0.5-0.20230827010352-5e9f46893d95/pkg/terraform/modules.go (about) 1 package terraform 2 3 import ( 4 "fmt" 5 6 "github.com/khulnasoft-lab/defsec/pkg/types" 7 ) 8 9 type Modules []*Module 10 11 type ResourceIDResolutions map[string]bool 12 13 func (r ResourceIDResolutions) Resolve(id string) { 14 r[id] = true 15 } 16 17 func (r ResourceIDResolutions) Orphans() (orphanIDs []string) { 18 for id, resolved := range r { 19 if !resolved { 20 orphanIDs = append(orphanIDs, id) 21 } 22 } 23 return orphanIDs 24 } 25 26 func (m Modules) GetResourcesByType(typeLabel ...string) Blocks { 27 var blocks Blocks 28 for _, module := range m { 29 blocks = append(blocks, module.GetResourcesByType(typeLabel...)...) 30 } 31 32 return blocks 33 } 34 35 func (m Modules) GetChildResourceIDMapByType(typeLabels ...string) ResourceIDResolutions { 36 blocks := m.GetResourcesByType(typeLabels...) 37 38 idMap := make(map[string]bool) 39 for _, block := range blocks { 40 idMap[block.ID()] = false 41 } 42 43 return idMap 44 } 45 46 func (m Modules) GetReferencedBlock(referringAttr *Attribute, parentBlock *Block) (*Block, error) { 47 var bestMatch *Block 48 for _, module := range m { 49 b, err := module.GetReferencedBlock(referringAttr, parentBlock) 50 if err == nil { 51 if bestMatch == nil || b.moduleBlock == parentBlock.moduleBlock { 52 bestMatch = b 53 } 54 } 55 } 56 if bestMatch != nil { 57 return bestMatch, nil 58 } 59 return nil, fmt.Errorf("block not found") 60 } 61 62 func (m Modules) GetReferencingResources(originalBlock *Block, referencingLabel string, referencingAttributeName string) Blocks { 63 var blocks Blocks 64 for _, module := range m { 65 blocks = append(blocks, module.GetReferencingResources(originalBlock, referencingLabel, referencingAttributeName)...) 66 } 67 68 return blocks 69 } 70 71 func (m Modules) GetBlocks() Blocks { 72 var blocks Blocks 73 for _, module := range m { 74 blocks = append(blocks, module.GetBlocks()...) 75 } 76 return blocks 77 } 78 79 func (m Modules) GetBlockById(id string) (*Block, error) { 80 for _, module := range m { 81 if found := module.blocks.WithID(id); found != nil { 82 return found, nil 83 } 84 85 } 86 return nil, fmt.Errorf("block not found") 87 } 88 89 func (m Modules) GetResourceByIDs(id ...string) Blocks { 90 var blocks Blocks 91 for _, module := range m { 92 blocks = append(blocks, module.GetResourcesByIDs(id...)...) 93 } 94 95 return blocks 96 } 97 98 func (m Modules) GetBlockByIgnoreRange(blockMetadata *types.Metadata) *Block { 99 for _, module := range m { 100 for _, block := range module.GetBlocks() { 101 metadata := block.GetMetadata() 102 if blockMetadata.Reference() == metadata.Reference() { 103 return block 104 } 105 } 106 } 107 return nil 108 }