From 788496ad44a0c3baca32ce659c7bbbc265dcac5a Mon Sep 17 00:00:00 2001 From: Daniel Schmidt Date: Thu, 21 Oct 2021 17:04:12 +0200 Subject: [PATCH] feat(lib): throw error when a token is used in a construct name Closes #1068 --- packages/cdktf/lib/terraform-resource.ts | 8 +++++++- packages/cdktf/lib/tokens/token.ts | 4 ++++ packages/cdktf/test/resource.test.ts | 18 ++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/cdktf/lib/terraform-resource.ts b/packages/cdktf/lib/terraform-resource.ts index 6b1fe87d99..d8ee397de9 100644 --- a/packages/cdktf/lib/terraform-resource.ts +++ b/packages/cdktf/lib/terraform-resource.ts @@ -1,5 +1,5 @@ import { Construct } from "constructs"; -import { Token } from "./tokens"; +import { Token, Tokenization } from "./tokens"; import { TerraformElement } from "./terraform-element"; import { TerraformProvider } from "./terraform-provider"; import { keysToSnakeCase, deepMerge } from "./util"; @@ -60,6 +60,12 @@ export class TerraformResource constructor(scope: Construct, id: string, config: TerraformResourceConfig) { super(scope, id); + if (Tokenization.containsToken(id)) { + throw new Error( + "You can not use a Token (e.g. a reference to an attribute) as name of a construct" + ); + } + this.terraformResourceType = config.terraformResourceType; this.terraformGeneratorMetadata = config.terraformGeneratorMetadata; if (Array.isArray(config.dependsOn)) { diff --git a/packages/cdktf/lib/tokens/token.ts b/packages/cdktf/lib/tokens/token.ts index 03534c6d0f..de4374cfd2 100644 --- a/packages/cdktf/lib/tokens/token.ts +++ b/packages/cdktf/lib/tokens/token.ts @@ -115,6 +115,10 @@ export class Tokenization { return []; } + public static containsToken(x: any): boolean { + return Tokenization.reverse(x).length > 0; + } + /** * Un-encode a string potentially containing encoded tokens */ diff --git a/packages/cdktf/test/resource.test.ts b/packages/cdktf/test/resource.test.ts index e022bffa95..bb2c27ea3e 100644 --- a/packages/cdktf/test/resource.test.ts +++ b/packages/cdktf/test/resource.test.ts @@ -160,3 +160,21 @@ test("numeric attributes", () => { expect(Testing.synth(stack)).toMatchSnapshot(); }); + +test("tokens as ids", () => { + const app = Testing.app(); + const stack = new TerraformStack(app, "test"); + new TestProvider(stack, "provider", {}); + + const foo = new TestResource(stack, "resource", { + name: "foo", + }); + + expect(() => { + new TestResource(stack, `resource-${foo.stringValue}`, { + name: "foo", + }); + }).toThrowErrorMatchingInlineSnapshot( + `"You can not use a Token (e.g. a reference to an attribute) as name of a construct"` + ); +});