Convert Terraform reference output type in cdktf

614 Views Asked by At

I have two resources in TF that I linked.


        service_account = \
            ServiceAccount(tf_stack,
                           id='123',
                           description='',
                           name="service-account",
                           provider=cc_provider)

        api_key = ApiKey(tf_stack,
                         id='api-keys',
                         environment_id="env-xxxxx",
                         cluster_id="lkc-123123",
                         user_id=service_account.id,
                         provider=cc_provider)

The ServiceAccount.id is a string, but ApiKey.user_id is int. When running this I get a legit exception from cdktf for type mismatch when setting user_id on ApiKey object.

Is it possible to craft type conversion of those variables somehow? In plain TF it's not a problem as I'd use atoi for this. But my challenge to make it work with cdktf

2

There are 2 best solutions below

2
On

I think this should work:

        api_key = ApiKey(tf_stack,
                         id='api-keys',
                         environment_id="env-xxxxx",
                         cluster_id="lkc-123123",
                         user_id= "atoi(" + service_account.id + ")",
                         provider=cc_provider)

this would render the terraform file with atoi function and then it should work as it works with normal terraform.

0
On

Terraform CDK introduced Terraform Functions in 0.7, so you should be able to use Fn.tonumber now:

    service_account = \
        ServiceAccount(tf_stack,
                       id='123',
                       description='',
                       name="service-account",
                       provider=cc_provider)

    api_key = ApiKey(tf_stack,
                     id='api-keys',
                     environment_id="env-xxxxx",
                     cluster_id="lkc-123123",
                     user_id=Fn.tonumber(service_account.id),
                     provider=cc_provider)