From 86e8b29d5d15c8bec427de9535e0051a26b7346f Mon Sep 17 00:00:00 2001 From: nikpivkin Date: Wed, 7 Aug 2024 14:44:59 +0700 Subject: [PATCH] return the first block if no index is passed Signed-off-by: nikpivkin --- pkg/iac/scanners/terraform/ignore_test.go | 2 +- pkg/iac/terraform/block.go | 15 +++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/pkg/iac/scanners/terraform/ignore_test.go b/pkg/iac/scanners/terraform/ignore_test.go index e657d2276862..1f467162303f 100644 --- a/pkg/iac/scanners/terraform/ignore_test.go +++ b/pkg/iac/scanners/terraform/ignore_test.go @@ -433,7 +433,7 @@ resource "bad" "my-rule" { { name: "ignore by dynamic block value", inputOptions: ` -// trivy:ignore:*[secure_settings.0.enabled=false] +// trivy:ignore:*[secure_settings.enabled=false] resource "bad" "my-rule" { dynamic "secure_settings" { for_each = ["false", "true"] diff --git a/pkg/iac/terraform/block.go b/pkg/iac/terraform/block.go index db94f42272a7..898db7bff69f 100644 --- a/pkg/iac/terraform/block.go +++ b/pkg/iac/terraform/block.go @@ -350,12 +350,11 @@ func (b *Block) getAttributeByPath(path string) (*Attribute, []string) { stepIndex int ) - currentBlock := b - for currentBlock != nil && stepIndex <= len(steps)-1 { + for currentBlock := b; currentBlock != nil && stepIndex < len(steps); { blocks := currentBlock.GetBlocks(steps[stepIndex]) - var nextBlock *Block - if len(blocks) == 1 { + if !hasIndex(steps, stepIndex) && len(blocks) > 0 { + // if index is not provided then return the first block for backwards compatibility nextBlock = blocks[0] } else if len(blocks) > 1 && stepIndex < len(steps)-2 { // handling the case when there are multiple blocks with the same name, @@ -378,6 +377,14 @@ func (b *Block) getAttributeByPath(path string) (*Attribute, []string) { return attribute, steps[stepIndex:] } +func hasIndex(steps []string, idx int) bool { + if idx < 0 || idx >= len(steps) { + return false + } + _, err := strconv.Atoi(steps[idx]) + return err == nil +} + func getValueByPath(val cty.Value, path []string) (cty.Value, error) { var err error for _, step := range path {