From d01f95ec8e4fd39750ad3f65885765623de8edd1 Mon Sep 17 00:00:00 2001
From: Ansgar Mertens <ansgar@hashicorp.com>
Date: Mon, 13 Dec 2021 15:52:02 +0100
Subject: [PATCH] fix(lib): make sure to resolve reference expression target

---
 packages/cdktf/lib/tfExpression.ts       |  2 +-
 packages/cdktf/test/tfExpression.test.ts | 15 ++++++++++++++-
 2 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/packages/cdktf/lib/tfExpression.ts b/packages/cdktf/lib/tfExpression.ts
index 5c0ad6cb1d..d45877091b 100644
--- a/packages/cdktf/lib/tfExpression.ts
+++ b/packages/cdktf/lib/tfExpression.ts
@@ -171,7 +171,7 @@ class PropertyAccess extends TFExpression {
       .map((a) => `[${a}]`) // property access
       .join("");
 
-    const expr = `${this.target}${serializedArgs}`;
+    const expr = `${this.resolveArg(context, this.target)}${serializedArgs}`;
 
     return this.isInnerTerraformExpression ? expr : `\${${expr}}`;
   }
diff --git a/packages/cdktf/test/tfExpression.test.ts b/packages/cdktf/test/tfExpression.test.ts
index 7705b93e37..da0f385fd8 100644
--- a/packages/cdktf/test/tfExpression.test.ts
+++ b/packages/cdktf/test/tfExpression.test.ts
@@ -1,4 +1,4 @@
-import { Token } from "../lib";
+import { Fn, Token } from "../lib";
 import {
   addOperation,
   andOperation,
@@ -44,6 +44,19 @@ test("propertyAccess renders correctly", () => {
   );
 });
 
+test("propertyAccess resolves target properly", () => {
+  expect(
+    resolveExpression(
+      propertyAccess(
+        Fn.tolist(ref("some_resource.my_resource.some_attribute_array")),
+        [0, "name"]
+      )
+    )
+  ).toMatchInlineSnapshot(
+    `"\${tolist(some_resource.my_resource.some_attribute_array)[0][\\"name\\"]}"`
+  );
+});
+
 test("conditional renders correctly", () => {
   expect(resolveExpression(conditional(true, 1, 0))).toMatchInlineSnapshot(
     `"\${true ? 1 : 0}"`