Coder Social home page Coder Social logo

cdktf / cdktf-tf-module-stack Goto Github PK

View Code? Open in Web Editor NEW
19.0 2.0 2.0 1.62 MB

A drop-in replacement for cdktf.TerraformStack that lets you define Terraform modules as constructs

License: Mozilla Public License 2.0

TypeScript 95.72% HCL 1.77% Shell 2.51%
cdktf terraform terraform-module constructs

cdktf-tf-module-stack's Introduction

cdktf-tf-module-stack

Status: Tech Preview Releases LICENSE build

A drop-in replacement for cdktf.TerraformStack that lets you define Terraform modules as constructs.

cdktf-tf-module-stack is in technical preview, which means it's a community supported project. It still requires extensive testing and polishing to mature into a HashiCorp officially supported project. Please file issues generously and detail your experience while using the library. We welcome your feedback.

By using the software in this repository, you acknowledge that:

  • cdktf-tf-module-stack is still in development, may change, and has not been released as a commercial product by HashiCorp and is not currently supported in any way by HashiCorp.
  • cdktf-tf-module-stack is provided on an "as-is" basis, and may include bugs, errors, or other issues.
  • cdktf-tf-module-stack is NOT INTENDED FOR PRODUCTION USE, use of the Software may result in unexpected results, loss of data, or other unexpected results, and HashiCorp disclaims any and all liability resulting from use of cdktf-tf-module-stack.
  • HashiCorp reserves all rights to make all decisions about the features, functionality and commercial release (or non-release) of cdktf-tf-module-stack, at any time and without any obligation or liability whatsoever.

Compatibility

  • cdktf >= 0.20.0
  • constructs >= 10.0.25

Available Packages

NPM

The npm package is available at https://www.npmjs.com/package/@cdktf/tf-module-stack.

npm install @cdktf/tf-module-stack

NOTE: Originally, this package was named cdktf-tf-module-stack, and the legacy versions (<= 0.2.0) can be found on npm here.

PyPI

The PyPI package is available at https://pypi.org/project/cdktf-tf-module-stack.

pipenv install cdktf-tf-module-stack

Nuget

The Nuget package is available at https://www.nuget.org/packages/HashiCorp.Cdktf.TfModuleStack.

dotnet add package HashiCorp.Cdktf.TfModuleStack

Maven

The Maven package is available at https://mvnrepository.com/artifact/com.hashicorp/cdktf-tf-module-stack.

<dependency>
    <groupId>com.hashicorp</groupId>
    <artifactId>cdktf-tf-module-stack</artifactId>
    <version>[REPLACE WITH DESIRED VERSION]</version>
</dependency>

Go

The go package is generated into the github.com/cdktf/cdktf-tf-module-stack-go package.

go get github.com/cdktf/cdktf-tf-module-stack-go/tfmodulestack

Usage

Typescript

import { App } from "cdktf";
import {
  TFModuleStack,
  TFModuleVariable,
  TFModuleOutput,
  ProviderRequirement,
} from "@cdktf/tf-module-stack";
import { Resource } from '@cdktf/provider-null/lib/resource';

class MyAwesomeModule extends TFModuleStack {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    new ProviderRequirement(this, "null", "~> 2.0");
    const resource = new Resource(this, "resource");

    new TFModuleVariable(this, "my_var", {
      type: "string",
      description: "A variable",
      default: "default",
    });

    new TFModuleOutput(this, "my_output", {
      value: resource.id,
    });
  }
}

const app = new App();
new MyAwesomeModule(app, "my-awesome-module");
app.synth();

Python

from constructs import Construct
from cdktf import App, TerraformStack
from imports.null.resource import Resource
from cdktf_tf_module_stack import TFModuleStack, TFModuleVariable, TFModuleOutput, ProviderRequirement


class MyAwesomeModule(TFModuleStack):
    def __init__(self, scope: Construct, ns: str):
        super().__init__(scope, ns)

        ProviderRequirement(self, "null", provider_version_constraint="~> 2.0")

        TFModuleVariable(self, "my_var", type="string", description="A variable", default="default")

        resource = Resource(self, "resource")

        TFModuleOutput(self, "my_output", value=resource.id)


app = App()
MyAwesomeModule(app, "my-awesome-module")
app.synth()

This will synthesize a Terraform JSON file that looks like this:

{
  "output": {
    "my_output": [
      {
        "value": "${null_resource.resource.id}"
      }
    ]
  },
  "resource": {
    "null_resource": {
      "resource": {}
    }
  },
  "terraform": {
    "required_providers": {
      "null": {
        "source": "null",
        "version": "~> 2.0"
      }
    },
    "variable": {
      "my_var": {
        "default": "default",
        "description": "A variable",
        "type": "string"
      }
    }
  }
}

Please note that the provider section is missing, so that the Terraform Workspace using the generated module can be used with any provider matching the version.

cdktf-tf-module-stack's People

Contributors

ansgarm avatar danielmschmidt avatar shinebayar-g avatar team-tf-cdk avatar xiehan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

cdktf-tf-module-stack's Issues

Provider & Backend information is not removed in cdktf 0.20.0 --hcl output

Description

Using the following example

import { App } from 'cdktf';
import { Construct } from 'constructs';
import {
    TFModuleStack,
    TFModuleVariable,
    TFModuleOutput,
    ProviderRequirement,
} from '@cdktf/tf-module-stack';
import { Resource } from '@cdktf/provider-null/lib/resource';

class MyAwesomeModule extends TFModuleStack {
    constructor(scope: Construct, id: string) {
        super(scope, id);

        new ProviderRequirement(this, 'null', '~> 2.0');
        const resource = new Resource(this, 'resource');

        new TFModuleVariable(this, 'my_var', {
            type: 'string',
            description: 'A variable',
            default: 'default',
        });

        new TFModuleOutput(this, 'my_output', {
            value: resource.id,
        });
    }
}

const app = new App();
new MyAwesomeModule(app, 'my-awesome-module');
app.synth();

cdktf synth generates

cdktf-modules
├── cdktf.out
│   ├── manifest.json
│   └── stacks
│       └── my-awesome-module
│           └── cdk.tf.json
└── main.ts

cdk.tf.json content

{
  "//": {
    "metadata": {
      "backend": "local",
      "stackName": "my-awesome-module",
      "version": "0.20.0"
    },
    "outputs": {
      "my-awesome-module": {
        "my_output": "my_output"
      }
    }
  },
  "output": {
    "my_output": [
      {
        "value": "${null_resource.resource.id}"
      }
    ]
  },
  "resource": {
    "null_resource": {
      "resource": {
        "//": {
          "metadata": {
            "path": "my-awesome-module/resource",
            "uniqueId": "resource"
          }
        }
      }
    }
  },
  "terraform": {
    "required_providers": {
      "null": {
        "version": "~> 2.0"
      }
    }
  },
  "variable": {
    "my_var": [
      {
        "default": "default",
        "description": "A variable",
        "type": "string"
      }
    ]
  }
}

cdktf synth --hcl generates

cdktf-modules
├── cdktf.out
│   ├── manifest.json
│   └── stacks
│       └── my-awesome-module
│           ├── cdk.tf
│           └── metadata.json
└── main.ts

cdk.tf content

terraform {
  required_providers {
    null = {
      version = "~> 2.0"
    }
  }
  backend "local" {
    path = "/Users/Home/cdktf-modules/terraform.my-awesome-module.tfstate"
  }


}

provider "null" {
}
resource "null_resource" "resource" {
}

variable "my_var" {
  default     = "default"
  description = "A variable"
  type        = string
}

output "my_output" {
  value = "${null_resource.resource.id}"
}

metadata.json content

{
  "//": {
    "metadata": {
      "backend": "local",
      "stackName": "my-awesome-module",
      "version": "0.20.0"
    },
    "outputs": {
      "my-awesome-module": {
        "my_output": "my_output"
      }
    }
  },
  "resource": {
    "null_resource": {
      "resource": {
        "//": {
          "metadata": {
            "path": "my-awesome-module/resource",
            "uniqueId": "resource"
          }
        }
      }
    }
  },
  "terraform": {
    "backend": {
      "local": {
        "path": "/Users/Home/cdktf-modules/terraform.my-awesome-module.tfstate"
      }
    },
    "required_providers": {
      "null": {
        "version": "~> 2.0"
      }
    }
  }
}

Versions

language: typescript
cdktf-cli: 0.20.0
cdktf: 0.20.0
node: v20.10.0
constructs: 10.3.0
terraform: v1.3.7
arch: arm64
os: darwin 23.2.0

Providers

"@cdktf/provider-null": "10.0.0",
"@cdktf/tf-module-stack": "5.0.0"

Gist

No response

Possible Solutions

No response

Workarounds

No response

Anything Else?

Is metadata.json file needed? It looks identical to the previous json version.

References

No response

Help Wanted

  • I'm interested in contributing a fix myself

Community Note

  • Please vote on this issue by adding a 👍 reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or other comments that do not add relevant new information or questions, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

What is the exact difference between cdktf synth and this?

Description

Documentation at https://developer.hashicorp.com/terraform/cdktf/concepts/hcl-interoperability mentions just run cdktf synth, copy the cdktf.out/stacks/<stack-name>/cdktf.json. This works.

It's unclear why this repository exists and what is the difference between cdktf synth json output and this.

Could you explain the use case?

Links

https://developer.hashicorp.com/terraform/cdktf/concepts/hcl-interoperability
https://developer.hashicorp.com/terraform/cdktf/develop-custom-constructs/publishing-and-distribution

Help Wanted

  • I'm interested in contributing a fix myself

Community Note

  • Please vote on this issue by adding a 👍 reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or other comments that do not add relevant new information or questions, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

Trying to use an object as TFModuleVariable fails on synthetizing

Description

I have started using this project to build a module with CDKTF.

I have set up a CDKTF project which uses the CDKTF Module and it works fine with a basic test, even passing a variable with a TFModuleVariable.

Now I want to do a more complex use case, that would involve having a TFModuleVariable which would be a complex object. Then I want to loop over it, and that is what fails. My current CDKTF module code looks like this:

class GitHubModule extends TFModuleStack {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    new ProviderRequirement(this, "github", "6.0.0", "integrations/github")

    const memberships = new TFModuleVariable(this, "memberships", {
      description: "Admin and members of the organization",
      default: {
        admins: ["fake"],
        members: ["fake"]
      }
    })

    memberships.value.admins.forEach(function(user: string) {
      new Membership(scope, `github-membership-${user}", {
        username: user,
        role: "admin"
      })
    })
  }
}

And that fails with:

[ERROR] default - TypeError: Cannot read properties of undefined (reading ‘forEach’)

I understand that, at synth time the content is undefined and therefore it fails. But then, this does not allow to pass dynamic configurations like this? I tried adding default values so that it could have some value, but it still failed.

Versions

cdktf debug output:

language: typescript
cdktf-cli: 0.20.3
node: v18.17.1
cdktf: 0.20.4
constructs: 10.3.0
jsii: null
terraform: 1.7.2
arch: arm64
os: darwin 23.2.0
providers
integrations/[email protected] (LOCAL)
        terraform provider version: 6.0.0
@cdktf/provider-github (PREBUILT)
        terraform provider version: 6.0.0
        prebuilt provider version: 14.0.0
        cdktf version: ^0.20.0

Providers

No response

Gist

No response

Possible Solutions

No response

Workarounds

No response

Anything Else?

No response

References

No response

Help Wanted

  • I'm interested in contributing a fix myself

Community Note

  • Please vote on this issue by adding a 👍 reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or other comments that do not add relevant new information or questions, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

Undefined type in go package: AppOptions

The go package for this will not build due to an undefined type.

../../../../../../go/pkg/mod/github.com/cdktf/cdktf-tf-module-stack-go/[email protected]/tfmodulestack_TFModuleApp.go:96:36: undefined: cdktf.AppOptions
../../../../../../go/pkg/mod/github.com/cdktf/cdktf-tf-module-stack-go/[email protected]/tfmodulestack_TFModuleApp.go:113:60: undefined: cdktf.AppOptions
../../../../../../go/pkg/mod/github.com/cdktf/cdktf-tf-module-stack-go/[email protected]/tfmodulestack_TFModuleApp__runtime_type_checks.go:55:54: undefined: cdktf.AppOptions

Looking at the other language versions and the cdtkf, this should be cdktf.AppConfig, I believe.

How does one invoke a TFModuleStack within the context of other Stack and pass variables or retrieve outputs

Description

Per the documentation on the TFModuleStack its unclear how this is supposed to be used (as its aligns to regular TF modules) in the context of a Stack.

Since this construct allows is to declare variables (via TFModuleVariable declarations) and Outputs (via TFModuleOutput declarations) how is one intended to use them?

The examples indicate that they are included in the main entry point and are passed the "App" instance, but nothing to indicate how one passes the variables and handles outputs.

As aligned to a more conventional Terraform module (in HCL), these would be used as an alternate to regular CK Constructs and used in the context of the Stack.

Am I missing something ?

Links

https://github.com/cdktf/cdktf-tf-module-stack

Help Wanted

  • I'm interested in contributing a fix myself

Community Note

  • Please vote on this issue by adding a 👍 reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or other comments that do not add relevant new information or questions, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

Dummy name for provider requirement fails validation

Using the latest release of the module, I get this error when trying to synth:

│   on _providers.tf line 3, in terraform:
│   82:       "not_needed_in_this_case": {
│   83:         "source": "hashicorp/aws",
│   84:         "version": "> 4"
│   85:       }
│
│ not_needed_in_this_case is an invalid provider local name: must contain
│ only letters, digits, and dashes, and may not use leading or trailing
│ dashes

The definition for the requirement, inside a TFModuleStack, but not inside a TFModuleApp.

new ProviderRequirement(this, 'aws', '> 4', 'hashicorp/aws')

The offending code:

class ProviderRequirement extends cdktf_1.TerraformProvider {
    constructor(scope, providerName, providerVersionConstraint, terraformProviderSource) {
        super(scope, providerName, {
            terraformResourceType: "not_needed_in_this_case",
            terraformGeneratorMetadata: {
                providerName,
                providerVersionConstraint,
            },
            terraformProviderSource,
        });
    }
}

Replacing "not_needed_in_this_case" with providerName gets it past the error, but I'm not sure if there are going to be any complications from that.
The synthed code looks about right:

  "terraform": {
    "required_providers": {
      "aws": {
        "source": "hashicorp/aws",
        "version": "> 4"
      }
    }
  },

cdktf conditional statements and Aliased Provider requirement not synthesized correctly

Description

I have created a cdktf construct where ResourceGroup resource is created with name having conditional statement as follows:

let resGrp = new resourceGroup.ResourceGroup(this, "resGrp", {
                location: input.location,
                name: input.existingRgName == ""? `${input.namePrefix}-${input.appName}-${input.environmentName}-rg` : input.existingRgName,
                tags: input.tags,
                provider: input.provider
            });

But after synthesizing it removes conditional statement and generates following output:

{
    "azurerm_resource_group": {
      "static-app_resGrp_E3D22600": {
        "//": {
          "metadata": {
            "path": "az-static-app/static-app/resGrp",
            "uniqueId": "static-app_resGrp_E3D22600"
          }
        },
        "location": "${var.location}",
        "name": "${var.existingRgName}",
        "provider": "azurerm",
        "tags": "${var.tags}"
      }
    }

Also I have passed an Alias azurerm provider requirement, but after synthesis, it's not taking the alias name, instead just taking the name of the provider.

let azurermProvider = new ProviderRequirement(this, "azurerm", "~> 3.70.0", "hashicorp/azurerm");
let providerAlias = new TFModuleVariable(this, "providerAlias", {
      type: "string",
      default: ""    
    });
azurermProvider.alias = providerAlias.value;

Synthesized output:

"azurerm_resource_group": {
      "static-app_resGrp_E3D22600": {
        "//": {
          "metadata": {
            "path": "az-static-app/static-app/resGrp",
            "uniqueId": "static-app_resGrp_E3D22600"
          }
        },
        "location": "${var.location}",
        "name": "${var.existingRgName}",
        "provider": "azurerm",
        "tags": "${var.tags}"
      }
    }

Versions

language: null
cdktf-cli: 0.18.0
node: v18.17.1
terraform: 1.5.2
arch: x64
os: win32 10.0.19045

Providers

No response

Gist

No response

Possible Solutions

No response

Workarounds

No response

Anything Else?

No response

References

No response

Help Wanted

  • I'm interested in contributing a fix myself

Community Note

  • Please vote on this issue by adding a 👍 reaction to the original issue to help the community and maintainers prioritize this request
  • Please do not leave "+1" or other comments that do not add relevant new information or questions, they generate extra noise for issue followers and do not help prioritize the request
  • If you are interested in working on this issue or have submitted a pull request, please leave a comment

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.