hashicorp / terraform-cdk

Define infrastructure resources using programming constructs and provision them using HashiCorp Terraform
https://www.terraform.io/cdktf
Mozilla Public License 2.0
4.89k stars 456 forks source link

(Concepts): new page to document Operators usage #2867

Open gmeligio opened 1 year ago

gmeligio commented 1 year ago

Description

I had an issue in the following snippet with mathematical expressions using values from a data source. The snippet already contains the solution using cdktf.Op.

I tried different ways to get defaultVcpus and using cdktf.Token but those didn't work and I was getting in totalCpu a big negative value, which is the internal Token representation . Then searching and reading a few issues to see if there were a similar one to mine, I found in #2557 that there is a cdktf.Op and that solved it.

It would be nice to have a documentation page about what Operators are, when to use them, and how they interact with Tokens.

const dataInstance = new aws.dataAwsEc2InstanceType.DataAwsEc2InstanceType(this, 'dataInstance', {
    instanceType: 't3a.medium',
  });

const totalCpu = cdktf.Op.mul(0.8, dataInstance.defaultVcpus);
const containerCpu = cdktf.Op.mul(0.45, totalCpu);

const threadCount = cdktf.Fn.ceil(cdktf.Token.asNumber(containerCpu));

Links

https://developer.hashicorp.com/terraform/cdktf

Help Wanted

Community Note

xiehan commented 1 year ago

Note that we do already have https://developer.hashicorp.com/terraform/cdktf/concepts/functions#operators but I agree it's worth expanding with at least a few more examples.

gmeligio commented 1 year ago

Thank you @xiehan. I was looking for an independent page like in the HCL docs and didn't find it on the Functions page.

It's OK where it is today in the link you shared.

If possible, I would like the new examples to showcase when Operators are the easiest or the only way to accomplish something, like their interaction with Token, instead of only showing the API syntax. Maybe something along the lines of my first comment could be used.

As it is right now, I read it like it covers an HCL feature but doesn't explain the difference with Typescript operators. An example of what I'm asking is this section that I read a lot when starting with Iterators https://developer.hashicorp.com/terraform/cdktf/concepts/iterators#when-to-use-iterators