diff --git a/docs/user-guide/compatibility.md b/docs/user-guide/compatibility.md index 95526d5cd..ecb69f4c8 100644 --- a/docs/user-guide/compatibility.md +++ b/docs/user-guide/compatibility.md @@ -123,37 +123,23 @@ The values below are state-dependent and cannot be determined statically, so TFL ## Dynamic Blocks -[Dynamic blocks](https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks) work just like normal blocks: +TFLint supports [dynamic blocks](https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks). ```hcl -resource "aws_instance" "static" { - ebs_block_device { - encrypted = false # => Must be encrypted - } -} - resource "aws_instance" "dynamic" { dynamic "ebs_block_device" { - for_each = var.block_devices + for_each = toset([ + { size = 10 }, + { size = 20 } + ]) content { - encrypted = false # => Must be encrypted + volume_size = ebs_block_device.value["size"] # => 10 and 20 } } } ``` -Note that iterator evaluation is not supported. - -```hcl -resource "aws_instance" "dynamic" { - dynamic "ebs_block_device" { - for_each = var.block_devices - content { - encrypted = ebs_block_device.value["encrypted"] # => ignored - } - } -} -``` +Similar to support for meta-arguments, some rules may process a dynamic block as-is without expansion. If the `for_each` is unknown, the block will be empty. ## Modules diff --git a/integrationtest/inspection/dynblock-unknown/.tflint.hcl b/integrationtest/inspection/dynblock-unknown/.tflint.hcl new file mode 100644 index 000000000..e19f589dd --- /dev/null +++ b/integrationtest/inspection/dynblock-unknown/.tflint.hcl @@ -0,0 +1,3 @@ +plugin "testing" { + enabled = true +} diff --git a/integrationtest/inspection/dynblock-unknown/main.tf b/integrationtest/inspection/dynblock-unknown/main.tf new file mode 100644 index 000000000..3384a0c42 --- /dev/null +++ b/integrationtest/inspection/dynblock-unknown/main.tf @@ -0,0 +1,69 @@ +variable "unknown_set" { + type = set(bool) +} + +variable "unknown_bool" { + type = bool +} + +resource "aws_s3_bucket" "main" { + lifecycle_rule { + enabled = true + } + + dynamic "lifecycle_rule" { + for_each = var.unknown_set + + content { + enabled = lifecycle_rule.value + } + } + + dynamic "lifecycle_rule" { + for_each = toset([var.unknown_bool]) + + content { + enabled = lifecycle_rule.value + } + } +} + +resource "aws_iam_role" "main" { + inline_policy { + name = "static" + } + + dynamic "inline_policy" { + for_each = toset(["foo", "bar"]) + + content { + name = inline_policy.value + } + } + + dynamic "inline_policy" { + for_each = var.unknown_set + + content { + name = inline_policy.value + } + } +} + +resource "testing_assertions" "main" { + equal "static" {} + + dynamic "equal" { + for_each = toset(["known_label"]) + iterator = it + labels = [it.value] + content {} + } + + dynamic "equal" { + for_each = toset(["unknown_label"]) + iterator = it + labels = ["${it.value}-${var.unknown_bool}"] + content {} + } +} diff --git a/integrationtest/inspection/dynblock-unknown/result.json b/integrationtest/inspection/dynblock-unknown/result.json new file mode 100644 index 000000000..f2745261b --- /dev/null +++ b/integrationtest/inspection/dynblock-unknown/result.json @@ -0,0 +1,145 @@ +{ + "issues": [ + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`lifecycle_rule` block found", + "range": { + "filename": "main.tf", + "start": { + "line": 10, + "column": 3 + }, + "end": { + "line": 10, + "column": 17 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`enabled` attribute found: true", + "range": { + "filename": "main.tf", + "start": { + "line": 11, + "column": 15 + }, + "end": { + "line": 11, + "column": 19 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`lifecycle_rule` block found", + "range": { + "filename": "main.tf", + "start": { + "line": 22, + "column": 3 + }, + "end": { + "line": 22, + "column": 27 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_iam_role_example", + "severity": "error", + "link": "" + }, + "message": "inline policy found", + "range": { + "filename": "main.tf", + "start": { + "line": 32, + "column": 3 + }, + "end": { + "line": 32, + "column": 16 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_iam_role_example", + "severity": "error", + "link": "" + }, + "message": "name is static", + "range": { + "filename": "main.tf", + "start": { + "line": 33, + "column": 12 + }, + "end": { + "line": 33, + "column": 20 + } + }, + "callers": [] + }, + { + "rule": { + "name": "testing_assertions_example", + "severity": "error", + "link": "" + }, + "message": "equal block found: label=static", + "range": { + "filename": "main.tf", + "start": { + "line": 54, + "column": 3 + }, + "end": { + "line": 54, + "column": 17 + } + }, + "callers": [] + }, + { + "rule": { + "name": "testing_assertions_example", + "severity": "error", + "link": "" + }, + "message": "equal block found: label=known_label", + "range": { + "filename": "main.tf", + "start": { + "line": 56, + "column": 3 + }, + "end": { + "line": 56, + "column": 18 + } + }, + "callers": [] + } + ], + "errors": [] +} diff --git a/integrationtest/inspection/dynblock/result.json b/integrationtest/inspection/dynblock/result.json index 0ccb63ccc..b881f6141 100644 --- a/integrationtest/inspection/dynblock/result.json +++ b/integrationtest/inspection/dynblock/result.json @@ -26,7 +26,7 @@ "severity": "error", "link": "" }, - "message": "`enabled` attribute found", + "message": "`enabled` attribute found: false", "range": { "filename": "template.tf", "start": { @@ -60,6 +60,26 @@ }, "callers": [] }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`days` attribute found: 30", + "range": { + "filename": "template.tf", + "start": { + "line": 5, + "column": 23 + }, + "end": { + "line": 5, + "column": 25 + } + }, + "callers": [] + }, { "rule": { "name": "aws_s3_bucket_example_lifecycle_rule", @@ -70,12 +90,12 @@ "range": { "filename": "template.tf", "start": { - "line": 15, - "column": 5 + "line": 20, + "column": 3 }, "end": { - "line": 15, - "column": 12 + "line": 20, + "column": 27 } }, "callers": [] @@ -86,16 +106,76 @@ "severity": "error", "link": "" }, - "message": "`enabled` attribute found", + "message": "`lifecycle_rule` block found", "range": { "filename": "template.tf", "start": { - "line": 16, + "line": 20, + "column": 3 + }, + "end": { + "line": 20, + "column": 27 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`enabled` attribute found: false", + "range": { + "filename": "template.tf", + "start": { + "line": 24, "column": 17 }, "end": { - "line": 16, - "column": 37 + "line": 24, + "column": 65 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`enabled` attribute found: true", + "range": { + "filename": "template.tf", + "start": { + "line": 24, + "column": 17 + }, + "end": { + "line": 24, + "column": 65 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`transition` block found", + "range": { + "filename": "template.tf", + "start": { + "line": 26, + "column": 7 + }, + "end": { + "line": 26, + "column": 27 } }, "callers": [] @@ -110,12 +190,292 @@ "range": { "filename": "template.tf", "start": { - "line": 21, - "column": 9 + "line": 26, + "column": 7 + }, + "end": { + "line": 26, + "column": 27 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`transition` block found", + "range": { + "filename": "template.tf", + "start": { + "line": 26, + "column": 7 + }, + "end": { + "line": 26, + "column": 27 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`transition` block found", + "range": { + "filename": "template.tf", + "start": { + "line": 26, + "column": 7 + }, + "end": { + "line": 26, + "column": 27 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`days` attribute found: 30", + "range": { + "filename": "template.tf", + "start": { + "line": 30, + "column": 27 + }, + "end": { + "line": 30, + "column": 90 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`days` attribute found: 40", + "range": { + "filename": "template.tf", + "start": { + "line": 30, + "column": 27 + }, + "end": { + "line": 30, + "column": 90 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`days` attribute found: 60", + "range": { + "filename": "template.tf", + "start": { + "line": 30, + "column": 27 + }, + "end": { + "line": 30, + "column": 90 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`days` attribute found: 70", + "range": { + "filename": "template.tf", + "start": { + "line": 30, + "column": 27 + }, + "end": { + "line": 30, + "column": 90 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`lifecycle_rule` block found", + "range": { + "filename": "template.tf", + "start": { + "line": 46, + "column": 3 + }, + "end": { + "line": 46, + "column": 27 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`lifecycle_rule` block found", + "range": { + "filename": "template.tf", + "start": { + "line": 46, + "column": 3 + }, + "end": { + "line": 46, + "column": 27 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`lifecycle_rule` block found", + "range": { + "filename": "template.tf", + "start": { + "line": 46, + "column": 3 + }, + "end": { + "line": 46, + "column": 27 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`lifecycle_rule` block found", + "range": { + "filename": "template.tf", + "start": { + "line": 46, + "column": 3 + }, + "end": { + "line": 46, + "column": 27 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`enabled` attribute found: false", + "range": { + "filename": "template.tf", + "start": { + "line": 50, + "column": 17 + }, + "end": { + "line": 50, + "column": 51 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`enabled` attribute found: false", + "range": { + "filename": "template.tf", + "start": { + "line": 50, + "column": 17 + }, + "end": { + "line": 50, + "column": 51 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`enabled` attribute found: false", + "range": { + "filename": "template.tf", + "start": { + "line": 50, + "column": 17 + }, + "end": { + "line": 50, + "column": 51 + } + }, + "callers": [] + }, + { + "rule": { + "name": "aws_s3_bucket_example_lifecycle_rule", + "severity": "error", + "link": "" + }, + "message": "`enabled` attribute found: true", + "range": { + "filename": "template.tf", + "start": { + "line": 50, + "column": 17 }, "end": { - "line": 21, - "column": 16 + "line": 50, + "column": 51 } }, "callers": [] diff --git a/integrationtest/inspection/dynblock/template.tf b/integrationtest/inspection/dynblock/template.tf index 6ae07e759..b160109ef 100644 --- a/integrationtest/inspection/dynblock/template.tf +++ b/integrationtest/inspection/dynblock/template.tf @@ -9,20 +9,45 @@ resource "aws_s3_bucket" "bucket" { } resource "aws_s3_bucket" "dynamic" { + dynamic "cors_rule" { + for_each = toset(["*"]) + + content { + allowed_headers = [cors_rule.value] + } + } + dynamic "lifecycle_rule" { - for_each = toset([true]) + for_each = toset([true, false]) content { - enabled = lifecycle_rule.value + enabled = var.force_disable ? false : lifecycle_rule.value dynamic "transition" { - for_each = toset([30]) + for_each = toset([30, 60]) content { - days = transition.value + days = lifecycle_rule.value ? transition.value + 10 : transition.value storage_class = "STANDARD_IA" } } } } } + +variable "force_disable" { + type = bool + default = false +} + +resource "aws_s3_bucket" "dynamic_with_meta_arguments" { + for_each = toset([true, false]) + + dynamic "lifecycle_rule" { + for_each = toset([true, false]) + + content { + enabled = lifecycle_rule.value && each.value + } + } +} diff --git a/integrationtest/inspection/inspection_test.go b/integrationtest/inspection/inspection_test.go index 2eb803c75..d98d05228 100644 --- a/integrationtest/inspection/inspection_test.go +++ b/integrationtest/inspection/inspection_test.go @@ -118,6 +118,11 @@ func TestIntegration(t *testing.T) { Command: "./tflint --format json", Dir: "dynblock", }, + { + Name: "unknown dynamic blocks", + Command: "./tflint --format json", + Dir: "dynblock-unknown", + }, { Name: "provider config", Command: "./tflint --format json", diff --git a/plugin/server.go b/plugin/server.go index 8bd18dfe8..dfa90fa9f 100644 --- a/plugin/server.go +++ b/plugin/server.go @@ -115,9 +115,7 @@ func (s *GRPCServer) EvaluateExpr(expr hcl.Expression, opts sdk.EvaluateExprOpti runner = s.rootRunner } - // We always use EvalDataForNoInstanceKey here because an expression that depend on - // an instance key, such as `each.key` and `count.index`, is already bound. - val, diags := runner.Ctx.EvaluateExpr(expr, *opts.WantType, terraform.EvalDataForNoInstanceKey) + val, diags := runner.Ctx.EvaluateExpr(expr, *opts.WantType) if diags.HasErrors() { return val, diags } diff --git a/plugin/server_test.go b/plugin/server_test.go index 8d218d20f..e64d5b5de 100644 --- a/plugin/server_test.go +++ b/plugin/server_test.go @@ -21,10 +21,22 @@ func TestGetModuleContent(t *testing.T) { runner := tflint.TestRunner(t, map[string]string{"main.tf": ` resource "aws_instance" "foo" { instance_type = "t2.micro" + + ebs_block_device {} + dynamic "ebs_block_device" { + for_each = toset(["foo"]) + content {} + } } resource "aws_instance" "baz" { count = 0 instance_type = "t3.nano" + + ebs_block_device {} + dynamic "ebs_block_device" { + for_each = toset(["foo"]) + content {} + } }`}) rootRunner := tflint.TestRunner(t, map[string]string{"main.tf": ` resource "aws_instance" "bar" { @@ -48,6 +60,7 @@ resource "aws_instance" "bar" { LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{ Attributes: []hclext.AttributeSchema{{Name: "instance_type"}}, + Blocks: []hclext.BlockSchema{{Type: "ebs_block_device"}}, }, }, }, @@ -60,6 +73,16 @@ resource "aws_instance" "bar" { Labels: []string{"aws_instance", "foo"}, Body: &hclext.BodyContent{ Attributes: hclext.Attributes{"instance_type": &hclext.Attribute{Name: "instance_type"}}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + }, }, }, }, @@ -87,6 +110,7 @@ resource "aws_instance" "bar" { Labels: []string{"aws_instance", "bar"}, Body: &hclext.BodyContent{ Attributes: hclext.Attributes{"instance_type": &hclext.Attribute{Name: "instance_type"}}, + Blocks: hclext.Blocks{}, }, }, }, @@ -102,6 +126,7 @@ resource "aws_instance" "bar" { LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{ Attributes: []hclext.AttributeSchema{{Name: "instance_type"}}, + Blocks: []hclext.BlockSchema{{Type: "ebs_block_device"}}, }, }, }, @@ -111,16 +136,28 @@ resource "aws_instance" "bar" { Blocks: hclext.Blocks{ { Type: "resource", - Labels: []string{"aws_instance", "foo"}, + Labels: []string{"aws_instance", "baz"}, Body: &hclext.BodyContent{ Attributes: hclext.Attributes{"instance_type": &hclext.Attribute{Name: "instance_type"}}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + }, }, }, { Type: "resource", - Labels: []string{"aws_instance", "baz"}, + Labels: []string{"aws_instance", "foo"}, Body: &hclext.BodyContent{ Attributes: hclext.Attributes{"instance_type": &hclext.Attribute{Name: "instance_type"}}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + }, }, }, }, @@ -136,6 +173,7 @@ resource "aws_instance" "bar" { LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{ Attributes: []hclext.AttributeSchema{{Name: "instance_type"}}, + Blocks: []hclext.BlockSchema{{Type: "ebs_block_device"}}, }, }, }, @@ -145,16 +183,28 @@ resource "aws_instance" "bar" { Blocks: hclext.Blocks{ { Type: "resource", - Labels: []string{"aws_instance", "foo"}, + Labels: []string{"aws_instance", "baz"}, Body: &hclext.BodyContent{ Attributes: hclext.Attributes{"instance_type": &hclext.Attribute{Name: "instance_type"}}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + }, }, }, { Type: "resource", - Labels: []string{"aws_instance", "baz"}, + Labels: []string{"aws_instance", "foo"}, Body: &hclext.BodyContent{ Attributes: hclext.Attributes{"instance_type": &hclext.Attribute{Name: "instance_type"}}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + }, }, }, }, diff --git a/plugin/stub-generator/sources/testing/main.go b/plugin/stub-generator/sources/testing/main.go index 275374e6f..8dcd78710 100644 --- a/plugin/stub-generator/sources/testing/main.go +++ b/plugin/stub-generator/sources/testing/main.go @@ -22,6 +22,8 @@ func main() { rules.NewAwsDBInstanceWithDefaultConfigExampleRule(), rules.NewAwsCloudFormationStackErrorRule(), rules.NewLocalsJustAttributesExampleRule(), + rules.NewAwsIAMRoleExampleRule(), + rules.NewTestingAssertionsExampleRule(), }, }, }) diff --git a/plugin/stub-generator/sources/testing/rules/aws_iam_role_example.go b/plugin/stub-generator/sources/testing/rules/aws_iam_role_example.go new file mode 100644 index 000000000..2f936da15 --- /dev/null +++ b/plugin/stub-generator/sources/testing/rules/aws_iam_role_example.go @@ -0,0 +1,87 @@ +package rules + +import ( + "fmt" + + "github.com/terraform-linters/tflint-plugin-sdk/hclext" + "github.com/terraform-linters/tflint-plugin-sdk/tflint" +) + +// AwsIAMRoleExampleRule checks whether ... +type AwsIAMRoleExampleRule struct { + tflint.DefaultRule +} + +// NewAwsIAMPolicyExampleRule returns a new rule +func NewAwsIAMRoleExampleRule() *AwsIAMRoleExampleRule { + return &AwsIAMRoleExampleRule{} +} + +// Name returns the rule name +func (r *AwsIAMRoleExampleRule) Name() string { + return "aws_iam_role_example" +} + +// Enabled returns whether the rule is enabled by default +func (r *AwsIAMRoleExampleRule) Enabled() bool { + return true +} + +// Severity returns the rule severity +func (r *AwsIAMRoleExampleRule) Severity() tflint.Severity { + return tflint.ERROR +} + +// Link returns the rule reference link +func (r *AwsIAMRoleExampleRule) Link() string { + return "" +} + +// Check checks whether ... +func (r *AwsIAMRoleExampleRule) Check(runner tflint.Runner) error { + resources, err := runner.GetResourceContent("aws_iam_role", &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "inline_policy", + Body: &hclext.BodySchema{ + Attributes: []hclext.AttributeSchema{{Name: "name"}}, + }, + }, + }, + }, &tflint.GetModuleContentOption{ + ModuleCtx: tflint.SelfModuleCtxType, + ExpandMode: tflint.ExpandModeNone, + }) + if err != nil { + return err + } + + for _, resource := range resources.Blocks { + for _, policy := range resource.Body.Blocks { + if err := runner.EmitIssue(r, "inline policy found", policy.DefRange); err != nil { + return err + } + + attribute, exists := policy.Body.Attributes["name"] + if !exists { + continue + } + + var name string + err := runner.EvaluateExpr(attribute.Expr, &name, nil) + + err = runner.EnsureNoError(err, func() error { + return runner.EmitIssue( + r, + fmt.Sprintf("name is %s", name), + attribute.Expr.Range(), + ) + }) + if err != nil { + return err + } + } + } + + return nil +} diff --git a/plugin/stub-generator/sources/testing/rules/aws_s3_bucket_example_lifecycle_rule.go b/plugin/stub-generator/sources/testing/rules/aws_s3_bucket_example_lifecycle_rule.go index e0133e109..ab5bb5a20 100644 --- a/plugin/stub-generator/sources/testing/rules/aws_s3_bucket_example_lifecycle_rule.go +++ b/plugin/stub-generator/sources/testing/rules/aws_s3_bucket_example_lifecycle_rule.go @@ -1,6 +1,8 @@ package rules import ( + "fmt" + "github.com/terraform-linters/tflint-plugin-sdk/hclext" "github.com/terraform-linters/tflint-plugin-sdk/tflint" ) @@ -46,7 +48,14 @@ func (r *AwsS3BucketExampleLifecycleRuleRule) Check(runner tflint.Runner) error {Name: "enabled"}, }, Blocks: []hclext.BlockSchema{ - {Type: "transition", Body: &hclext.BodySchema{}}, + { + Type: "transition", + Body: &hclext.BodySchema{ + Attributes: []hclext.AttributeSchema{ + {Name: "days"}, + }, + }, + }, }, }, }, @@ -63,7 +72,11 @@ func (r *AwsS3BucketExampleLifecycleRuleRule) Check(runner tflint.Runner) error } if attr, exists := lifecycle.Body.Attributes["enabled"]; exists { - if err := runner.EmitIssue(r, "`enabled` attribute found", attr.Expr.Range()); err != nil { + var enabled string + err := runner.EnsureNoError(runner.EvaluateExpr(attr.Expr, &enabled, nil), func() error { + return runner.EmitIssue(r, fmt.Sprintf("`enabled` attribute found: %s", enabled), attr.Expr.Range()) + }) + if err != nil { return err } } @@ -72,6 +85,16 @@ func (r *AwsS3BucketExampleLifecycleRuleRule) Check(runner tflint.Runner) error if err := runner.EmitIssue(r, "`transition` block found", transition.DefRange); err != nil { return err } + + if attr, exists := transition.Body.Attributes["days"]; exists { + var days int + err := runner.EnsureNoError(runner.EvaluateExpr(attr.Expr, &days, nil), func() error { + return runner.EmitIssue(r, fmt.Sprintf("`days` attribute found: %d", days), attr.Expr.Range()) + }) + if err != nil { + return err + } + } } } } diff --git a/plugin/stub-generator/sources/testing/rules/testing_assertions_example.go b/plugin/stub-generator/sources/testing/rules/testing_assertions_example.go new file mode 100644 index 000000000..9a000dc32 --- /dev/null +++ b/plugin/stub-generator/sources/testing/rules/testing_assertions_example.go @@ -0,0 +1,63 @@ +package rules + +import ( + "fmt" + + "github.com/terraform-linters/tflint-plugin-sdk/hclext" + "github.com/terraform-linters/tflint-plugin-sdk/tflint" +) + +// TestingAssertionsExampleRule checks whether ... +type TestingAssertionsExampleRule struct { + tflint.DefaultRule +} + +// NewTestingAssertionsExampleRule returns a new rule +func NewTestingAssertionsExampleRule() *TestingAssertionsExampleRule { + return &TestingAssertionsExampleRule{} +} + +// Name returns the rule name +func (r *TestingAssertionsExampleRule) Name() string { + return "testing_assertions_example" +} + +// Enabled returns whether the rule is enabled by default +func (r *TestingAssertionsExampleRule) Enabled() bool { + return true +} + +// Severity returns the rule severity +func (r *TestingAssertionsExampleRule) Severity() tflint.Severity { + return tflint.ERROR +} + +// Link returns the rule reference link +func (r *TestingAssertionsExampleRule) Link() string { + return "" +} + +// Check checks whether ... +func (r *TestingAssertionsExampleRule) Check(runner tflint.Runner) error { + resources, err := runner.GetResourceContent("testing_assertions", &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "equal", + LabelNames: []string{"name"}, + }, + }, + }, nil) + if err != nil { + return err + } + + for _, resource := range resources.Blocks { + for _, equal := range resource.Body.Blocks { + if err := runner.EmitIssue(r, fmt.Sprintf("equal block found: label=%s", equal.Labels[0]), equal.DefRange); err != nil { + return err + } + } + } + + return nil +} diff --git a/terraform/evaluator.go b/terraform/evaluator.go index 978baea50..9e1ed56a6 100644 --- a/terraform/evaluator.go +++ b/terraform/evaluator.go @@ -8,6 +8,7 @@ import ( "github.com/agext/levenshtein" "github.com/hashicorp/hcl/v2" + "github.com/terraform-linters/tflint-plugin-sdk/hclext" "github.com/terraform-linters/tflint/terraform/addrs" "github.com/terraform-linters/tflint/terraform/lang" "github.com/terraform-linters/tflint/terraform/lang/marks" @@ -80,115 +81,62 @@ type Evaluator struct { CallStack *CallStack } -func (e *Evaluator) EvaluateExpr(expr hcl.Expression, wantType cty.Type, keyData InstanceKeyEvalData) (cty.Value, hcl.Diagnostics) { - scope := &lang.Scope{ - Data: &evaluationData{ - Evaluator: e, - ModulePath: e.ModulePath, - InstanceKeyData: keyData, - }, +// EvaluateExpr takes the given HCL expression and evaluates it to produce a value. +func (e *Evaluator) EvaluateExpr(expr hcl.Expression, wantType cty.Type) (cty.Value, hcl.Diagnostics) { + if e == nil { + panic("evaluator must not be nil") } - return scope.EvalExpr(expr, wantType) + return e.scope().EvalExpr(expr, wantType) } -type InstanceKeyEvalData struct { - CountIndex cty.Value - EachKey, EachValue cty.Value +// ExpandBlock expands "dynamic" blocks and resources/modules with count/for_each. +// +// In the expanded body, the content can be retrieved with the HCL API without +// being aware of the differences in the dynamic block schema. Also, the number +// of blocks and attribute values will be the same as the expanded result. +func (e *Evaluator) ExpandBlock(body hcl.Body, schema *hclext.BodySchema) (hcl.Body, hcl.Diagnostics) { + if e == nil { + return body, nil + } + return e.scope().ExpandBlock(body, schema) } -var EvalDataForNoInstanceKey = InstanceKeyEvalData{} +func (e *Evaluator) scope() *lang.Scope { + return &lang.Scope{ + Data: &evaluationData{ + Evaluator: e, + ModulePath: e.ModulePath, + }, + } +} type evaluationData struct { - Evaluator *Evaluator - ModulePath addrs.ModuleInstance - InstanceKeyData InstanceKeyEvalData + Evaluator *Evaluator + ModulePath addrs.ModuleInstance } var _ lang.Data = (*evaluationData)(nil) func (d *evaluationData) GetCountAttr(addr addrs.CountAttr, rng hcl.Range) (cty.Value, hcl.Diagnostics) { - var diags hcl.Diagnostics - - // Even when evaluating an expression that already has the value of `count.*` bound to it, - // it still tries to create an EvalContext because it contains `count.*` as a reference. - // In that case it returns an unknown value without returning an error. - if d.InstanceKeyData == EvalDataForNoInstanceKey { - return cty.UnknownVal(cty.Number), diags - } - - switch addr.Name { - - case "index": - idxVal := d.InstanceKeyData.CountIndex - if idxVal == cty.NilVal { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to "count" in non-counted context`, - Detail: `The "count" object can only be used in "module", "resource", and "data" blocks, and only when the "count" argument is set.`, - Subject: rng.Ptr(), - }) - return cty.UnknownVal(cty.Number), diags - } - return idxVal, diags - - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "count" attribute`, - Detail: fmt.Sprintf(`The "count" object does not have an attribute named %q. The only supported attribute is count.index, which is the index of each instance of a resource block that has the "count" argument set.`, addr.Name), - Subject: rng.Ptr(), - }) - return cty.DynamicVal, diags - } + // Note that the actual evaluation of count.index is not done here. + // count.index is already evaluated when expanded by ExpandBlock, + // and the value is bound to the expanded body. + // + // Although, there are cases where count.index is evaluated as-is, + // such as when not expanding the body. In that case, evaluate it + // as an unknown and skip further checks. + return cty.UnknownVal(cty.Number), nil } func (d *evaluationData) GetForEachAttr(addr addrs.ForEachAttr, rng hcl.Range) (cty.Value, hcl.Diagnostics) { - var diags hcl.Diagnostics - - // Even when evaluating an expression that already has the value of `each.*` bound to it, - // it still tries to create an EvalContext because it contains `each.*` as a reference. - // In that case it returns an unknown value without returning an error. - if d.InstanceKeyData == EvalDataForNoInstanceKey { - return cty.UnknownVal(cty.DynamicPseudoType), diags - } - - var returnVal cty.Value - switch addr.Name { - - case "key": - returnVal = d.InstanceKeyData.EachKey - case "value": - returnVal = d.InstanceKeyData.EachValue - - if returnVal == cty.NilVal { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `each.value cannot be used in this context`, - Detail: `A reference to "each.value" has been used in a context in which it unavailable, such as when the configuration no longer contains the value in its "for_each" expression. Remove this reference to each.value in your configuration to work around this error.`, - Subject: rng.Ptr(), - }) - return cty.UnknownVal(cty.DynamicPseudoType), diags - } - default: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Invalid "each" attribute`, - Detail: fmt.Sprintf(`The "each" object does not have an attribute named %q. The supported attributes are each.key and each.value, the current key and value pair of the "for_each" attribute set.`, addr.Name), - Subject: rng.Ptr(), - }) - return cty.DynamicVal, diags - } - - if returnVal == cty.NilVal { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `Reference to "each" in context without for_each`, - Detail: `The "each" object can be used only in "module" or "resource" blocks, and only when the "for_each" argument is set.`, - Subject: rng.Ptr(), - }) - return cty.UnknownVal(cty.DynamicPseudoType), diags - } - return returnVal, diags + // Note that the actual evaluation of each.key/each.value is not done here. + // each.key/each.value is already evaluated when expanded by ExpandBlock, + // and the value is bound to the expanded body. + // + // Although, there are cases where each.key/each.value is evaluated as-is, + // such as when not expanding the body. In that case, evaluate it + // as an unknown and skip further checks. + return cty.DynamicVal, nil } func (d *evaluationData) GetInputVariable(addr addrs.InputVariable, rng hcl.Range) (cty.Value, hcl.Diagnostics) { @@ -313,9 +261,7 @@ func (d *evaluationData) GetLocalValue(addr addrs.LocalValue, rng hcl.Range) (ct return cty.UnknownVal(cty.DynamicPseudoType), diags } - // Always use EvalDataForNoInstanceKey because local values cannot use expressions - // that depend on instance keys, such as `count.*` and `each.*`. - val, diags := d.Evaluator.EvaluateExpr(config.Expr, cty.DynamicPseudoType, EvalDataForNoInstanceKey) + val, diags := d.Evaluator.EvaluateExpr(config.Expr, cty.DynamicPseudoType) d.Evaluator.CallStack.Pop() return val, diags diff --git a/terraform/evaluator_test.go b/terraform/evaluator_test.go index b27f9a8bc..dcbc25f4c 100644 --- a/terraform/evaluator_test.go +++ b/terraform/evaluator_test.go @@ -6,11 +6,14 @@ import ( "path/filepath" "testing" + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" "github.com/hashicorp/go-version" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/hclsyntax" "github.com/spf13/afero" "github.com/terraform-linters/tflint-plugin-sdk/hclext" + "github.com/terraform-linters/tflint/terraform/lang/marks" "github.com/zclconf/go-cty/cty" ) @@ -38,7 +41,6 @@ func TestEvaluateExpr(t *testing.T) { inputs []InputValues expr hcl.Expression ty cty.Type - keyData InstanceKeyEvalData want string errCheck func(hcl.Diagnostics) bool }{ @@ -701,14 +703,6 @@ locals { want: `cty.UnknownVal(cty.Number)`, errCheck: neverHappend, }, - { - name: "count.index in counted context", - expr: expr(`count.index`), - ty: cty.Number, - keyData: InstanceKeyEvalData{CountIndex: cty.NumberIntVal(1)}, - want: `cty.NumberIntVal(1)`, - errCheck: neverHappend, - }, { name: "each.key in non-forEach context", expr: expr(`each.key`), @@ -716,14 +710,6 @@ locals { want: `cty.UnknownVal(cty.String)`, errCheck: neverHappend, }, - { - name: "each.key in forEach context", - expr: expr(`each.key`), - ty: cty.String, - keyData: InstanceKeyEvalData{EachKey: cty.StringVal("foo"), EachValue: cty.StringVal("bar")}, - want: `cty.StringVal("foo")`, - errCheck: neverHappend, - }, { name: "each.value in non-forEach context", expr: expr(`each.value`), @@ -732,15 +718,7 @@ locals { errCheck: neverHappend, }, { - name: "each.value in forEach context", - expr: expr(`each.value`), - ty: cty.String, - keyData: InstanceKeyEvalData{EachKey: cty.StringVal("foo"), EachValue: cty.StringVal("bar")}, - want: `cty.StringVal("bar")`, - errCheck: neverHappend, - }, - { - name: "bound expr without key data", + name: "bound expr", expr: hclext.BindValue(cty.StringVal("foo"), expr(`each.value`)), ty: cty.String, want: `cty.StringVal("foo")`, @@ -777,7 +755,7 @@ locals { CallStack: NewCallStack(), } - got, diags := evaluator.EvaluateExpr(test.expr, test.ty, test.keyData) + got, diags := evaluator.EvaluateExpr(test.expr, test.ty) if test.errCheck(diags) { t.Fatal(diags) } @@ -788,3 +766,1323 @@ locals { }) } } + +func TestExpandBlock(t *testing.T) { + tests := []struct { + name string + config string + schema *hclext.BodySchema + want *hclext.BodyContent + }{ + { + name: "no meta-arguments", + config: ` +resource "aws_instance" "main" {} +`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + {Type: "resource", Labels: []string{"aws_instance", "main"}, Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}}, + }, + }, + }, + { + name: "count is not zero (literal)", + config: ` +resource "aws_instance" "main" { + count = 1 + value = count.index +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(0), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + name: "count is not zero (variable)", + config: ` +variable "count" { + default = 1 +} +resource "aws_instance" "main" { + count = var.count + value = count.index +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(0), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + name: "count is greater than 1", + config: ` +resource "aws_instance" "main" { + count = 2 + value = count.index +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(0), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(1), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + name: "count is unknown", + config: ` +variable "count" {} + +resource "aws_instance" "main" { + count = var.count +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, + }, + }, + want: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + { + name: "count is sensitive", + config: ` +variable "count" { + sensitive = true + default = 1 +} +resource "aws_instance" "main" { + count = var.count +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + {Type: "resource", Labels: []string{"aws_instance", "main"}, Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}}, + }, + }, + }, + { + name: "count is unevaluable", + config: ` +resource "aws_instance" "main" { + count = module.meta.count +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, + }, + }, + want: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + { + name: "count is zero", + config: ` +resource "aws_instance" "main" { + count = 0 +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, + }, + }, + want: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + { + name: "count is string", + config: ` +resource "aws_instance" "main" { + count = "1" +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + {Type: "resource", Labels: []string{"aws_instance", "main"}, Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}}, + }, + }, + }, + { + name: "count.index and sensitive value", + config: ` +variable "sensitive" { + sensitive = true + default = "foo" +} +resource "aws_instance" "main" { + count = 1 + value = "${count.index}-${var.sensitive}" +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.UnknownVal(cty.String).Mark(marks.Sensitive), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + name: "count.index and nested sensitive value", + config: ` +variable "sensitive" { + sensitive = true + default = "foo" +} +resource "aws_instance" "main" { + count = 1 + value = [count.index, var.sensitive] +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.UnknownVal(cty.Number), cty.StringVal("foo").Mark(marks.Sensitive)}), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + name: "for_each is not empty (literal)", + config: ` +resource "aws_instance" "main" { + for_each = { foo = "bar" } + value = "${each.key}-${each.value}" +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + name: "for_each is not empty (variable)", + config: ` +variable "for_each" { + default = { foo = "bar" } +} +resource "aws_instance" "main" { + for_each = var.for_each + value = "${each.key}-${each.value}" +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + name: "for_each is unknown", + config: ` +variable "for_each" {} + +resource "aws_instance" "main" { + for_each = var.for_each +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, + }, + }, + want: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + { + name: "for_each is evaluable", + config: ` +resource "aws_instance" "main" { + for_each = module.meta.for_each +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, + }, + }, + want: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + { + name: "for_each contains unevaluable", + config: ` +resource "aws_instance" "main" { + for_each = { + known = "known" + unknown = module.meta.unknown + } + value = [each.key, each.value] +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{ + "value": { + Name: "value", + Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.StringVal("known"), cty.StringVal("known")}), hcl.Range{}), + }, + }, + Blocks: hclext.Blocks{}, + }, + }, + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{ + "value": { + Name: "value", + Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.StringVal("unknown"), cty.DynamicVal}), hcl.Range{}), + }, + }, + Blocks: hclext.Blocks{}, + }, + }, + }, + }, + }, + { + name: "for_each is empty", + config: ` +resource "aws_instance" "main" { + for_each = {} +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, + }, + }, + want: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + { + name: "for_each is not empty set", + config: ` +resource "aws_instance" "main" { + for_each = toset(["foo", "bar"]) + value = each.key +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + name: "for_each is empty set", + config: ` +resource "aws_instance" "main" { + for_each = toset([]) +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, + }, + }, + want: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}, + }, + { + name: "each.key/each.value and sensitive value", + config: ` +variable "sensitive" { + sensitive = true + default = "foo" +} +resource "aws_instance" "main" { + for_each = { foo = "bar" } + value = "${each.key}-${each.value}-${var.sensitive}" +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.UnknownVal(cty.String).Mark(marks.Sensitive), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + name: "each.key/each.value and nested sensitive value", + config: ` +variable "sensitive" { + sensitive = true + default = "foo" +} +resource "aws_instance" "main" { + for_each = { foo = "bar" } + value = [each.key, var.sensitive] +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.DynamicVal, cty.StringVal("foo").Mark(marks.Sensitive)}), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + name: "non-empty object dynamic blocks", + config: ` +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = { + foo = "bar" + baz = "qux" + } + content { + value = "${ebs_block_device.key}-${ebs_block_device.value}" + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("baz-qux"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + }, + }, + }, + { + name: "non-empty object variable dynamic blocks", + config: ` +variable "for_each" { + default = { + foo = "bar" + baz = "qux" + } +} +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = var.for_each + content { + value = "${ebs_block_device.key}-${ebs_block_device.value}" + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("baz-qux"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + }, + }, + }, + { + name: "unknown variable dynamic blocks", + config: ` +variable "for_each" {} + +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = var.for_each + content { + value = "${ebs_block_device.key}-${ebs_block_device.value}" + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{}, + }, + }, + }, + }, + }, + { + name: "unevaluable variable dynamic blocks", + config: ` +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = module.meta.for_each + content { + value = "${ebs_block_device.key}-${ebs_block_device.value}" + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{}, + }, + }, + }, + }, + }, + { + name: "object contains unevaluable dynamic blocks", + config: ` +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = { + known = "known" + unknown = module.meta.unknown + } + content { + value = "${ebs_block_device.key}-${ebs_block_device.value}" + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("known-known"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.UnknownVal(cty.String), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + }, + }, + }, + { + name: "empty object dynamic blocks", + config: ` +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = {} + content { + value = "${ebs_block_device.key}-${ebs_block_device.value}" + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{}, + }, + }, + }, + }, + }, + { + name: "non-empty set dynamic blocks", + config: ` +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = toset(["foo", "bar"]) + content { + value = "${ebs_block_device.key}-${ebs_block_device.value}" + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("bar-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-foo"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + }, + }, + }, + { + name: "empty set dynamic blocks", + config: ` +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = toset([]) + content { + value = "${ebs_block_device.key}-${ebs_block_device.value}" + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{}, + }, + }, + }, + }, + }, + { + name: "iterator with sensitive value", + config: ` +variable "sensitive" { + sensitive = true + default = "foo" +} +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = { foo = "bar" } + content { + value = "${ebs_block_device.key}-${ebs_block_device.value}-${var.sensitive}" + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.UnknownVal(cty.String).Mark(marks.Sensitive), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + }, + }, + }, + { + name: "iterator with nested sensitive value", + config: ` +variable "sensitive" { + sensitive = true + default = "foo" +} +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = { foo = "bar" } + content { + value = [ebs_block_device.key, var.sensitive] + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.DynamicVal, cty.StringVal("foo").Mark(marks.Sensitive)}), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + }, + }, + }, + { + name: "nested dynamic blocks", + config: ` +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = toset(["foo", "bar"]) + content { + dynamic "nested" { + for_each = toset(["baz", "qux"]) + content { + value = "${ebs_block_device.key}-${nested.value}" + } + } + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "nested", + Body: &hclext.BodySchema{ + Attributes: []hclext.AttributeSchema{{Name: "value"}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "nested", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("bar-baz"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + { + Type: "nested", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("bar-qux"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "nested", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-baz"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + { + Type: "nested", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-qux"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + { + name: "custom iterator", + config: ` +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = { foo = "bar" } + iterator = it + content { + value = "${it.key}-${it.value}" + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + }, + }, + }, + { + name: "dynamic labels", + config: ` +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = { foo = "bar" } + labels = [ebs_block_device.key] + content { + value = ebs_block_device.value + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + LabelNames: []string{"name"}, + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Labels: []string{"foo"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + }, + }, + }, + { + // Terraform does not allow variables to be used in dynamic labels. + // @see https://github.com/hashicorp/terraform/issues/32180 + name: "dynamic labels with variable", + config: ` +variable "label" { + default = "baz" +} +resource "aws_instance" "main" { + dynamic "ebs_block_device" { + for_each = { foo = "bar" } + labels = [var.label] + content { + value = ebs_block_device.value + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + LabelNames: []string{"name"}, + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Labels: []string{"baz"}, + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + }, + }, + }, + { + name: "meta-aruguments and dynamic blocks", + config: ` +resource "aws_instance" "main" { + count = 2 + + dynamic "ebs_block_device" { + for_each = toset(["foo", "bar"]) + content { + value = "${count.index}-${ebs_block_device.value}" + } + } +}`, + schema: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "resource", + LabelNames: []string{"type", "name"}, + Body: &hclext.BodySchema{ + Blocks: []hclext.BlockSchema{ + { + Type: "ebs_block_device", + Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}, + }, + }, + }, + }, + }, + }, + want: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("0-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("0-foo"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + { + Type: "resource", + Labels: []string{"aws_instance", "main"}, + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{}, + Blocks: hclext.Blocks{ + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("1-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("1-foo"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + }, + }, + }, + }, + }, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + fs := afero.Afero{Fs: afero.NewMemMapFs()} + if err := fs.WriteFile("main.tf", []byte(test.config), os.ModePerm); err != nil { + t.Fatal(err) + } + file, diags := hclsyntax.ParseConfig([]byte(test.config), "main.tf", hcl.InitialPos) + if diags.HasErrors() { + t.Fatal(diags) + } + + parser := NewParser(fs) + mod, diags := parser.LoadConfigDir(".") + if diags.HasErrors() { + t.Fatal(diags) + } + config, diags := BuildConfig(mod, ModuleWalkerFunc(func(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics) { return nil, nil, nil })) + if diags.HasErrors() { + t.Fatal(diags) + } + variableValues, diags := VariableValues(config) + if diags.HasErrors() { + t.Fatal(diags) + } + + evaluator := &Evaluator{ + Meta: &ContextMeta{Env: Workspace()}, + ModulePath: config.Path.UnkeyedInstanceShim(), + Config: config, + VariableValues: variableValues, + CallStack: NewCallStack(), + } + + expanded, diags := evaluator.ExpandBlock(file.Body, test.schema) + if diags.HasErrors() { + t.Fatal(diags) + } + got, diags := hclext.PartialContent(expanded, test.schema) + if diags.HasErrors() { + t.Fatal(diags) + } + + opts := cmp.Options{ + cmpopts.IgnoreFields(hclext.Block{}, "TypeRange", "LabelRanges"), + cmpopts.IgnoreFields(hclext.Attribute{}, "NameRange"), + cmpopts.IgnoreFields(hcl.Range{}, "Start", "End", "Filename"), + cmp.Comparer(func(x, y hcl.Expression) bool { + xv, diags := evaluator.EvaluateExpr(x, cty.DynamicPseudoType) + if diags.HasErrors() { + t.Fatal(diags) + } + yv, diags := evaluator.EvaluateExpr(y, cty.DynamicPseudoType) + if diags.HasErrors() { + t.Fatal(diags) + } + return xv.RawEquals(yv) + }), + } + if diff := cmp.Diff(got, test.want, opts); diff != "" { + t.Error(diff) + } + }) + } +} diff --git a/terraform/expandable.go b/terraform/expandable.go deleted file mode 100644 index ad6ad68e8..000000000 --- a/terraform/expandable.go +++ /dev/null @@ -1,208 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/terraform-linters/tflint-plugin-sdk/hclext" - "github.com/terraform-linters/tflint/terraform/addrs" - "github.com/terraform-linters/tflint/terraform/lang" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/gocty" -) - -type expandable struct { - Count hcl.Expression - ForEach hcl.Expression -} - -// expandBlock returns multiple blocks based on the meta-arguments (count/for_each). -// -// This function returns no blocks if `count` is 0, if `for_each` is empty, or if they are unknown. -// Otherwise it returns the number of blocks according to the value. -// -// Expressions containing `count.*` or `each.*` are evaluated here when expanding blocks. -// Make an instance key and bind the evaluation result based on it to the expression. -// Note that sensitive values are not bound. This is a limitation in value decoding. -// This means that `count.*`, `each.*` with sensitive values will resolve to unknown values. -func (e *expandable) expandBlock(ctx *Evaluator, block *hclext.Block) (hclext.Blocks, hcl.Diagnostics) { - if e.Count != nil { - return e.expandBlockByCount(ctx, block) - } - - if e.ForEach != nil { - return e.expandBlockByForEach(ctx, block) - } - - return hclext.Blocks{block}, hcl.Diagnostics{} -} - -func (e *expandable) expandBlockByCount(ctx *Evaluator, block *hclext.Block) (hclext.Blocks, hcl.Diagnostics) { - var diags hcl.Diagnostics - - countVal, countDiags := ctx.EvaluateExpr(e.Count, cty.Number, EvalDataForNoInstanceKey) - diags = diags.Extend(countDiags) - if diags.HasErrors() { - return hclext.Blocks{}, diags - } - countVal, _ = countVal.Unmark() - - if countVal.IsNull() { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The given "count" argument value is null. An integer is required.`, - Subject: e.Count.Range().Ptr(), - }) - return hclext.Blocks{}, diags - } - if !countVal.IsKnown() { - // If count is unknown, no blocks are returned - return hclext.Blocks{}, diags - } - - var count int - err := gocty.FromCtyValue(countVal, &count) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: fmt.Sprintf(`The given "count" argument value is unsuitable: %s.`, err), - Subject: e.Count.Range().Ptr(), - }) - return hclext.Blocks{}, diags - } - if count < 0 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid count argument", - Detail: `The given "count" argument value is unsuitable: negative numbers are not supported.`, - Subject: e.Count.Range().Ptr(), - }) - return hclext.Blocks{}, diags - } - - blocks := make(hclext.Blocks, count) - for i := 0; i < count; i++ { - expanded := block.Copy() - keyData := InstanceKeyEvalData{CountIndex: cty.NumberIntVal(int64(i))} - - walkDiags := expanded.Body.WalkAttributes(func(attr *hclext.Attribute) hcl.Diagnostics { - var diags hcl.Diagnostics - - refs, refsDiags := lang.ReferencesInExpr(attr.Expr) - if refsDiags.HasErrors() { - diags = diags.Extend(refsDiags) - return diags - } - - var contain bool - for _, ref := range refs { - if _, ok := ref.Subject.(addrs.CountAttr); ok { - contain = true - } - } - - if contain { - val, evalDiags := ctx.EvaluateExpr(attr.Expr, cty.DynamicPseudoType, keyData) - if evalDiags.HasErrors() { - diags = diags.Extend(evalDiags) - return diags - } - // If marked as sensitive, the cty.Value cannot be marshaled in MessagePack, - // so only bind it if it is unmarked. - if !val.ContainsMarked() { - // Even if there is no instance key later, the evaluated result is bound to - // the expression so that it can be referenced by EvaluateExpr. - attr.Expr = hclext.BindValue(val, attr.Expr) - } - } - return diags - }) - - diags = diags.Extend(walkDiags) - blocks[i] = expanded - } - - return blocks, diags -} - -func (e *expandable) expandBlockByForEach(ctx *Evaluator, block *hclext.Block) (hclext.Blocks, hcl.Diagnostics) { - var diags hcl.Diagnostics - - forEach, forEachDiags := ctx.EvaluateExpr(e.ForEach, cty.DynamicPseudoType, EvalDataForNoInstanceKey) - diags = diags.Extend(forEachDiags) - if diags.HasErrors() { - return hclext.Blocks{}, diags - } - - if forEach.IsNull() { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid for_each argument", - Detail: `The given "for_each" argument value is unsuitable: the given "for_each" argument value is null. A map, or set of strings is allowed.`, - Subject: e.ForEach.Range().Ptr(), - }) - return hclext.Blocks{}, diags - } - if !forEach.IsKnown() { - // If for_each is unknown, no blocks are returned - return hclext.Blocks{}, diags - } - if !forEach.CanIterateElements() { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "The `for_each` value is not iterable", - Detail: fmt.Sprintf("`%s` is not iterable", forEach.GoString()), - Subject: e.ForEach.Range().Ptr(), - }) - return hclext.Blocks{}, diags - } - - blocks := make(hclext.Blocks, forEach.LengthInt()) - it := forEach.ElementIterator() - for i := 0; it.Next(); i++ { - expanded := block.Copy() - - key, value := it.Element() - keyData := InstanceKeyEvalData{EachKey: key, EachValue: value} - - walkDiags := expanded.Body.WalkAttributes(func(attr *hclext.Attribute) hcl.Diagnostics { - var diags hcl.Diagnostics - - refs, refsDiags := lang.ReferencesInExpr(attr.Expr) - if refsDiags.HasErrors() { - diags = diags.Extend(refsDiags) - return diags - } - - var contain bool - for _, ref := range refs { - if _, ok := ref.Subject.(addrs.ForEachAttr); ok { - contain = true - } - } - - if contain { - val, evalDiags := ctx.EvaluateExpr(attr.Expr, cty.DynamicPseudoType, keyData) - if evalDiags.HasErrors() { - diags = diags.Extend(evalDiags) - return diags - } - // If marked as sensitive, the cty.Value cannot be marshaled in MessagePack, - // so only bind it if it is unmarked. - if !val.ContainsMarked() { - // Even if there is no instance key later, the evaluated result is bound to - // the expression so that it can be referenced by EvaluateExpr. - attr.Expr = hclext.BindValue(val, attr.Expr) - } - } - return diags - }) - - diags = diags.Extend(walkDiags) - blocks[i] = expanded - } - - return blocks, diags -} diff --git a/terraform/lang/eval.go b/terraform/lang/eval.go index 20cfbfcea..44a0ad982 100644 --- a/terraform/lang/eval.go +++ b/terraform/lang/eval.go @@ -4,12 +4,30 @@ import ( "fmt" "github.com/hashicorp/hcl/v2" + "github.com/terraform-linters/tflint-plugin-sdk/hclext" "github.com/terraform-linters/tflint/terraform/addrs" "github.com/terraform-linters/tflint/terraform/tfdiags" + "github.com/terraform-linters/tflint/terraform/tfhcl" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/convert" ) +// ExpandBlock expands "dynamic" blocks and resources/modules with count/for_each. +// Note that Terraform only expands dynamic blocks, but TFLint also expands +// count/for_each here. +// +// Expressions in expanded blocks are evaluated immediately, so all variables +// contained in attributes specified in the body schema are gathered. +func (s *Scope) ExpandBlock(body hcl.Body, schema *hclext.BodySchema) (hcl.Body, hcl.Diagnostics) { + traversals := tfhcl.ExpandVariablesHCLExt(body, schema) + refs, diags := References(traversals) + + ctx, ctxDiags := s.EvalContext(refs) + diags = diags.Extend(ctxDiags) + + return tfhcl.Expand(body, ctx), diags +} + // EvalExpr evaluates a single expression in the receiving context and returns // the resulting value. The value will be converted to the given type before // it is returned if possible, or else an error diagnostic will be produced diff --git a/terraform/module.go b/terraform/module.go index 9f0660b3e..1c197d1f8 100644 --- a/terraform/module.go +++ b/terraform/module.go @@ -77,23 +77,23 @@ func (m *Module) build() hcl.Diagnostics { // Basically, this function is a wrapper for hclext.PartialContent, but in some ways it reproduces // Terraform language semantics. // -// 1. The block schema implicitly adds dynamic blocks to the target -// https://www.terraform.io/language/expressions/dynamic-blocks -// 2. Supports overriding files -// https://www.terraform.io/language/files/override +// 1. Supports overriding files +// https://developer.hashicorp.com/terraform/language/files/override +// 2. Expands "dynamic" blocks +// https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks // 3. Expands resource/module depends on the meta-arguments -// https://www.terraform.io/language/meta-arguments/count -// https://www.terraform.io/language/meta-arguments/for_each +// https://developer.hashicorp.com/terraform/language/meta-arguments/count +// https://developer.hashicorp.com/terraform/language/meta-arguments/for_each // -// But 3 won't run if you didn't pass the evaluation context. +// But 2 and 3 won't run if you didn't pass the evaluation context. func (m *Module) PartialContent(schema *hclext.BodySchema, ctx *Evaluator) (*hclext.BodyContent, hcl.Diagnostics) { content := &hclext.BodyContent{} diags := hcl.Diagnostics{} - schema = schemaWithDynamic(schema) - for _, f := range m.primaries { - c, d := hclext.PartialContent(f.Body, schema) + expanded, d := ctx.ExpandBlock(f.Body, schema) + diags = diags.Extend(d) + c, d := hclext.PartialContent(expanded, schema) diags = diags.Extend(d) for name, attr := range c.Attributes { content.Attributes[name] = attr @@ -101,7 +101,9 @@ func (m *Module) PartialContent(schema *hclext.BodySchema, ctx *Evaluator) (*hcl content.Blocks = append(content.Blocks, c.Blocks...) } for _, f := range m.overrides { - c, d := hclext.PartialContent(f.Body, schema) + expanded, d := ctx.ExpandBlock(f.Body, schema) + diags = diags.Extend(d) + c, d := hclext.PartialContent(expanded, schema) diags = diags.Extend(d) for name, attr := range c.Attributes { content.Attributes[name] = attr @@ -109,48 +111,9 @@ func (m *Module) PartialContent(schema *hclext.BodySchema, ctx *Evaluator) (*hcl content.Blocks = overrideBlocks(content.Blocks, c.Blocks) } - content = resolveDynamicBlocks(content) - - if ctx == nil { - return content, diags - } - - content, expandDiags := m.expandBlocks(content, ctx) - diags = diags.Extend(expandDiags) - return content, diags } -// expandBlocks expands resource/module blocks depending on evaluation context. -func (m *Module) expandBlocks(content *hclext.BodyContent, ctx *Evaluator) (*hclext.BodyContent, hcl.Diagnostics) { - out := &hclext.BodyContent{Attributes: content.Attributes} - diags := hcl.Diagnostics{} - - for _, block := range content.Blocks { - switch block.Type { - case "resource": - resourceType := block.Labels[0] - resourceName := block.Labels[1] - - resource := m.Resources[resourceType][resourceName] - blocks, expandDiags := resource.expandBlock(ctx, block) - diags = diags.Extend(expandDiags) - out.Blocks = append(out.Blocks, blocks...) - case "module": - name := block.Labels[0] - - module := m.ModuleCalls[name] - blocks, expandDiags := module.expandBlock(ctx, block) - diags = diags.Extend(expandDiags) - out.Blocks = append(out.Blocks, blocks...) - default: - out.Blocks = append(out.Blocks, block) - } - } - - return out, diags -} - // overrideBlocks changes the attributes in the passed primary blocks by override blocks recursively. func overrideBlocks(primaries, overrides hclext.Blocks) hclext.Blocks { dict := map[string]*hclext.Block{} @@ -172,58 +135,11 @@ func overrideBlocks(primaries, overrides hclext.Blocks) hclext.Blocks { return primaries } -// schemaWithDynamic appends a dynamic block schema to block schemes recursively. -// The content retrieved by the added schema is formatted by resolveDynamicBlocks in the same way as regular blocks. -func schemaWithDynamic(schema *hclext.BodySchema) *hclext.BodySchema { - out := &hclext.BodySchema{Mode: schema.Mode, Attributes: schema.Attributes} - - for _, block := range schema.Blocks { - block.Body = schemaWithDynamic(block.Body) - - out.Blocks = append(out.Blocks, block, hclext.BlockSchema{ - Type: "dynamic", - LabelNames: []string{"type"}, - Body: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - { - Type: "content", - Body: block.Body, - }, - }, - }, - }) - } - - return out -} - -// resolveDynamicBlocks formats the passed content based on the block schema added by schemaWithDynamic. -// This allows you to get all named blocks without being aware of the difference in the structure of the dynamic block. -func resolveDynamicBlocks(content *hclext.BodyContent) *hclext.BodyContent { - out := &hclext.BodyContent{Attributes: content.Attributes} - - for _, block := range content.Blocks { - block.Body = resolveDynamicBlocks(block.Body) - - if block.Type != "dynamic" { - out.Blocks = append(out.Blocks, block) - } else { - for _, dynamicContent := range block.Body.Blocks { - dynamicContent.Type = block.Labels[0] - out.Blocks = append(out.Blocks, dynamicContent) - } - } - } - - return out -} - var moduleSchema = &hclext.BodySchema{ Blocks: []hclext.BlockSchema{ { Type: "resource", LabelNames: []string{"type", "name"}, - Body: resourceBlockSchema, }, { Type: "variable", diff --git a/terraform/module_call.go b/terraform/module_call.go index 4e6d336b5..290254d5e 100644 --- a/terraform/module_call.go +++ b/terraform/module_call.go @@ -10,8 +10,6 @@ type ModuleCall struct { Name string SourceAddrRaw string - expandable - DeclRange hcl.Range } @@ -28,14 +26,6 @@ func decodeModuleBlock(block *hclext.Block) (*ModuleCall, hcl.Diagnostics) { diags = diags.Extend(valDiags) } - if attr, exists := block.Body.Attributes["count"]; exists { - mc.Count = attr.Expr - } - - if attr, exists := block.Body.Attributes["for_each"]; exists { - mc.ForEach = attr.Expr - } - return mc, diags } @@ -44,11 +34,5 @@ var moduleBlockSchema = &hclext.BodySchema{ { Name: "source", }, - { - Name: "count", - }, - { - Name: "for_each", - }, }, } diff --git a/terraform/module_test.go b/terraform/module_test.go index 59b03da56..263b29578 100644 --- a/terraform/module_test.go +++ b/terraform/module_test.go @@ -10,8 +10,6 @@ import ( "github.com/hashicorp/hcl/v2" "github.com/spf13/afero" "github.com/terraform-linters/tflint-plugin-sdk/hclext" - "github.com/terraform-linters/tflint/terraform/lang/marks" - "github.com/zclconf/go-cty/cty" ) func TestPartialContent(t *testing.T) { @@ -65,6 +63,7 @@ resource "aws_instance" "bar" { Labels: []string{"aws_instance", "foo"}, Body: &hclext.BodyContent{ Attributes: hclext.Attributes{"instance_type": &hclext.Attribute{Name: "instance_type", Range: hcl.Range{Filename: "main1.tf"}}}, + Blocks: hclext.Blocks{}, }, DefRange: hcl.Range{Filename: "main1.tf"}, }, @@ -73,6 +72,7 @@ resource "aws_instance" "bar" { Labels: []string{"aws_instance", "bar"}, Body: &hclext.BodyContent{ Attributes: hclext.Attributes{"instance_type": &hclext.Attribute{Name: "instance_type", Range: hcl.Range{Filename: "main2.tf"}}}, + Blocks: hclext.Blocks{}, }, DefRange: hcl.Range{Filename: "main2.tf"}, }, @@ -108,6 +108,7 @@ resource "aws_instance" "foo" { Labels: []string{"aws_instance", "foo"}, Body: &hclext.BodyContent{ Attributes: hclext.Attributes{"instance_type": &hclext.Attribute{Name: "instance_type", Range: hcl.Range{Filename: "main_override.tf"}}}, + Blocks: hclext.Blocks{}, }, DefRange: hcl.Range{Filename: "main.tf"}, }, @@ -140,6 +141,7 @@ locals { "foo": &hclext.Attribute{Name: "foo", Range: hcl.Range{Filename: "main.tf"}}, "bar": &hclext.Attribute{Name: "bar", Range: hcl.Range{Filename: "main.tf"}}, }, + Blocks: hclext.Blocks{}, }, DefRange: hcl.Range{Filename: "main.tf"}, }, @@ -286,6 +288,7 @@ resource "aws_instance" "bar" { Type: "ebs_block_device", Body: &hclext.BodyContent{ Attributes: hclext.Attributes{"volume_size": &hclext.Attribute{Name: "volume_size", Range: hcl.Range{Filename: "main.tf"}}}, + Blocks: hclext.Blocks{}, }, DefRange: hcl.Range{Filename: "main.tf"}, }, @@ -303,6 +306,15 @@ resource "aws_instance" "bar" { Type: "ebs_block_device", Body: &hclext.BodyContent{ Attributes: hclext.Attributes{"volume_size": &hclext.Attribute{Name: "volume_size", Range: hcl.Range{Filename: "main.tf"}}}, + Blocks: hclext.Blocks{}, + }, + DefRange: hcl.Range{Filename: "main.tf"}, + }, + { + Type: "ebs_block_device", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{"volume_size": &hclext.Attribute{Name: "volume_size", Range: hcl.Range{Filename: "main.tf"}}}, + Blocks: hclext.Blocks{}, }, DefRange: hcl.Range{Filename: "main.tf"}, }, @@ -365,865 +377,129 @@ resource "aws_instance" "bar" { } } -func Test_expandBlocks(t *testing.T) { +func Test_overrideBlocks(t *testing.T) { tests := []struct { - name string - config string - schema *hclext.BodySchema - want *hclext.BodyContent + Name string + Primaries hclext.Blocks + Overrides hclext.Blocks + Want hclext.Blocks }{ { - name: "no meta-arguments", - config: ` -resource "aws_instance" "main" {} - -module "aws_instance" {} -`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - {Type: "resource", Labels: []string{"aws_instance", "main"}, Body: &hclext.BodyContent{Attributes: hclext.Attributes{}}}, - {Type: "module", Labels: []string{"aws_instance"}, Body: &hclext.BodyContent{Attributes: hclext.Attributes{}}}, - }, - }, + Name: "empty blocks", + Primaries: hclext.Blocks{}, + Overrides: hclext.Blocks{}, + Want: hclext.Blocks{}, }, { - name: "count is not zero (literal)", - config: ` -resource "aws_instance" "main" { - count = 1 - value = count.index -} -module "aws_instance" { - count = 1 - value = count.index -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(0), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(0), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + Name: "no override", + Primaries: hclext.Blocks{ + { + Type: "resource", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, }, }, }, - }, - { - name: "count is not zero (variable)", - config: ` -variable "count" { - default = 1 -} -resource "aws_instance" "main" { - count = var.count - value = count.index -} -module "aws_instance" { - count = var.count - value = count.index -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(0), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(0), hcl.Range{})}}, Blocks: hclext.Blocks{}}, + Overrides: hclext.Blocks{}, + Want: hclext.Blocks{ + { + Type: "resource", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, }, }, }, }, { - name: "count is greater than 1", - config: ` -resource "aws_instance" "main" { - count = 2 - value = count.index -} -module "aws_instance" { - count = 2 - value = count.index -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(0), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 2}}, - }, - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(1), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 2}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(0), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 6}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.NumberIntVal(1), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 6}}, + Name: "override", + Primaries: hclext.Blocks{ + { + Type: "resource", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{ + "foo": &hclext.Attribute{Name: "foo"}, + "bar": &hclext.Attribute{Name: "bar"}, + }, }, }, }, - }, - { - name: "count is unknown", - config: ` -variable "count" {} - -resource "aws_instance" "main" { - count = var.count -} -module "aws_instance" { - count = var.count -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{}}, - }, - }, - want: &hclext.BodyContent{}, - }, - { - name: "count is sensitive", - config: ` -variable "count" { - sensitive = true - default = 1 -} -resource "aws_instance" "main" { - count = var.count -} -module "aws_instance" { - count = var.count -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - {Type: "resource", Labels: []string{"aws_instance", "main"}, Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}}, - {Type: "module", Labels: []string{"aws_instance"}, Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}}, - }, - }, - }, - { - name: "count is unevaluable", - config: ` -resource "aws_instance" "main" { - count = module.meta.count -} -module "aws_instance" { - count = module.meta.count -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{}}, - }, - }, - want: &hclext.BodyContent{}, - }, - { - name: "count is zero", - config: ` -resource "aws_instance" "main" { - count = 0 -} -module "aws_instance" { - count = 0 -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{}}, - }, - }, - want: &hclext.BodyContent{}, - }, - { - name: "count is string", - config: ` -resource "aws_instance" "main" { - count = "1" -} -module "aws_instance" { - count = "1" -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - {Type: "resource", Labels: []string{"aws_instance", "main"}, Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}}, - {Type: "module", Labels: []string{"aws_instance"}, Body: &hclext.BodyContent{Attributes: hclext.Attributes{}, Blocks: hclext.Blocks{}}}, - }, - }, - }, - { - name: "count.index and sensitive value", - config: ` -variable "sensitive" { - sensitive = true - default = "foo" -} -resource "aws_instance" "main" { - count = 1 - value = "${count.index}-${var.sensitive}" -} -module "aws_instance" { - count = 1 - value = "${count.index}-${var.sensitive}" -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + Overrides: hclext.Blocks{ + { + Type: "resource", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{ + "foo": &hclext.Attribute{Name: "bar"}, + }, + }, }, }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.UnknownVal(cty.String).Mark(marks.Sensitive), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 6}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.UnknownVal(cty.String).Mark(marks.Sensitive), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 10}}, + Want: hclext.Blocks{ + { + Type: "resource", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{ + "foo": &hclext.Attribute{Name: "bar"}, + "bar": &hclext.Attribute{Name: "bar"}, + }, }, }, }, }, { - name: "count.index and nested sensitive value", - config: ` -variable "sensitive" { - sensitive = true - default = "foo" -} -resource "aws_instance" "main" { - count = 1 - value = [count.index, var.sensitive] -} -module "aws_instance" { - count = 1 - value = [count.index, var.sensitive] -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.UnknownVal(cty.Number), cty.StringVal("foo").Mark(marks.Sensitive)}), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 6}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.UnknownVal(cty.Number), cty.StringVal("foo").Mark(marks.Sensitive)}), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 10}}, + Name: "override nested blocks", + Primaries: hclext.Blocks{ + { + Type: "resource", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, + Blocks: hclext.Blocks{ + { + Type: "nested", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{ + "baz": &hclext.Attribute{Name: "baz"}, + "qux": &hclext.Attribute{Name: "qux"}, + }, + }, + }, + }, }, }, }, - }, - { - name: "for_each is not empty (literal)", - config: ` -resource "aws_instance" "main" { - for_each = { foo = "bar" } - value = "${each.key}-${each.value}" -} -module "aws_instance" { - for_each = { foo = "bar" } - value = "${each.key}-${each.value}" -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, + Overrides: hclext.Blocks{ + { + Type: "resource", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "bar"}}, + Blocks: hclext.Blocks{ + { + Type: "nested", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{ + "baz": &hclext.Attribute{Name: "qux"}, + }, + }, + }, + }, + }, }, }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - }, - }, - }, - }, - { - name: "for_each is not empty (variable)", - config: ` -variable "for_each" { - default = { foo = "bar" } -} -resource "aws_instance" "main" { - for_each = var.for_each - value = "${each.key}-${each.value}" -} -module "aws_instance" { - for_each = var.for_each - value = "${each.key}-${each.value}" -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo-bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - }, - }, - }, - }, - { - name: "for_each is unknown", - config: ` -variable "for_each" {} - -resource "aws_instance" "main" { - for_each = var.for_each -} -module "aws_instance" { - for_each = var.for_each -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{}}, - }, - }, - want: &hclext.BodyContent{}, - }, - { - name: "for_each is evaluable", - config: ` -resource "aws_instance" "main" { - for_each = module.meta.for_each -} -module "aws_instance" { - for_each = module.meta.for_each -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{}}, - }, - }, - want: &hclext.BodyContent{}, - }, - { - name: "for_each contains unevaluable", - config: ` -resource "aws_instance" "main" { - for_each = { - known = "known" - unknown = module.meta.unknown - } - value = [each.key, each.value] -} -module "aws_instance" { - for_each = { - known = "known" - unknown = module.meta.unknown - } - value = [each.key, each.value] -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{ - "value": { - Name: "value", - Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.StringVal("known"), cty.StringVal("known")}), hcl.Range{}), - }, - }, - Blocks: hclext.Blocks{}, - }, - DefRange: hcl.Range{Start: hcl.Pos{Line: 2}}, - }, - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{ - "value": { - Name: "value", - Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.StringVal("unknown"), cty.DynamicVal}), hcl.Range{}), - }, - }, - Blocks: hclext.Blocks{}, - }, - DefRange: hcl.Range{Start: hcl.Pos{Line: 2}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{ - "value": { - Name: "value", - Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.StringVal("known"), cty.StringVal("known")}), hcl.Range{}), - }, - }, - Blocks: hclext.Blocks{}, - }, - DefRange: hcl.Range{Start: hcl.Pos{Line: 9}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{ - "value": { - Name: "value", - Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.StringVal("unknown"), cty.DynamicVal}), hcl.Range{}), - }, - }, - Blocks: hclext.Blocks{}, - }, - DefRange: hcl.Range{Start: hcl.Pos{Line: 9}}, - }, - }, - }, - }, - { - name: "for_each is empty", - config: ` -resource "aws_instance" "main" { - for_each = {} -} -module "aws_instance" { - for_each = {} -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{}}, - }, - }, - want: &hclext.BodyContent{}, - }, - { - name: "for_each is not empty set", - config: ` -resource "aws_instance" "main" { - for_each = toset(["foo", "bar"]) - value = each.key -} -module "aws_instance" { - for_each = toset(["foo", "bar"]) - value = each.key -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 2}}, - }, - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 2}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("foo"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 6}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.StringVal("bar"), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 6}}, - }, - }, - }, - }, - { - name: "for_each is empty set", - config: ` -resource "aws_instance" "main" { - for_each = toset([]) -} -module "aws_instance" { - for_each = toset([]) -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{}}, - }, - }, - want: &hclext.BodyContent{}, - }, - { - name: "each.key/each.value and sensitive value", - config: ` -variable "sensitive" { - sensitive = true - default = "foo" -} -resource "aws_instance" "main" { - for_each = { foo = "bar" } - value = "${each.key}-${each.value}-${var.sensitive}" -} -module "aws_instance" { - for_each = { foo = "bar" } - value = "${each.key}-${each.value}-${var.sensitive}" -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.UnknownVal(cty.String).Mark(marks.Sensitive), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 6}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.UnknownVal(cty.String).Mark(marks.Sensitive), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 10}}, - }, - }, - }, - }, - { - name: "each.key/each.value and nested sensitive value", - config: ` -variable "sensitive" { - sensitive = true - default = "foo" -} -resource "aws_instance" "main" { - for_each = { foo = "bar" } - value = [each.key, var.sensitive] -} -module "aws_instance" { - for_each = { foo = "bar" } - value = [each.value, var.sensitive] -}`, - schema: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - {Type: "resource", LabelNames: []string{"type", "name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - {Type: "module", LabelNames: []string{"name"}, Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "value"}}}}, - }, - }, - want: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "resource", - Labels: []string{"aws_instance", "main"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.DynamicVal, cty.StringVal("foo").Mark(marks.Sensitive)}), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 6}}, - }, - { - Type: "module", - Labels: []string{"aws_instance"}, - Body: &hclext.BodyContent{Attributes: hclext.Attributes{"value": {Name: "value", Expr: hcl.StaticExpr(cty.TupleVal([]cty.Value{cty.DynamicVal, cty.StringVal("foo").Mark(marks.Sensitive)}), hcl.Range{})}}, Blocks: hclext.Blocks{}}, - DefRange: hcl.Range{Start: hcl.Pos{Line: 10}}, - }, - }, - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - fs := afero.Afero{Fs: afero.NewMemMapFs()} - if err := fs.WriteFile("main.tf", []byte(test.config), os.ModePerm); err != nil { - t.Fatal(err) - } - - parser := NewParser(fs) - mod, diags := parser.LoadConfigDir(".") - if diags.HasErrors() { - t.Fatal(diags) - } - config, diags := BuildConfig(mod, ModuleWalkerFunc(func(req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics) { return nil, nil, nil })) - if diags.HasErrors() { - t.Fatal(diags) - } - variableValues, diags := VariableValues(config) - if diags.HasErrors() { - t.Fatal(diags) - } - - ctx := &Evaluator{ - Meta: &ContextMeta{Env: Workspace()}, - ModulePath: config.Path.UnkeyedInstanceShim(), - Config: config, - VariableValues: variableValues, - } - - got, diags := config.Module.PartialContent(test.schema, ctx) - if diags.HasErrors() { - t.Fatal(diags) - } - - opts := cmp.Options{ - cmpopts.IgnoreFields(hclext.Block{}, "TypeRange", "LabelRanges"), - cmpopts.IgnoreFields(hclext.Attribute{}, "NameRange"), - cmpopts.IgnoreFields(hcl.Range{}, "Start", "End", "Filename"), - cmpopts.SortSlices(func(i, j *hclext.Block) bool { - if i.DefRange.String() == j.DefRange.String() { - ia, iaExists := i.Body.Attributes["value"] - ja, jaExists := j.Body.Attributes["value"] - if iaExists && jaExists { - iv, diags := ia.Expr.Value(nil) - if diags.HasErrors() { - t.Fatal(diags) - } - jv, diags := ja.Expr.Value(nil) - if diags.HasErrors() { - t.Fatal(diags) - } - return iv.GoString() < jv.GoString() - } - } - return i.DefRange.String() < j.DefRange.String() - }), - cmp.Comparer(func(x, y hcl.Expression) bool { - xv, diags := ctx.EvaluateExpr(x, cty.DynamicPseudoType, EvalDataForNoInstanceKey) - if diags.HasErrors() { - t.Fatal(diags) - } - yv, diags := ctx.EvaluateExpr(y, cty.DynamicPseudoType, EvalDataForNoInstanceKey) - if diags.HasErrors() { - t.Fatal(diags) - } - return xv.RawEquals(yv) - }), - } - if diff := cmp.Diff(got, test.want, opts); diff != "" { - t.Error(diff) - } - }) - } -} - -func Test_overrideBlocks(t *testing.T) { - tests := []struct { - Name string - Primaries hclext.Blocks - Overrides hclext.Blocks - Want hclext.Blocks - }{ - { - Name: "empty blocks", - Primaries: hclext.Blocks{}, - Overrides: hclext.Blocks{}, - Want: hclext.Blocks{}, - }, - { - Name: "no override", - Primaries: hclext.Blocks{ - { - Type: "resource", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - }, - }, - }, - Overrides: hclext.Blocks{}, - Want: hclext.Blocks{ - { - Type: "resource", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - }, - }, - }, - }, - { - Name: "override", - Primaries: hclext.Blocks{ - { - Type: "resource", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{ - "foo": &hclext.Attribute{Name: "foo"}, - "bar": &hclext.Attribute{Name: "bar"}, - }, - }, - }, - }, - Overrides: hclext.Blocks{ - { - Type: "resource", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{ - "foo": &hclext.Attribute{Name: "bar"}, - }, - }, - }, - }, - Want: hclext.Blocks{ - { - Type: "resource", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{ - "foo": &hclext.Attribute{Name: "bar"}, - "bar": &hclext.Attribute{Name: "bar"}, - }, - }, - }, - }, - }, - { - Name: "override nested blocks", - Primaries: hclext.Blocks{ - { - Type: "resource", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - Blocks: hclext.Blocks{ - { - Type: "nested", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{ - "baz": &hclext.Attribute{Name: "baz"}, - "qux": &hclext.Attribute{Name: "qux"}, - }, - }, - }, - }, - }, - }, - }, - Overrides: hclext.Blocks{ - { - Type: "resource", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "bar"}}, - Blocks: hclext.Blocks{ - { - Type: "nested", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{ - "baz": &hclext.Attribute{Name: "qux"}, - }, - }, - }, - }, - }, - }, - }, - Want: hclext.Blocks{ - { - Type: "resource", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "bar"}}, - Blocks: hclext.Blocks{ - { - Type: "nested", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{ - "baz": &hclext.Attribute{Name: "qux"}, - "qux": &hclext.Attribute{Name: "qux"}, - }, - }, - }, - }, + Want: hclext.Blocks{ + { + Type: "resource", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "bar"}}, + Blocks: hclext.Blocks{ + { + Type: "nested", + Body: &hclext.BodyContent{ + Attributes: hclext.Attributes{ + "baz": &hclext.Attribute{Name: "qux"}, + "qux": &hclext.Attribute{Name: "qux"}, + }, + }, + }, + }, }, }, }, @@ -1240,343 +516,3 @@ func Test_overrideBlocks(t *testing.T) { }) } } - -func Test_schemaWithDynamic(t *testing.T) { - tests := []struct { - name string - in *hclext.BodySchema - want *hclext.BodySchema - }{ - { - name: "empty schema", - in: &hclext.BodySchema{}, - want: &hclext.BodySchema{}, - }, - { - name: "attribute schemas", - in: &hclext.BodySchema{ - Attributes: []hclext.AttributeSchema{{Name: "foo"}}, - }, - want: &hclext.BodySchema{ - Attributes: []hclext.AttributeSchema{{Name: "foo"}}, - }, - }, - { - name: "block schemas", - in: &hclext.BodySchema{ - Attributes: []hclext.AttributeSchema{{Name: "foo"}}, - Blocks: []hclext.BlockSchema{ - { - Type: "toplevel", - Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "bar"}}}, - }, - }, - }, - want: &hclext.BodySchema{ - Attributes: []hclext.AttributeSchema{{Name: "foo"}}, - Blocks: []hclext.BlockSchema{ - { - Type: "toplevel", - Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "bar"}}}, - }, - { - Type: "dynamic", - LabelNames: []string{"type"}, - Body: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - { - Type: "content", - Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "bar"}}}, - }, - }, - }, - }, - }, - }, - }, - { - name: "nested block schemas", - in: &hclext.BodySchema{ - Attributes: []hclext.AttributeSchema{{Name: "foo"}}, - Blocks: []hclext.BlockSchema{ - { - Type: "toplevel", - Body: &hclext.BodySchema{ - Attributes: []hclext.AttributeSchema{{Name: "bar"}}, - Blocks: []hclext.BlockSchema{ - { - Type: "nested", - Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "bar"}}}, - }, - }, - }, - }, - }, - }, - want: &hclext.BodySchema{ - Attributes: []hclext.AttributeSchema{{Name: "foo"}}, - Blocks: []hclext.BlockSchema{ - { - Type: "toplevel", - Body: &hclext.BodySchema{ - Attributes: []hclext.AttributeSchema{{Name: "bar"}}, - Blocks: []hclext.BlockSchema{ - { - Type: "nested", - Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "bar"}}}, - }, - { - Type: "dynamic", - LabelNames: []string{"type"}, - Body: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - { - Type: "content", - Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "bar"}}}, - }, - }, - }, - }, - }, - }, - }, - { - Type: "dynamic", - LabelNames: []string{"type"}, - Body: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - { - Type: "content", - Body: &hclext.BodySchema{ - Attributes: []hclext.AttributeSchema{{Name: "bar"}}, - Blocks: []hclext.BlockSchema{ - { - Type: "nested", - Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "bar"}}}, - }, - { - Type: "dynamic", - LabelNames: []string{"type"}, - Body: &hclext.BodySchema{ - Blocks: []hclext.BlockSchema{ - { - Type: "content", - Body: &hclext.BodySchema{Attributes: []hclext.AttributeSchema{{Name: "bar"}}}, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := schemaWithDynamic(test.in) - - if diff := cmp.Diff(got, test.want); diff != "" { - t.Error(diff) - } - }) - } -} - -func Test_resolveDynamicBlocks(t *testing.T) { - tests := []struct { - name string - in *hclext.BodyContent - want *hclext.BodyContent - }{ - { - name: "empty body", - in: &hclext.BodyContent{}, - want: &hclext.BodyContent{}, - }, - { - name: "only attributes", - in: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - }, - want: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - }, - }, - { - name: "regular blocks", - in: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - Blocks: hclext.Blocks{ - { - Type: "toplevel", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"bar": &hclext.Attribute{Name: "bar"}}, - }, - }, - }, - }, - want: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - Blocks: hclext.Blocks{ - { - Type: "toplevel", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"bar": &hclext.Attribute{Name: "bar"}}, - }, - }, - }, - }, - }, - { - name: "dynamic blocks", - in: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - Blocks: hclext.Blocks{ - { - Type: "dynamic", - Labels: []string{"toplevel"}, - Body: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "content", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"bar": &hclext.Attribute{Name: "bar"}}, - }, - }, - }, - }, - }, - }, - }, - want: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - Blocks: hclext.Blocks{ - { - Type: "toplevel", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"bar": &hclext.Attribute{Name: "bar"}}, - }, - }, - }, - }, - }, - { - name: "dynamic nested blocks in regular blocks", - in: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - Blocks: hclext.Blocks{ - { - Type: "toplevel", - Body: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "dynamic", - Labels: []string{"nested"}, - Body: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "content", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"bar": &hclext.Attribute{Name: "bar"}}, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - want: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - Blocks: hclext.Blocks{ - { - Type: "toplevel", - Body: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "nested", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"bar": &hclext.Attribute{Name: "bar"}}, - }, - }, - }, - }, - }, - }, - }, - }, - { - name: "dynamic nested blocks in dynamic blocks", - in: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - Blocks: hclext.Blocks{ - { - Type: "dynamic", - Labels: []string{"toplevel"}, - Body: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "content", - Body: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "dynamic", - Labels: []string{"nested"}, - Body: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "content", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"bar": &hclext.Attribute{Name: "bar"}}, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - want: &hclext.BodyContent{ - Attributes: hclext.Attributes{"foo": &hclext.Attribute{Name: "foo"}}, - Blocks: hclext.Blocks{ - { - Type: "toplevel", - Body: &hclext.BodyContent{ - Blocks: hclext.Blocks{ - { - Type: "nested", - Body: &hclext.BodyContent{ - Attributes: hclext.Attributes{"bar": &hclext.Attribute{Name: "bar"}}, - }, - }, - }, - }, - }, - }, - }, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := resolveDynamicBlocks(test.in) - - if diff := cmp.Diff(got, test.want); diff != "" { - t.Error(diff) - } - }) - } -} diff --git a/terraform/resource.go b/terraform/resource.go index 4c9de88ef..f4ca3ab5e 100644 --- a/terraform/resource.go +++ b/terraform/resource.go @@ -9,32 +9,15 @@ type Resource struct { Name string Type string - expandable - DeclRange hcl.Range TypeRange hcl.Range } func decodeResourceBlock(block *hclext.Block) *Resource { - r := &Resource{ + return &Resource{ Type: block.Labels[0], Name: block.Labels[1], DeclRange: block.DefRange, TypeRange: block.LabelRanges[0], } - - if attr, exists := block.Body.Attributes["count"]; exists { - r.Count = attr.Expr - } - if attr, exists := block.Body.Attributes["for_each"]; exists { - r.ForEach = attr.Expr - } - return r -} - -var resourceBlockSchema = &hclext.BodySchema{ - Attributes: []hclext.AttributeSchema{ - {Name: "count"}, - {Name: "for_each"}, - }, } diff --git a/terraform/tfhcl/LICENSE b/terraform/tfhcl/LICENSE new file mode 100644 index 000000000..e25da5fad --- /dev/null +++ b/terraform/tfhcl/LICENSE @@ -0,0 +1,355 @@ +Copyright (c) 2014 HashiCorp, Inc. + +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. “Contributor” + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. “Contributor Version” + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor’s Contribution. + +1.3. “Contribution” + + means Covered Software of a particular Contributor. + +1.4. “Covered Software” + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. “Incompatible With Secondary Licenses” + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of version + 1.1 or earlier of the License, but not also under the terms of a + Secondary License. + +1.6. “Executable Form” + + means any form of the work other than Source Code Form. + +1.7. “Larger Work” + + means a work that combines Covered Software with other material, in a separate + file or files, that is not Covered Software. + +1.8. “License” + + means this document. + +1.9. “Licensable” + + means having the right to grant, to the maximum extent possible, whether at the + time of the initial grant or subsequently, any and all of the rights conveyed by + this License. + +1.10. “Modifications” + + means any of the following: + + a. any file in Source Code Form that results from an addition to, deletion + from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. “Patent Claims” of a Contributor + + means any patent claim(s), including without limitation, method, process, + and apparatus claims, in any patent Licensable by such Contributor that + would be infringed, but for the grant of the License, by the making, + using, selling, offering for sale, having made, import, or transfer of + either its Contributions or its Contributor Version. + +1.12. “Secondary License” + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. “Source Code Form” + + means the form of the work preferred for making modifications. + +1.14. “You” (or “Your”) + + means an individual or a legal entity exercising rights under this + License. For legal entities, “You” includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, “control” means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or as + part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its Contributions + or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution become + effective for each Contribution on the date the Contributor first distributes + such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under this + License. No additional rights or licenses will be implied from the distribution + or licensing of Covered Software under this License. Notwithstanding Section + 2.1(b) above, no patent license is granted by a Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party’s + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of its + Contributions. + + This License does not grant any rights in the trademarks, service marks, or + logos of any Contributor (except as may be necessary to comply with the + notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this License + (see Section 10.2) or under the terms of a Secondary License (if permitted + under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its Contributions + are its original creation(s) or it has sufficient rights to grant the + rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under applicable + copyright doctrines of fair use, fair dealing, or other equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under the + terms of this License. You must inform recipients that the Source Code Form + of the Covered Software is governed by the terms of this License, and how + they can obtain a copy of this License. You may not attempt to alter or + restrict the recipients’ rights in the Source Code Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this License, + or sublicense it under different terms, provided that the license for + the Executable Form does not attempt to limit or alter the recipients’ + rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for the + Covered Software. If the Larger Work is a combination of Covered Software + with a work governed by one or more Secondary Licenses, and the Covered + Software is not Incompatible With Secondary Licenses, this License permits + You to additionally distribute such Covered Software under the terms of + such Secondary License(s), so that the recipient of the Larger Work may, at + their option, further distribute the Covered Software under the terms of + either this License or such Secondary License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices (including + copyright notices, patent notices, disclaimers of warranty, or limitations + of liability) contained within the Source Code Form of the Covered + Software, except that You may alter any license notices to the extent + required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on behalf + of any Contributor. You must make it absolutely clear that any such + warranty, support, indemnity, or liability obligation is offered by You + alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, judicial + order, or regulation then You must: (a) comply with the terms of this License + to the maximum extent possible; and (b) describe the limitations and the code + they affect. Such description must be placed in a text file included with all + distributions of the Covered Software under this License. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing basis, + if such Contributor fails to notify You of the non-compliance by some + reasonable means prior to 60 days after You have come back into compliance. + Moreover, Your grants from a particular Contributor are reinstated on an + ongoing basis if such Contributor notifies You of the non-compliance by + some reasonable means, this is the first time You have received notice of + non-compliance with this License from such Contributor, and You become + compliant prior to 30 days after Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, counter-claims, + and cross-claims) alleging that a Contributor Version directly or + indirectly infringes any patent, then the rights granted to You by any and + all Contributors for the Covered Software under Section 2.1 of this License + shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an “as is” basis, without + warranty of any kind, either expressed, implied, or statutory, including, + without limitation, warranties that the Covered Software is free of defects, + merchantable, fit for a particular purpose or non-infringing. The entire + risk as to the quality and performance of the Covered Software is with You. + Should any Covered Software prove defective in any respect, You (not any + Contributor) assume the cost of any necessary servicing, repair, or + correction. This disclaimer of warranty constitutes an essential part of this + License. No use of any Covered Software is authorized under this License + except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from such + party’s negligence to the extent applicable law prohibits such limitation. + Some jurisdictions do not allow the exclusion or limitation of incidental or + consequential damages, so this exclusion and limitation may not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts of + a jurisdiction where the defendant maintains its principal place of business + and such litigation shall be governed by laws of that jurisdiction, without + reference to its conflict-of-law provisions. Nothing in this Section shall + prevent a party’s ability to bring cross-claims or counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject matter + hereof. If any provision of this License is held to be unenforceable, such + provision shall be reformed only to the extent necessary to make it + enforceable. Any law or regulation which provides that the language of a + contract shall be construed against the drafter shall not be used to construe + this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version of + the License under which You originally received the Covered Software, or + under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a modified + version of this License if you rename the license and remove any + references to the name of the license steward (except to note that such + modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + If You choose to distribute Source Code Form that is Incompatible With + Secondary Licenses under the terms of this version of the License, the + notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then +You may include the notice in a location (such as a LICENSE file in a relevant +directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - “Incompatible With Secondary Licenses” Notice + + This Source Code Form is “Incompatible + With Secondary Licenses”, as defined by + the Mozilla Public License, v. 2.0. diff --git a/terraform/tfhcl/README.md b/terraform/tfhcl/README.md new file mode 100644 index 000000000..c6de5ecbe --- /dev/null +++ b/terraform/tfhcl/README.md @@ -0,0 +1,3 @@ +# Forked `hcl/ext/dynblock` package + +This package is a fork of [`github.com/hashicorp/hcl/ext/dynblock`](https://github.com/hashicorp/hcl/tree/main/ext/dynblock). TFLint maintains its own dynblock implementation to support not only dynamic blocks, but also count/for_each meta-arguments in the HCL layer. diff --git a/terraform/tfhcl/expand_body.go b/terraform/tfhcl/expand_body.go new file mode 100644 index 000000000..3bb83fd8b --- /dev/null +++ b/terraform/tfhcl/expand_body.go @@ -0,0 +1,341 @@ +package tfhcl + +import ( + "fmt" + + "github.com/hashicorp/hcl/v2" + "github.com/terraform-linters/tflint-plugin-sdk/hclext" + "github.com/zclconf/go-cty/cty" +) + +// expandBody wraps another hcl.Body and expands any "dynamic" blocks, count/for-each +// resources found inside whenever Content or PartialContent is called. +type expandBody struct { + original hcl.Body + ctx *hcl.EvalContext + dynamicIteration *dynamicIteration // non-nil if we're nested inside a "dynamic" block + metaArgIteration *metaArgIteration // non-nil if we're nested inside a block with meta-arguments + + // These are used with PartialContent to produce a "remaining items" + // body to return. They are nil on all bodies fresh out of the transformer. + // + // Note that this is re-implemented here rather than delegating to the + // existing support required by the underlying body because we need to + // retain access to the entire original body on subsequent decode operations + // so we can retain any "dynamic" blocks for types we didn't take consume + // on the first pass. + hiddenAttrs map[string]struct{} + hiddenBlocks map[string]hcl.BlockHeaderSchema +} + +func (b *expandBody) Content(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Diagnostics) { + extSchema := b.extendSchema(schema) + rawContent, diags := b.original.Content(extSchema) + + blocks, blockDiags := b.expandBlocks(schema, rawContent.Blocks, false) + diags = append(diags, blockDiags...) + attrs, attrDiags := b.prepareAttributes(rawContent.Attributes) + diags = append(diags, attrDiags...) + + content := &hcl.BodyContent{ + Attributes: attrs, + Blocks: blocks, + MissingItemRange: b.original.MissingItemRange(), + } + + return content, diags +} + +func (b *expandBody) PartialContent(schema *hcl.BodySchema) (*hcl.BodyContent, hcl.Body, hcl.Diagnostics) { + extSchema := b.extendSchema(schema) + rawContent, _, diags := b.original.PartialContent(extSchema) + // We discard the "remain" argument above because we're going to construct + // our own remain that also takes into account remaining "dynamic" blocks. + + blocks, blockDiags := b.expandBlocks(schema, rawContent.Blocks, true) + diags = append(diags, blockDiags...) + attrs, attrDiags := b.prepareAttributes(rawContent.Attributes) + diags = append(diags, attrDiags...) + + content := &hcl.BodyContent{ + Attributes: attrs, + Blocks: blocks, + MissingItemRange: b.original.MissingItemRange(), + } + + remain := &expandBody{ + original: b.original, + ctx: b.ctx, + dynamicIteration: b.dynamicIteration, + metaArgIteration: b.metaArgIteration, + hiddenAttrs: make(map[string]struct{}), + hiddenBlocks: make(map[string]hcl.BlockHeaderSchema), + } + for name := range b.hiddenAttrs { + remain.hiddenAttrs[name] = struct{}{} + } + for typeName, blockS := range b.hiddenBlocks { + remain.hiddenBlocks[typeName] = blockS + } + for _, attrS := range schema.Attributes { + remain.hiddenAttrs[attrS.Name] = struct{}{} + } + for _, blockS := range schema.Blocks { + remain.hiddenBlocks[blockS.Type] = blockS + } + + return content, remain, diags +} + +func (b *expandBody) extendSchema(schema *hcl.BodySchema) *hcl.BodySchema { + // We augment the requested schema to also include our special "dynamic" + // block type, since then we'll get instances of it interleaved with + // all of the literal child blocks we must also include. + extSchema := &hcl.BodySchema{ + Attributes: schema.Attributes, + Blocks: make([]hcl.BlockHeaderSchema, len(schema.Blocks), len(schema.Blocks)+len(b.hiddenBlocks)+1), + } + copy(extSchema.Blocks, schema.Blocks) + extSchema.Blocks = append(extSchema.Blocks, dynamicBlockHeaderSchema) + + // If we have any hiddenBlocks then we also need to register those here + // so that a call to "Content" on the underlying body won't fail. + // (We'll filter these out again once we process the result of either + // Content or PartialContent.) + for _, blockS := range b.hiddenBlocks { + extSchema.Blocks = append(extSchema.Blocks, blockS) + } + + // If we have any hiddenAttrs then we also need to register these, for + // the same reason as we deal with hiddenBlocks above. + if len(b.hiddenAttrs) != 0 { + newAttrs := make([]hcl.AttributeSchema, len(schema.Attributes), len(schema.Attributes)+len(b.hiddenAttrs)) + copy(newAttrs, extSchema.Attributes) + for name := range b.hiddenAttrs { + newAttrs = append(newAttrs, hcl.AttributeSchema{ + Name: name, + Required: false, + }) + } + extSchema.Attributes = newAttrs + } + + return extSchema +} + +func (b *expandBody) prepareAttributes(rawAttrs hcl.Attributes) (hcl.Attributes, hcl.Diagnostics) { + var diags hcl.Diagnostics + + if len(b.hiddenAttrs) == 0 && b.dynamicIteration == nil && b.metaArgIteration == nil { + // Easy path: just pass through the attrs from the original body verbatim + return rawAttrs, diags + } + + // Otherwise we have some work to do: we must filter out any attributes + // that are hidden (since a previous PartialContent call already saw these) + // and wrap the expressions of the inner attributes so that they will + // have access to our iteration variables. + attrs := make(hcl.Attributes, len(rawAttrs)) + for name, rawAttr := range rawAttrs { + if _, hidden := b.hiddenAttrs[name]; hidden { + continue + } + if b.dynamicIteration != nil || b.metaArgIteration != nil { + attr := *rawAttr // shallow copy so we can mutate it + expr := exprWrap{ + Expression: attr.Expr, + di: b.dynamicIteration, + mi: b.metaArgIteration, + } + // Unlike hcl/ext/dynblock, wrapped expressions are evaluated immediately. + // The result is bound to the expression and can be accessed without + // the iterator context. + val, evalDiags := expr.Value(b.ctx) + if evalDiags.HasErrors() { + diags = append(diags, evalDiags...) + continue + } + // Marked values (e.g. sensitive values) are unbound for serialization. + if !val.ContainsMarked() { + attr.Expr = hclext.BindValue(val, expr) + } + attrs[name] = &attr + } else { + // If we have no active iteration then no wrapping is required. + attrs[name] = rawAttr + } + } + return attrs, diags +} + +func (b *expandBody) expandBlocks(schema *hcl.BodySchema, rawBlocks hcl.Blocks, partial bool) (hcl.Blocks, hcl.Diagnostics) { + var blocks hcl.Blocks + var diags hcl.Diagnostics + + for _, rawBlock := range rawBlocks { + switch rawBlock.Type { + case "dynamic": + expandedBlocks, expandDiags := b.expandDynamicBlock(schema, rawBlock, partial) + blocks = append(blocks, expandedBlocks...) + diags = append(diags, expandDiags...) + + case "resource", "module": + expandedBlocks, expandDiags := b.expandMetaArgBlock(schema, rawBlock) + blocks = append(blocks, expandedBlocks...) + diags = append(diags, expandDiags...) + + default: + if _, hidden := b.hiddenBlocks[rawBlock.Type]; !hidden { + blocks = append(blocks, b.expandStaticBlock(rawBlock)) + } + } + } + + return blocks, diags +} + +func (b *expandBody) expandDynamicBlock(schema *hcl.BodySchema, rawBlock *hcl.Block, partial bool) (hcl.Blocks, hcl.Diagnostics) { + var diags hcl.Diagnostics + + realBlockType := rawBlock.Labels[0] + if _, hidden := b.hiddenBlocks[realBlockType]; hidden { + return hcl.Blocks{}, diags + } + + var blockS *hcl.BlockHeaderSchema + for _, candidate := range schema.Blocks { + if candidate.Type == realBlockType { + blockS = &candidate + break + } + } + if blockS == nil { + // Not a block type that the caller requested. + if !partial { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unsupported block type", + Detail: fmt.Sprintf("Blocks of type %q are not expected here.", realBlockType), + Subject: &rawBlock.LabelRanges[0], + }) + } + return hcl.Blocks{}, diags + } + + spec, specDiags := b.decodeDynamicSpec(blockS, rawBlock) + diags = append(diags, specDiags...) + if specDiags.HasErrors() { + return hcl.Blocks{}, diags + } + + if !spec.forEachVal.IsKnown() { + // If for_each is unknown, no blocks are returned + return hcl.Blocks{}, diags + } + + var blocks hcl.Blocks + + for it := spec.forEachVal.ElementIterator(); it.Next(); { + key, value := it.Element() + i := b.dynamicIteration.MakeChild(spec.iteratorName, key, value) + + block, blockDiags := spec.newBlock(i, b.ctx) + diags = append(diags, blockDiags...) + if block != nil { + // Attach our new iteration context so that attributes + // and other nested blocks can refer to our iterator. + block.Body = b.expandChild(block.Body, i, b.metaArgIteration) + blocks = append(blocks, block) + } + } + return blocks, diags +} + +func (b *expandBody) expandMetaArgBlock(schema *hcl.BodySchema, rawBlock *hcl.Block) (hcl.Blocks, hcl.Diagnostics) { + var diags hcl.Diagnostics + + if _, hidden := b.hiddenBlocks[rawBlock.Type]; hidden { + return hcl.Blocks{}, diags + } + + spec, specDiags := b.decodeMetaArgSpec(rawBlock) + diags = append(diags, specDiags...) + if specDiags.HasErrors() { + return hcl.Blocks{}, diags + } + + //// count attribute + + if spec.countSet { + if !spec.countVal.IsKnown() { + // If count is unknown, no blocks are returned + return hcl.Blocks{}, diags + } + + var blocks hcl.Blocks + + for idx := 0; idx < spec.countNum; idx++ { + i := MakeCountIteration(cty.NumberIntVal(int64(idx))) + + expandedBlock := *rawBlock // shallow copy + expandedBlock.Body = b.expandChild(rawBlock.Body, b.dynamicIteration, i) + blocks = append(blocks, &expandedBlock) + } + + return blocks, diags + } + + //// for_each attribute + + if spec.forEachSet { + if !spec.forEachVal.IsKnown() { + // If for_each is unknown, no blocks are returned + return hcl.Blocks{}, diags + } + + var blocks hcl.Blocks + + for it := spec.forEachVal.ElementIterator(); it.Next(); { + i := MakeForEachIteration(it.Element()) + + expandedBlock := *rawBlock // shallow copy + expandedBlock.Body = b.expandChild(rawBlock.Body, b.dynamicIteration, i) + blocks = append(blocks, &expandedBlock) + } + + return blocks, diags + } + + //// Neither count/for_each + + return hcl.Blocks{b.expandStaticBlock(rawBlock)}, diags +} + +func (b *expandBody) expandStaticBlock(rawBlock *hcl.Block) *hcl.Block { + // A static block doesn't create a new iteration context, but + // it does need to inherit _our own_ iteration context in + // case it contains expressions that refer to our inherited + // iterators, or nested "dynamic" blocks. + expandedBlock := *rawBlock + expandedBlock.Body = b.expandChild(rawBlock.Body, b.dynamicIteration, b.metaArgIteration) + return &expandedBlock +} + +func (b *expandBody) expandChild(child hcl.Body, i *dynamicIteration, mi *metaArgIteration) hcl.Body { + chiCtx := i.EvalContext(mi.EvalContext(b.ctx)) + ret := Expand(child, chiCtx) + ret.(*expandBody).dynamicIteration = i + ret.(*expandBody).metaArgIteration = mi + return ret +} + +func (b *expandBody) JustAttributes() (hcl.Attributes, hcl.Diagnostics) { + // blocks aren't allowed in JustAttributes mode and this body can + // only produce blocks, so we'll just pass straight through to our + // underlying body here. + return b.original.JustAttributes() +} + +func (b *expandBody) MissingItemRange() hcl.Range { + return b.original.MissingItemRange() +} diff --git a/terraform/tfhcl/expand_body_test.go b/terraform/tfhcl/expand_body_test.go new file mode 100644 index 000000000..7fdd6878e --- /dev/null +++ b/terraform/tfhcl/expand_body_test.go @@ -0,0 +1,333 @@ +package tfhcl + +import ( + "testing" + + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/hcldec" + "github.com/hashicorp/hcl/v2/hcltest" + "github.com/zclconf/go-cty/cty" +) + +func TestExpand(t *testing.T) { + srcBody := hcltest.MockBody(&hcl.BodyContent{ + Blocks: hcl.Blocks{ + { + Type: "a", + Labels: []string{"static0"}, + LabelRanges: []hcl.Range{hcl.Range{}}, + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "val": hcltest.MockExprLiteral(cty.StringVal("static a 0")), + }), + }), + }, + { + Type: "b", + Body: hcltest.MockBody(&hcl.BodyContent{ + Blocks: hcl.Blocks{ + { + Type: "c", + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "val0": hcltest.MockExprLiteral(cty.StringVal("static c 0")), + }), + }), + }, + { + Type: "dynamic", + Labels: []string{"c"}, + LabelRanges: []hcl.Range{hcl.Range{}}, + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "for_each": hcltest.MockExprLiteral(cty.ListVal([]cty.Value{ + cty.StringVal("dynamic c 0"), + cty.StringVal("dynamic c 1"), + })), + "iterator": hcltest.MockExprVariable("dyn_c"), + }), + Blocks: hcl.Blocks{ + { + Type: "content", + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "val0": hcltest.MockExprTraversalSrc("dyn_c.value"), + }), + }), + }, + }, + }), + }, + }, + }), + }, + { + Type: "dynamic", + Labels: []string{"a"}, + LabelRanges: []hcl.Range{hcl.Range{}}, + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "for_each": hcltest.MockExprLiteral(cty.ListVal([]cty.Value{ + cty.StringVal("dynamic a 0"), + cty.StringVal("dynamic a 1"), + cty.StringVal("dynamic a 2"), + })), + "labels": hcltest.MockExprList([]hcl.Expression{ + hcltest.MockExprTraversalSrc("a.key"), + }), + }), + Blocks: hcl.Blocks{ + { + Type: "content", + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "val": hcltest.MockExprTraversalSrc("a.value"), + }), + }), + }, + }, + }), + }, + { + Type: "dynamic", + Labels: []string{"b"}, + LabelRanges: []hcl.Range{hcl.Range{}}, + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "for_each": hcltest.MockExprLiteral(cty.ListVal([]cty.Value{ + cty.StringVal("dynamic b 0"), + cty.StringVal("dynamic b 1"), + })), + "iterator": hcltest.MockExprVariable("dyn_b"), + }), + Blocks: hcl.Blocks{ + { + Type: "content", + Body: hcltest.MockBody(&hcl.BodyContent{ + Blocks: hcl.Blocks{ + { + Type: "c", + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "val0": hcltest.MockExprLiteral(cty.StringVal("static c 1")), + "val1": hcltest.MockExprTraversalSrc("dyn_b.value"), + }), + }), + }, + { + Type: "dynamic", + Labels: []string{"c"}, + LabelRanges: []hcl.Range{hcl.Range{}}, + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "for_each": hcltest.MockExprLiteral(cty.ListVal([]cty.Value{ + cty.StringVal("dynamic c 2"), + cty.StringVal("dynamic c 3"), + })), + }), + Blocks: hcl.Blocks{ + { + Type: "content", + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "val0": hcltest.MockExprTraversalSrc("c.value"), + "val1": hcltest.MockExprTraversalSrc("dyn_b.value"), + }), + }), + }, + }, + }), + }, + }, + }), + }, + }, + }), + }, + { + Type: "dynamic", + Labels: []string{"b"}, + LabelRanges: []hcl.Range{hcl.Range{}}, + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "for_each": hcltest.MockExprLiteral(cty.MapVal(map[string]cty.Value{ + "foo": cty.ListVal([]cty.Value{ + cty.StringVal("dynamic c nested 0"), + cty.StringVal("dynamic c nested 1"), + }), + })), + "iterator": hcltest.MockExprVariable("dyn_b"), + }), + Blocks: hcl.Blocks{ + { + Type: "content", + Body: hcltest.MockBody(&hcl.BodyContent{ + Blocks: hcl.Blocks{ + { + Type: "dynamic", + Labels: []string{"c"}, + LabelRanges: []hcl.Range{hcl.Range{}}, + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "for_each": hcltest.MockExprTraversalSrc("dyn_b.value"), + }), + Blocks: hcl.Blocks{ + { + Type: "content", + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "val0": hcltest.MockExprTraversalSrc("c.value"), + "val1": hcltest.MockExprTraversalSrc("dyn_b.key"), + }), + }), + }, + }, + }), + }, + }, + }), + }, + }, + }), + }, + { + Type: "a", + Labels: []string{"static1"}, + LabelRanges: []hcl.Range{hcl.Range{}}, + Body: hcltest.MockBody(&hcl.BodyContent{ + Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ + "val": hcltest.MockExprLiteral(cty.StringVal("static a 1")), + }), + }), + }, + }, + }) + + dynBody := Expand(srcBody, nil) + var remain hcl.Body + + t.Run("PartialDecode", func(t *testing.T) { + decSpec := &hcldec.BlockMapSpec{ + TypeName: "a", + LabelNames: []string{"key"}, + Nested: &hcldec.AttrSpec{ + Name: "val", + Type: cty.String, + Required: true, + }, + } + + var got cty.Value + var diags hcl.Diagnostics + got, remain, diags = hcldec.PartialDecode(dynBody, decSpec, nil) + if len(diags) != 0 { + t.Errorf("unexpected diagnostics") + for _, diag := range diags { + t.Logf("- %s", diag) + } + return + } + + want := cty.MapVal(map[string]cty.Value{ + "static0": cty.StringVal("static a 0"), + "static1": cty.StringVal("static a 1"), + "0": cty.StringVal("dynamic a 0"), + "1": cty.StringVal("dynamic a 1"), + "2": cty.StringVal("dynamic a 2"), + }) + + if !got.RawEquals(want) { + t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, want) + } + }) + + t.Run("Decode", func(t *testing.T) { + decSpec := &hcldec.BlockListSpec{ + TypeName: "b", + Nested: &hcldec.BlockListSpec{ + TypeName: "c", + Nested: &hcldec.ObjectSpec{ + "val0": &hcldec.AttrSpec{ + Name: "val0", + Type: cty.String, + }, + "val1": &hcldec.AttrSpec{ + Name: "val1", + Type: cty.String, + }, + }, + }, + } + + var got cty.Value + var diags hcl.Diagnostics + got, diags = hcldec.Decode(remain, decSpec, nil) + if len(diags) != 0 { + t.Errorf("unexpected diagnostics") + for _, diag := range diags { + t.Logf("- %s", diag) + } + return + } + + want := cty.ListVal([]cty.Value{ + cty.ListVal([]cty.Value{ + cty.ObjectVal(map[string]cty.Value{ + "val0": cty.StringVal("static c 0"), + "val1": cty.NullVal(cty.String), + }), + cty.ObjectVal(map[string]cty.Value{ + "val0": cty.StringVal("dynamic c 0"), + "val1": cty.NullVal(cty.String), + }), + cty.ObjectVal(map[string]cty.Value{ + "val0": cty.StringVal("dynamic c 1"), + "val1": cty.NullVal(cty.String), + }), + }), + cty.ListVal([]cty.Value{ + cty.ObjectVal(map[string]cty.Value{ + "val0": cty.StringVal("static c 1"), + "val1": cty.StringVal("dynamic b 0"), + }), + cty.ObjectVal(map[string]cty.Value{ + "val0": cty.StringVal("dynamic c 2"), + "val1": cty.StringVal("dynamic b 0"), + }), + cty.ObjectVal(map[string]cty.Value{ + "val0": cty.StringVal("dynamic c 3"), + "val1": cty.StringVal("dynamic b 0"), + }), + }), + cty.ListVal([]cty.Value{ + cty.ObjectVal(map[string]cty.Value{ + "val0": cty.StringVal("static c 1"), + "val1": cty.StringVal("dynamic b 1"), + }), + cty.ObjectVal(map[string]cty.Value{ + "val0": cty.StringVal("dynamic c 2"), + "val1": cty.StringVal("dynamic b 1"), + }), + cty.ObjectVal(map[string]cty.Value{ + "val0": cty.StringVal("dynamic c 3"), + "val1": cty.StringVal("dynamic b 1"), + }), + }), + cty.ListVal([]cty.Value{ + cty.ObjectVal(map[string]cty.Value{ + "val0": cty.StringVal("dynamic c nested 0"), + "val1": cty.StringVal("foo"), + }), + cty.ObjectVal(map[string]cty.Value{ + "val0": cty.StringVal("dynamic c nested 1"), + "val1": cty.StringVal("foo"), + }), + }), + }) + + if !got.RawEquals(want) { + t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, want) + } + }) + +} diff --git a/terraform/tfhcl/expand_spec.go b/terraform/tfhcl/expand_spec.go new file mode 100644 index 000000000..4dbee278a --- /dev/null +++ b/terraform/tfhcl/expand_spec.go @@ -0,0 +1,343 @@ +package tfhcl + +import ( + "fmt" + + "github.com/hashicorp/hcl/v2" + "github.com/terraform-linters/tflint/terraform/tfdiags" + "github.com/zclconf/go-cty/cty" + "github.com/zclconf/go-cty/cty/convert" + "github.com/zclconf/go-cty/cty/gocty" +) + +type expandDynamicSpec struct { + blockType string + blockTypeRange hcl.Range + defRange hcl.Range + forEachVal cty.Value + iteratorName string + labelExprs []hcl.Expression + contentBody hcl.Body +} + +func (b *expandBody) decodeDynamicSpec(blockS *hcl.BlockHeaderSchema, rawSpec *hcl.Block) (*expandDynamicSpec, hcl.Diagnostics) { + var diags hcl.Diagnostics + + var schema *hcl.BodySchema + if len(blockS.LabelNames) != 0 { + schema = dynamicBlockBodySchemaLabels + } else { + schema = dynamicBlockBodySchemaNoLabels + } + + specContent, specDiags := rawSpec.Body.Content(schema) + diags = append(diags, specDiags...) + if specDiags.HasErrors() { + return nil, diags + } + + //// for_each attribute + + eachAttr := specContent.Attributes["for_each"] + eachVal, eachDiags := eachAttr.Expr.Value(b.ctx) + diags = append(diags, eachDiags...) + + if !eachVal.CanIterateElements() && eachVal.Type() != cty.DynamicPseudoType { + // We skip this error for DynamicPseudoType because that means we either + // have a null (which is checked immediately below) or an unknown + // (which is handled in the expandBody Content methods). + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid dynamic for_each value", + Detail: fmt.Sprintf("Cannot use a %s value in for_each. An iterable collection is required.", eachVal.Type().FriendlyName()), + Subject: eachAttr.Expr.Range().Ptr(), + Expression: eachAttr.Expr, + EvalContext: b.ctx, + }) + return nil, diags + } + if eachVal.IsNull() { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid dynamic for_each value", + Detail: "Cannot use a null value in for_each.", + Subject: eachAttr.Expr.Range().Ptr(), + Expression: eachAttr.Expr, + EvalContext: b.ctx, + }) + return nil, diags + } + + //// iterator attribute + + iteratorName := blockS.Type + if iteratorAttr := specContent.Attributes["iterator"]; iteratorAttr != nil { + itTraversal, itDiags := hcl.AbsTraversalForExpr(iteratorAttr.Expr) + diags = append(diags, itDiags...) + if itDiags.HasErrors() { + return nil, diags + } + + if len(itTraversal) != 1 { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid dynamic iterator name", + Detail: "Dynamic iterator must be a single variable name.", + Subject: itTraversal.SourceRange().Ptr(), + }) + return nil, diags + } + + iteratorName = itTraversal.RootName() + } + + var labelExprs []hcl.Expression + if labelsAttr := specContent.Attributes["labels"]; labelsAttr != nil { + var labelDiags hcl.Diagnostics + labelExprs, labelDiags = hcl.ExprList(labelsAttr.Expr) + diags = append(diags, labelDiags...) + if labelDiags.HasErrors() { + return nil, diags + } + + if len(labelExprs) > len(blockS.LabelNames) { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Extraneous dynamic block label", + Detail: fmt.Sprintf("Blocks of type %q require %d label(s).", blockS.Type, len(blockS.LabelNames)), + Subject: labelExprs[len(blockS.LabelNames)].Range().Ptr(), + }) + return nil, diags + } else if len(labelExprs) < len(blockS.LabelNames) { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Insufficient dynamic block labels", + Detail: fmt.Sprintf("Blocks of type %q require %d label(s).", blockS.Type, len(blockS.LabelNames)), + Subject: labelsAttr.Expr.Range().Ptr(), + }) + return nil, diags + } + } + + // Since our schema requests only blocks of type "content", we can assume + // that all entries in specContent.Blocks are content blocks. + if len(specContent.Blocks) == 0 { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Missing dynamic content block", + Detail: "A dynamic block must have a nested block of type \"content\" to describe the body of each generated block.", + Subject: &specContent.MissingItemRange, + }) + return nil, diags + } + if len(specContent.Blocks) > 1 { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Extraneous dynamic content block", + Detail: "Only one nested content block is allowed for each dynamic block.", + Subject: &specContent.Blocks[1].DefRange, + }) + return nil, diags + } + + return &expandDynamicSpec{ + blockType: blockS.Type, + blockTypeRange: rawSpec.LabelRanges[0], + defRange: rawSpec.DefRange, + forEachVal: eachVal, + iteratorName: iteratorName, + labelExprs: labelExprs, + contentBody: specContent.Blocks[0].Body, + }, diags +} + +func (s *expandDynamicSpec) newBlock(i *dynamicIteration, ctx *hcl.EvalContext) (*hcl.Block, hcl.Diagnostics) { + var diags hcl.Diagnostics + var labels []string + var labelRanges []hcl.Range + lCtx := i.EvalContext(ctx) + for _, labelExpr := range s.labelExprs { + labelVal, labelDiags := labelExpr.Value(lCtx) + diags = append(diags, labelDiags...) + if labelDiags.HasErrors() { + return nil, diags + } + + var convErr error + labelVal, convErr = convert.Convert(labelVal, cty.String) + if convErr != nil { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid dynamic block label", + Detail: fmt.Sprintf("Cannot use this value as a dynamic block label: %s.", convErr), + Subject: labelExpr.Range().Ptr(), + Expression: labelExpr, + EvalContext: lCtx, + }) + return nil, diags + } + if labelVal.IsNull() { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid dynamic block label", + Detail: "Cannot use a null value as a dynamic block label.", + Subject: labelExpr.Range().Ptr(), + Expression: labelExpr, + EvalContext: lCtx, + }) + return nil, diags + } + if !labelVal.IsKnown() { + return nil, diags + } + if labelVal.IsMarked() { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid dynamic block label", + Detail: "Cannot use a marked value as a dynamic block label.", + Subject: labelExpr.Range().Ptr(), + Expression: labelExpr, + EvalContext: lCtx, + }) + return nil, diags + } + + labels = append(labels, labelVal.AsString()) + labelRanges = append(labelRanges, labelExpr.Range()) + } + + block := &hcl.Block{ + Type: s.blockType, + TypeRange: s.blockTypeRange, + Labels: labels, + LabelRanges: labelRanges, + DefRange: s.defRange, + Body: s.contentBody, + } + + return block, diags +} + +type expandMetaArgSpec struct { + rawBlock *hcl.Block + countSet bool + countVal cty.Value + countNum int + forEachSet bool + forEachVal cty.Value +} + +func (b *expandBody) decodeMetaArgSpec(rawSpec *hcl.Block) (*expandMetaArgSpec, hcl.Diagnostics) { + spec := &expandMetaArgSpec{rawBlock: rawSpec} + var diags hcl.Diagnostics + + specContent, _, specDiags := rawSpec.Body.PartialContent(expandableBlockBodySchema) + diags = append(diags, specDiags...) + if specDiags.HasErrors() { + return spec, diags + } + + //// count attribute + + if countAttr, exists := specContent.Attributes["count"]; exists { + spec.countSet = true + + countVal, countDiags := countAttr.Expr.Value(b.ctx) + diags = append(diags, countDiags...) + countVal, _ = countVal.Unmark() + + spec.countVal = countVal + + // We skip validation for count attribute if the value is unknwon + if countVal.IsKnown() { + if countVal.IsNull() { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid count argument", + Detail: `The given "count" argument value is null. An integer is required.`, + Subject: countAttr.Expr.Range().Ptr(), + Expression: countAttr.Expr, + EvalContext: b.ctx, + }) + return spec, diags + } + + var convErr error + countVal, convErr = convert.Convert(countVal, cty.Number) + if convErr != nil { + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Incorrect value type", + Detail: fmt.Sprintf("Invalid expression value: %s.", tfdiags.FormatError(convErr)), + Subject: countAttr.Expr.Range().Ptr(), + Expression: countAttr.Expr, + EvalContext: b.ctx, + }) + return spec, diags + } + + err := gocty.FromCtyValue(countVal, &spec.countNum) + if err != nil { + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid count argument", + Detail: fmt.Sprintf(`The given "count" argument value is unsuitable: %s.`, err), + Subject: countAttr.Expr.Range().Ptr(), + Expression: countAttr.Expr, + EvalContext: b.ctx, + }) + return spec, diags + } + if spec.countNum < 0 { + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid count argument", + Detail: `The given "count" argument value is unsuitable: negative numbers are not supported.`, + Subject: countAttr.Expr.Range().Ptr(), + Expression: countAttr.Expr, + EvalContext: b.ctx, + }) + return spec, diags + } + } + } + + //// for_each attribute + + if eachAttr, exists := specContent.Attributes["for_each"]; exists { + spec.forEachSet = true + + eachVal, eachDiags := eachAttr.Expr.Value(b.ctx) + diags = append(diags, eachDiags...) + + spec.forEachVal = eachVal + + if !eachVal.CanIterateElements() && eachVal.Type() != cty.DynamicPseudoType { + // We skip this error for DynamicPseudoType because that means we either + // have a null (which is checked immediately below) or an unknown + // (which is handled in the expandBody Content methods). + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "The `for_each` value is not iterable", + Detail: fmt.Sprintf("`%s` is not iterable", eachVal.GoString()), + Subject: eachAttr.Expr.Range().Ptr(), + Expression: eachAttr.Expr, + EvalContext: b.ctx, + }) + return spec, diags + } + if eachVal.IsNull() { + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid for_each argument", + Detail: `The given "for_each" argument value is unsuitable: the given "for_each" argument value is null. A map, or set of strings is allowed.`, + Subject: eachAttr.Expr.Range().Ptr(), + Expression: eachAttr.Expr, + EvalContext: b.ctx, + }) + return spec, diags + } + } + + return spec, diags +} diff --git a/terraform/tfhcl/expr_wrap.go b/terraform/tfhcl/expr_wrap.go new file mode 100644 index 000000000..1843e4aef --- /dev/null +++ b/terraform/tfhcl/expr_wrap.go @@ -0,0 +1,46 @@ +package tfhcl + +import ( + "github.com/hashicorp/hcl/v2" + "github.com/zclconf/go-cty/cty" +) + +type exprWrap struct { + hcl.Expression + di *dynamicIteration + mi *metaArgIteration +} + +func (e exprWrap) Variables() []hcl.Traversal { + raw := e.Expression.Variables() + if e.di == nil { + return raw + } + ret := make([]hcl.Traversal, 0, len(raw)) + + // Filter out traversals that refer to our dynamic iterator name or any + // iterator we've inherited; we're going to provide those in + // our Value wrapper, so the caller doesn't need to know about them. + for _, traversal := range raw { + rootName := traversal.RootName() + if rootName == e.di.IteratorName { + continue + } + if _, inherited := e.di.Inherited[rootName]; inherited { + continue + } + ret = append(ret, traversal) + } + return ret +} + +func (e exprWrap) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { + extCtx := e.di.EvalContext(e.mi.EvalContext(ctx)) + return e.Expression.Value(extCtx) +} + +// UnwrapExpression returns the expression being wrapped by this instance. +// This allows the original expression to be recovered by hcl.UnwrapExpression. +func (e exprWrap) UnwrapExpression() hcl.Expression { + return e.Expression +} diff --git a/terraform/tfhcl/iteration.go b/terraform/tfhcl/iteration.go new file mode 100644 index 000000000..e96dabb0b --- /dev/null +++ b/terraform/tfhcl/iteration.go @@ -0,0 +1,103 @@ +package tfhcl + +import ( + "github.com/hashicorp/hcl/v2" + "github.com/zclconf/go-cty/cty" +) + +type dynamicIteration struct { + IteratorName string + Key cty.Value + Value cty.Value + Inherited map[string]*dynamicIteration +} + +func (i *dynamicIteration) Object() cty.Value { + return cty.ObjectVal(map[string]cty.Value{ + "key": i.Key, + "value": i.Value, + }) +} + +func (i *dynamicIteration) EvalContext(base *hcl.EvalContext) *hcl.EvalContext { + new := base.NewChild() + + if i != nil { + new.Variables = map[string]cty.Value{} + for name, otherIt := range i.Inherited { + new.Variables[name] = otherIt.Object() + } + new.Variables[i.IteratorName] = i.Object() + } + + return new +} + +func (i *dynamicIteration) MakeChild(iteratorName string, key, value cty.Value) *dynamicIteration { + if i == nil { + // Create entirely new root iteration, then + return &dynamicIteration{ + IteratorName: iteratorName, + Key: key, + Value: value, + } + } + + inherited := map[string]*dynamicIteration{} + for name, otherIt := range i.Inherited { + inherited[name] = otherIt + } + inherited[i.IteratorName] = i + return &dynamicIteration{ + IteratorName: iteratorName, + Key: key, + Value: value, + Inherited: inherited, + } +} + +type metaArgIteration struct { + Count bool + Index cty.Value + + ForEach bool + Key cty.Value + Value cty.Value +} + +func MakeCountIteration(index cty.Value) *metaArgIteration { + return &metaArgIteration{ + Count: true, + Index: index, + } +} + +func MakeForEachIteration(key, value cty.Value) *metaArgIteration { + return &metaArgIteration{ + ForEach: true, + Key: key, + Value: value, + } +} + +func (i *metaArgIteration) EvalContext(base *hcl.EvalContext) *hcl.EvalContext { + new := base.NewChild() + + if i != nil { + new.Variables = map[string]cty.Value{} + + if i.Count { + new.Variables["count"] = cty.ObjectVal(map[string]cty.Value{ + "index": i.Index, + }) + } + if i.ForEach { + new.Variables["each"] = cty.ObjectVal(map[string]cty.Value{ + "key": i.Key, + "value": i.Value, + }) + } + } + + return new +} diff --git a/terraform/tfhcl/public.go b/terraform/tfhcl/public.go new file mode 100644 index 000000000..220a0e52f --- /dev/null +++ b/terraform/tfhcl/public.go @@ -0,0 +1,25 @@ +// Package tfhcl is a fork of hcl/ext/dynblock. +// Like dynblock, it supports dynamic block expansion, but also resource +// expansion via count/for_each meta-arguments. +// This package is defined separately from hclext because meta-arguments +// are a Terraform concern. +package tfhcl + +import "github.com/hashicorp/hcl/v2" + +// Expand "dynamic" blocks and count/for_for_each meta-arguments resources +// in the given body, returning a new body that has those blocks expanded. +// +// The given EvalContext is used when evaluating attributes within the given +// body. If the body has a dynamic block or an expandable resource, its +// contents are evaluated immediately. +// +// Expand returns no diagnostics because no blocks are actually expanded +// until a call to Content or PartialContent on the returned body, which +// will then expand only the blocks selected by the schema. +func Expand(body hcl.Body, ctx *hcl.EvalContext) hcl.Body { + return &expandBody{ + original: body, + ctx: ctx, + } +} diff --git a/terraform/tfhcl/schema.go b/terraform/tfhcl/schema.go new file mode 100644 index 000000000..86c0fa024 --- /dev/null +++ b/terraform/tfhcl/schema.go @@ -0,0 +1,63 @@ +package tfhcl + +import "github.com/hashicorp/hcl/v2" + +var dynamicBlockHeaderSchema = hcl.BlockHeaderSchema{ + Type: "dynamic", + LabelNames: []string{"type"}, +} + +var dynamicBlockBodySchemaLabels = &hcl.BodySchema{ + Attributes: []hcl.AttributeSchema{ + { + Name: "for_each", + Required: true, + }, + { + Name: "iterator", + Required: false, + }, + { + Name: "labels", + Required: true, + }, + }, + Blocks: []hcl.BlockHeaderSchema{ + { + Type: "content", + LabelNames: nil, + }, + }, +} + +var dynamicBlockBodySchemaNoLabels = &hcl.BodySchema{ + Attributes: []hcl.AttributeSchema{ + { + Name: "for_each", + Required: true, + }, + { + Name: "iterator", + Required: false, + }, + }, + Blocks: []hcl.BlockHeaderSchema{ + { + Type: "content", + LabelNames: nil, + }, + }, +} + +var expandableBlockBodySchema = &hcl.BodySchema{ + Attributes: []hcl.AttributeSchema{ + { + Name: "count", + Required: false, + }, + { + Name: "for_each", + Required: false, + }, + }, +} diff --git a/terraform/tfhcl/variables_hclext.go b/terraform/tfhcl/variables_hclext.go new file mode 100644 index 000000000..994650b25 --- /dev/null +++ b/terraform/tfhcl/variables_hclext.go @@ -0,0 +1,65 @@ +package tfhcl + +import ( + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/ext/dynblock" + "github.com/terraform-linters/tflint-plugin-sdk/hclext" +) + +// ExpandVariablesHCLExt is a wrapper around dynblock.WalkVariables that +// uses the given hclext.BodySchema to automatically drive the recursive +// walk through nested blocks in the given body. +// +// Note that it's a wrapper around ExpandVariables, not WalkExpandVariables. +// This package evaluates expressions immediately on expansion, so we always +// need all variables to expand. It also implicitly walks count/for_each to +// support expansion by meta-arguments. +func ExpandVariablesHCLExt(body hcl.Body, schema *hclext.BodySchema) []hcl.Traversal { + rootNode := dynblock.WalkVariables(body) + return walkVariablesWithHCLExt(rootNode, schema) +} + +func walkVariablesWithHCLExt(node dynblock.WalkVariablesNode, schema *hclext.BodySchema) []hcl.Traversal { + vars, children := node.Visit(extendSchema(asHCLSchema(schema))) + + if len(children) > 0 { + childSchemas := childBlockTypes(schema) + for _, child := range children { + if childSchema, exists := childSchemas[child.BlockTypeName]; exists { + vars = append(vars, walkVariablesWithHCLExt(child.Node, childSchema.Body)...) + } + } + } + + return vars +} + +func asHCLSchema(in *hclext.BodySchema) *hcl.BodySchema { + out := &hcl.BodySchema{} + if in == nil || in.Mode == hclext.SchemaJustAttributesMode { + return out + } + + out.Attributes = make([]hcl.AttributeSchema, len(in.Attributes)) + for idx, attr := range in.Attributes { + out.Attributes[idx] = hcl.AttributeSchema{Name: attr.Name, Required: attr.Required} + } + out.Blocks = make([]hcl.BlockHeaderSchema, len(in.Blocks)) + for idx, block := range in.Blocks { + out.Blocks[idx] = hcl.BlockHeaderSchema{Type: block.Type, LabelNames: block.LabelNames} + } + return out +} + +func extendSchema(schema *hcl.BodySchema) *hcl.BodySchema { + schema.Attributes = append(schema.Attributes, hcl.AttributeSchema{Name: "count"}, hcl.AttributeSchema{Name: "for_each"}) + return schema +} + +func childBlockTypes(schema *hclext.BodySchema) map[string]hclext.BlockSchema { + ret := make(map[string]hclext.BlockSchema) + for _, block := range schema.Blocks { + ret[block.Type] = block + } + return ret +} diff --git a/tflint/runner.go b/tflint/runner.go index 78ec9616a..9008201c3 100644 --- a/tflint/runner.go +++ b/tflint/runner.go @@ -117,7 +117,7 @@ func NewModuleRunners(parent *Runner) ([]*Runner, error) { modVars := map[string]*moduleVariable{} inputs := terraform.InputValues{} for varName, attribute := range body.Attributes { - val, diags := parent.Ctx.EvaluateExpr(attribute.Expr, cty.DynamicPseudoType, terraform.EvalDataForNoInstanceKey) + val, diags := parent.Ctx.EvaluateExpr(attribute.Expr, cty.DynamicPseudoType) if diags.HasErrors() { err := fmt.Errorf( "failed to eval an expression in %s:%d; %w", diff --git a/tflint/runner_test.go b/tflint/runner_test.go index f95ffc6a8..b8fd39d58 100644 --- a/tflint/runner_test.go +++ b/tflint/runner_test.go @@ -277,7 +277,7 @@ func Test_NewModuleRunners_withInvalidExpression(t *testing.T) { _, err := NewModuleRunners(runner) - expected := errors.New(`failed to eval an expression in module.tf:4; module.tf:4,16-29: Invalid "terraform" attribute; The terraform.env attribute was deprecated in v0.10 and removed in v0.12. The "state environment" concept was renamed to "workspace" in v0.12, and so the workspace name can now be accessed using the terraform.workspace attribute.`) + expected := errors.New(`module.tf:4,16-29: Invalid "terraform" attribute; The terraform.env attribute was deprecated in v0.10 and removed in v0.12. The "state environment" concept was renamed to "workspace" in v0.12, and so the workspace name can now be accessed using the terraform.workspace attribute.`) if err == nil { t.Fatal("an error was expected to occur, but it did not") }