• HashiCorp Developer

  • HashiCorp Cloud Platform
  • Terraform
  • Packer
  • Consul
  • Vault
  • Boundary
  • Nomad
  • Waypoint
  • Vagrant
Terraform
  • Install
  • Tutorials
    • About the Docs
    • Configuration Language
    • Terraform CLI
    • Terraform Cloud
    • Terraform Enterprise
    • CDK for Terraform
    • Provider Use
    • Plugin Development
    • Registry Publishing
    • Integration Program
  • Registry(opens in new tab)
  • Try Cloud(opens in new tab)
  • Sign up
Terraform Home

CDK for Terraform

Skip to main content
  • CDK for Terraform
  • Get Started
    • Architecture
    • HCL Interoperability
    • Constructs
    • Providers
    • Resources
    • Modules
    • Data Sources
    • Variables and Outputs
    • Functions
    • Iterators
    • Remote Backends
    • Aspects
    • Assets
    • Tokens
    • Stacks
  • Community
  • Telemetry

  • Resources

  • Tutorial Library
  • Certifications
  • Community Forum
    (opens in new tab)
  • Support
    (opens in new tab)
  • GitHub
    (opens in new tab)
  • Terraform Registry
    (opens in new tab)
  1. Developer
  2. Terraform
  3. CDK for Terraform
  4. Concepts
  5. Providers
  • CDK For Terraform
  • v0.14.x
  • v0.13.x
  • v0.12.x
  • v0.11.x
  • v0.10.x
  • v0.9.x
  • v0.8.x

»Providers

A provider is a plugin that lets Terraform manage an external API. In your CDK for Terraform (CDKTF) application, you use your preferred programming language to define the resources you want Terraform to manage on one or more providers.

You can install pre-built providers packaged with the required code bindings for your language or add providers to the cdktf.json file and generate code bindings manually. To use providers in your application, you can import them from the Terraform Registry or from your local machine.

What Are Providers?

Provider plugins like the AWS provider or the cloud-init provider act as a translation layer that allows Terraform to communicate with many different cloud providers, databases, and services.

diagram: How Terraform uses plugins

Terraform uses providers to provision resources, which describe one or more infrastructure objects like virtual networks and compute instances. Each provider on the Terraform Registry has documentation detailing available resources and their configuration options.

Install Pre-Built Providers

It can take several minutes for CDKTF to generate the code bindings for providers with very large schemas, so we offer several popular providers as pre-built packages. Pre-built providers are a completely optional performance optimization, and you may prefer to generate the code bindings for these providers yourself. For example, you may want to use a different version of that provider than the one in the pre-built package. The Terraform CDK Providers page has a complete list, but available pre-built providers include the following options:

  • AWS Provider
  • Google Provider
  • Azure Provider
  • Kubernetes Provider
  • Docker Provider
  • Github Provider
  • Null Provider

We regularly publish these packages to NPM / PyPi, and you can treat them like any other dependency. The following example shows how to install the AWS provider in TypeScript / Node.

npm install @cdktf/provider-aws

When you use npm install to install a pre-built provider, you should not define that provider again in your cdktf.json file. If you receive errors while running cdktf synth because of duplicate providers, remove the duplicates from your cdktf.json file, delete tsbuildinfo.json, and run cdktf synth again.

Add Providers with CLI

Use the provider add command to automatically install a pre-built provider if available. If a pre-built provider is not available, CDKTF uses local provider bindings.

Import Providers

CDK for Terraform lets you import Terraform providers to your project.

This TypeScript example project has a main.ts file that defines AWS resources.

import { Construct } from "constructs";
import { TerraformStack, Token } from "cdktf";
import { AwsProvider } from "@cdktf/provider-aws/lib/aws-provider";
import { Instance } from "@cdktf/provider-aws/lib/instance";

export class ProvidersStack extends TerraformStack {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    new AwsProvider(this, "aws", {
      region: "us-east-1",
    });

    const instance = new Instance(this, "Hello", {
      ami: "ami-2757f631",
      instanceType: "t2.micro",
    });
  }
}
import software.constructs.Construct;
import com.hashicorp.cdktf.App;
import com.hashicorp.cdktf.TerraformStack;
import imports.aws.provider.AwsProvider;
import imports.aws.provider.AwsProviderConfig;
import imports.aws.instance.Instance;
import imports.aws.instance.InstanceConfig;

public class MainImportProviders extends TerraformStack {

    public MainImportProviders(Construct scope, String id){
        super(scope, id);

        new AwsProvider(this, "aws", AwsProviderConfig.builder()
                .region("us-east-1")
                .build()
        );

        new Instance(this, "hello", InstanceConfig.builder()
                .ami("ami-2757f631")
                .instanceType("t2.micro")
                .build()
        );
    }

    public static void main(String[] args) {
        final App app = new App();
        new MainImportProviders(app, "hello-terraform");
        app.synth();
    }
}
from constructs import Construct
from cdktf import App, TerraformStack
from imports.aws.provider import AwsProvider
from imports.aws.instance import Instance

class SimpleProviderStack(TerraformStack):
    def __init__(self, scope: Construct, id: str):
        super().__init__(scope, id)

        AwsProvider(self, "aws",
            region = "us-east-1",
        )

        Instance(self, "hello",
            ami = "ami-2757f631",
            instance_type = "t2.micro",
        )

app = App()
SimpleProviderStack(app, "provider-stack")
app.synth()
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Constructs;
using HashiCorp.Cdktf;
using aws.Provider;
using aws.Instance;

namespace Examples
{
    class ProviderStack : TerraformStack
    {
        public ProviderStack(Construct scope, string name) : base(scope, name)
        {
            // Add this to your project's .csproj file:
            // <ItemGroup>
            //     <ProjectReference Include=".gen\aws\aws.csproj" />
            // </ItemGroup>

            new AwsProvider(this, "aws", new AwsProviderConfig
            {
                Region = "eu-central-1"
            });

            new Instance(this, "instance", new InstanceConfig
            {
                Ami = "ami-2757f631",
                InstanceType = "t2.micro"
            });
        }
    }
}
import (
    "os"

    "github.com/aws/constructs-go/constructs/v10"
    "github.com/aws/jsii-runtime-go"
    "github.com/hashicorp/terraform-cdk-go/cdktf"

    "github.com/hashicorp/terraform-cdk/examples/go/documentation/generated/hashicorp/aws/instance"
    aws "github.com/hashicorp/terraform-cdk/examples/go/documentation/generated/hashicorp/aws/provider"
)

func NewProvidersStack(scope constructs.Construct, name string) cdktf.TerraformStack {
    stack := cdktf.NewTerraformStack(scope, &name)

    aws.NewAwsProvider(stack, jsii.String("aws"), &aws.AwsProviderConfig{
        Region: jsii.String(("us-east-1")),
    })

    instance := instance.NewInstance(stack, jsii.String("hello"), &instance.InstanceConfig{
        Ami:          jsii.String("ami-2757f631"),
        InstanceType: jsii.String("t2.micro"),
    })
    return stack
}

Add Provider to cdktf.json

To use a new provider, first add it to the "terraformProviders" array in the cdktf.json file.

The following example adds the DNS Simple provider.

{
  "language": "typescript",
  "app": "npm run --silent compile && node main.js",
  "terraformProviders": ["aws@~> 2.0", "dnsimple/dnsimple"]
}

Generate Classes

Go to the working directory and run cdktf get to create the appropriate TypeScript classes for the provider automatically.

cdktf get
â ‹ downloading and generating providers...
Generated typescript constructs in the output directory: .gen

Import Classes

Import and use the generated classes in your application. The following example imports the DnsimpleProvider and Record resources from ./.gen/providers/dnsimple and defines them.

import { Construct } from "constructs";
import { TerraformStack, Token } from "cdktf";
import { AwsProvider } from "@cdktf/provider-aws/lib/aws-provider";
import { Instance } from "@cdktf/provider-aws/lib/instance";
import { DnsimpleProvider } from "@cdktf/provider-dnsimple/lib/provider";
import { Record } from "@cdktf/provider-dnsimple/lib/record";

export class ProvidersStack extends TerraformStack {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    new AwsProvider(this, "aws", {
      region: "us-east-1",
    });

    const instance = new Instance(this, "Hello", {
      ami: "ami-2757f631",
      instanceType: "t2.micro",
    });

    new DnsimpleProvider(this, "dnsimple", {
      token: Token.asString(process.env.DNSIMPLE_TOKEN),
      account: Token.asString(process.env.DNSIMPLE_ACCOUNT),
    });

    new Record(this, "web-www", {
      domain: "example.com",
      name: "web",
      value: instance.publicIp,
      type: "A",
    });
  }
}
import software.constructs.Construct;
import com.hashicorp.cdktf.App;
import com.hashicorp.cdktf.TerraformStack;
import com.hashicorp.cdktf.Token;
import imports.aws.instance.Instance;
import imports.aws.instance.InstanceConfig;
import imports.aws.provider.AwsProvider;
import imports.aws.provider.AwsProviderConfig;
import imports.dnsimple.provider.DnsimpleProvider;
import imports.dnsimple.provider.DnsimpleProviderConfig;
import imports.dnsimple.record.Record;
import imports.dnsimple.record.RecordConfig;

public class MainImportClasses extends TerraformStack {

    public MainImportClasses(Construct scope, String id){
        super(scope, id);

        new AwsProvider(this, "aws", AwsProviderConfig.builder()
                .region("us-east-1")
                .build()
        );

        Instance instance = new Instance(this, "Hello", InstanceConfig.builder()
                .ami("ami-2757f631")
                .instanceType("t2.micro")
                .build()
        );

        new DnsimpleProvider(this, "dnsimple", DnsimpleProviderConfig.builder()
                .token(Token.asString(System.getenv("DNSIMPLE_TOKEN")))
                .account(Token.asString(System.getenv("DNSIMPLE_ACCOUNT")))
                .build()
        );

        new Record(this, "web-www", RecordConfig.builder()
                .domain("example.com")
                .name("web")
                .value(instance.getPublicIp())
                .type("A")
                .build()
        );
    }

    public static void main(String[] args) {
        final App app = new App();
        new MainImportClasses(app, "hello-terraform");
        app.synth();
    }
}
import os
from constructs import Construct
from cdktf import App, TerraformStack, Token
from imports.aws.provider import AwsProvider
from imports.dnsimple.provider import DnsimpleProvider
from imports.dnsimple.record import Record

class ProviderStack(TerraformStack):
    def __init__(self, scope: Construct, id: str):
        super().__init__(scope, id)

        AwsProvider(self, "aws",
            region = "us-east-1",
        )

        instance = Instance(self, "Hello",
            ami = "ami-2757f631",
            instance_type = "t2.micro",
        )

        DnsimpleProvider(self, "dnsimple",
            token = Token.as_string(os.getenv("DNSIMPLE_TOKEN")),
            account = Token.as_string(os.getenv("DNSIMPLE_ACCOUNT")),
        )

        Record(self, "web-www",
            domain = "example.com",
            name = "web",
            value = instance.public_ip,
            type = "A"
        )

app = App()
ProviderStack(app, "provider-stack")
app.synth()
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Constructs;
using HashiCorp.Cdktf;
using aws.Provider;
using aws.Instance;
using dnsimple.Provider;
using dnsimple.Record;


namespace Examples
{
    class ProviderClassesStack : TerraformStack
    {
        public ProviderClassesStack(Construct scope, string name) : base(scope, name)
        {
            // Add this to your project's .csproj file:
            // <ItemGroup>
            //     <ProjectReference Include=".gen\aws\aws.csproj" />
            // </ItemGroup>
            // <ItemGroup>
            //     <ProjectReference Include=".gen\dnsimple\dnsimple.csproj" />
            // </ItemGroup>

            new AwsProvider(this, "aws", new AwsProviderConfig
            {
                Region = "eu-east-1"
            });

            Instance instance = new Instance(this, "instance", new InstanceConfig
            {
                Ami = "ami-2757f631",
                InstanceType = "t2.micro"
            });

            new DnsimpleProvider(this, "dnsimple", new DnsimpleProviderConfig
            {
                Token = Token.AsString(Environment.GetEnvironmentVariable("DNSIMPLE_TOKEN")),
                Account = Token.AsString(Environment.GetEnvironmentVariable("DNSIMPLE_ACCOUNT"))
            });

            new Record(this, "web-www", new RecordConfig
            {
                Domain = "example.com",
                Name = "web",
                Value = instance.PublicIp,
                Type = "A"
            });
        }
    }
}
import (
    "os"

    "github.com/aws/constructs-go/constructs/v10"
    "github.com/aws/jsii-runtime-go"
    "github.com/hashicorp/terraform-cdk-go/cdktf"

    dnsimple "github.com/hashicorp/terraform-cdk/examples/go/documentation/generated/dnsimple/dnsimple/provider"
    "github.com/hashicorp/terraform-cdk/examples/go/documentation/generated/dnsimple/dnsimple/record"

    "github.com/hashicorp/terraform-cdk/examples/go/documentation/generated/hashicorp/aws/instance"
    aws "github.com/hashicorp/terraform-cdk/examples/go/documentation/generated/hashicorp/aws/provider"
)

func NewProvidersStack(scope constructs.Construct, name string) cdktf.TerraformStack {
    stack := cdktf.NewTerraformStack(scope, &name)

    aws.NewAwsProvider(stack, jsii.String("aws"), &aws.AwsProviderConfig{
        Region: jsii.String(("us-east-1")),
    })

    instance := instance.NewInstance(stack, jsii.String("hello"), &instance.InstanceConfig{
        Ami:          jsii.String("ami-2757f631"),
        InstanceType: jsii.String("t2.micro"),
    })

    dnsimple.NewDnsimpleProvider(stack, jsii.String("dnsimple"), &dnsimple.DnsimpleProviderConfig{
        Token:   jsii.String(os.Getenv("DNSIMPLE_TOKEN")),
        Account: jsii.String(os.Getenv("DNSIMPLE_ACCOUNT")),
    })

    record.NewRecord(stack, jsii.String("web-www"), &record.RecordConfig{
        Domain: jsii.String("example.com"),
        Name:   jsii.String("web"),
        Value:  instance.PublicIp(),
        Type:   jsii.String("A"),
    })

    return stack
}

Use the synth command to convert your code into a JSON Terraform configuration file.

cdktf synth --json
{
  "//": {
    "metadata": {
      "version": "0.0.11-pre.8757404fa25b6e405f1a51eac11b96943ccb372e",
      "stackName": "vpc-example"
    }
  },
  "terraform": {
    "required_providers": {
      "aws": "~> 2.0",
      "dnsimple": "undefined"
    }
  },
  "provider": {
    "aws": [
      {
        "region": "us-east-1"
      }
    ],
    "dnsimple": [
      {
        "account": "hello@example.com",
        "token": "xxxxxxxxxx"
      }
    ]
  },
  "resource": {
    "aws_instance": {
      "vpcexample_Hello_279554CB": {
        "ami": "ami-2757f631",
        "instance_type": "t2.micro",
        "//": {
          "metadata": {
            "path": "vpc-example/Hello",
            "uniqueId": "vpcexample_Hello_279554CB",
            "stackTrace": [
              .....
            ]
          }
        }
      }
    },
    "dnsimple_record": {
      "vpcexample_webwww_477C7150": {
        "domain": "example.com",
        "name": "web",
        "type": "A",
        "value": "${aws_instance.vpcexample_Hello_279554CB.public_ip}",
        "//": {
          "metadata": {
            "path": "vpc-example/web-www",
            "uniqueId": "vpcexample_webwww_477C7150",
            "stackTrace": [
              .....
            ]
          }
        }
      }
    }
  }
}

Provider Caching

Caching prevents CDK for Terraform from re-downloading providers between each CLI command. It is also useful when you need to remove the cdktf.out folder and re-synthesize your configuration. Finally, caching is necessary when you use multiple stacks within one application.

Set the Caching Directory

Refer to the Terraform documentation about how to configure your plugin cache. Otherwise, CDKTF automatically sets the TF_PLUGIN_CACHE_DIR environment variable to $HOME/.terraform.d/plugin-cache when you use cdktf cli commands.

To disable this behavior, set CDKTF_DISABLE_PLUGIN_CACHE_ENV to a non null value, like CDKTF_DISABLE_PLUGIN_CACHE_ENV=1. You may want to do this when a different cache directory is configured via a .terraformrc configuration file.

Use a Local Provider

Terraform needs to know the location of local providers to enable CDKTF to generate the appropriate type bindings. You can configure this in two ways:

  • Implied Local Mirrors
  • Development Overrides

Once configured properly, you can reference these providers in the cdktf.json file the same way that you reference providers from the Terraform Registry. Refer to the project configuration documentation for more details about the cdktf.json specification.

Edit this page on GitHub

On this page

  1. Providers
  2. What Are Providers?
  3. Install Pre-Built Providers
  4. Add Providers with CLI
  5. Import Providers
  6. Provider Caching
  7. Use a Local Provider
Give Feedback(opens in new tab)
  • Certifications
  • System Status
  • Terms of Use
  • Security
  • Privacy
  • Trademark Policy
  • Trade Controls
  • Give Feedback(opens in new tab)