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.84k stars 450 forks source link

Use specific imports for used resources when converting #2647

Closed mutahhir closed 1 year ago

mutahhir commented 1 year ago

Currently convert generates a single import line per provider for typescript, something like so:

import * as aws from "../../.gen/providers/aws";

and then uses the following syntax for referencing resources / data sources:

    new aws.provider.AwsProvider(this, "aws", {

While this works fine for Typescript, it doesn't work for languages that don't allow * imports, like C#.

That import becomes:

using Gen.Providers.Aws;

and declaring the resource becomes:

            new aws.Provider.AwsProvider(this, "aws", new Struct

which does not work.

Apart from it being broken on C#, there are performance implications for doing a * import for large providers. Thus, this is a performance improvement as well.

            new aws.Provider.AwsProvider(this, "aws", new Struct
            {
// ...
            });
DanielMSchmidt commented 1 year ago

This is related to JSII not successfully compiling the intermediate TS code, once it compiles it the specific import (e.g. using Gen.Providers.Kubernetes;) is used. #2646 is the issue tracking this.

ansgarm commented 1 year ago

I just wanted to quickly note that the import seems to be still wrong (even after JSII resolves to the right structs) – I don't know how related that is exactly (i.e. whether the structs fix was supposed to fix the imports too) which is why I'm posting this message 😄

I just got the following code produced (with ^0.16.0-pre.89)

using Constructs;
using HashiCorp.Cdktf;
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
using Gen.Providers.Aws;
class MyConvertedCode : TerraformStack
{
    public MyConvertedCode(Construct scope, string name) : base(scope, name)
    {
        var awsS3BucketB = new S3Bucket.S3Bucket(this, "b", new S3BucketConfig {
            Bucket = "my-tf-test-bucket",
            Tags = new Dictionary<string, string> {
                { "Environment", "Dev" },
                { "Name", "My bucket" }
            }
        });
        new S3BucketAcl.S3BucketAcl(this, "example", new S3BucketAclConfig {
            Acl = "private",
            Bucket = awsS3BucketB.Id
        });
    }
}

which seems to have a wrong import (Gen.Providers.Aws).

github-actions[bot] commented 1 year ago

I'm going to lock this issue because it has been closed for 30 days. This helps our maintainers find and focus on the active issues. If you've found a problem that seems similar to this, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further.