Reputation: 314
Is instantiating AwsProvider
mandatory in the example given below? If yes, why? If not, why?
Example is taken from official docs
import { Construct } from "constructs";
import { App, TerraformStack, TerraformOutput } from "cdktf";
import { AwsProvider } from "@cdktf/provider-aws/lib/provider";
import { Instance } from "@cdktf/provider-aws/lib/instance";
class MyStack extends TerraformStack {
constructor(scope: Construct, id: string) {
super(scope, id);
new AwsProvider(this, "AWS", {
region: "us-west-1",
});
const ec2Instance = new Instance(this, "compute", {
ami: "ami-01456a894f71116f2",
instanceType: "t2.micro",
});
new TerraformOutput(this, "public_ip", {
value: ec2Instance.publicIp,
});
}
}
const app = new App();
const stack = new MyStack(app, "aws_instance");
new RemoteBackend(stack, {
hostname: "app.terraform.io",
organization: "<YOUR_ORG>",
workspaces: {
name: "learn-cdktf",
},
});
app.synth();
Upvotes: 0
Views: 38
Reputation: 74564
CDK for Terraform is ultimately a tool for generating Terraform configuration files, and so your program exists to tell CDK for Terraform what it should generate.
In order to use the hashicorp/aws
provider you need to configure it using a provider configuration block, which would be written like this in the main Terraform language:
provider "aws" {
region = "us-west-1"
}
Calling new AwsProvider
with the arguments you describe tells CDK for Terraform that it should generate a block like the one I included above. If you didn't include that then you would have no configuration for this provider. That would be valid only if all of the information needed to configure the provider were available from ambient locations like environment variables or the AWS configuration file.
This is similar to how your call to new TerraformOutput
causes CDK for Terraform to generate an output "public_ip"
block in the resulting Terraform configuration.
The typical way to use the hashicorp/aws
provider is to provide its authentication credentials "ambiently" (via environment variables or configuration files) but to specify the target region in the configuration, because the region where your infrastructure objects are to be created must remain consistent across all uses of this Terraform configuration, whereas the authentication credentials naturally vary depending on who or what is running Terraform and where Terraform is running.
Therefore writing a provider "aws"
block containing a region
argument is the typical way to use this provider, even though technically it's possible to also specify the region using an environment variable if you want to.
Upvotes: 1