Skip to content

Instantly share code, notes, and snippets.

@jcdan3
Last active November 27, 2021 13:31
Show Gist options
  • Save jcdan3/629df39853f3beae22b02d21ad984701 to your computer and use it in GitHub Desktop.
Save jcdan3/629df39853f3beae22b02d21ad984701 to your computer and use it in GitHub Desktop.
AWS infrastructure sample with cdktf
package main
import (
"encoding/json"
"github.com/aws/constructs-go/constructs/v10"
"github.com/aws/jsii-runtime-go"
"github.com/hashicorp/terraform-cdk-go/cdktf"
"github.com/jcdan3/cdktf-provider-aws-go"
"github.com/jcdan3/cdktf-provider-aws-go/iam"
"github.com/jcdan3/cdktf-provider-aws-go/lambdafunction"
"io/ioutil"
"path"
"runtime"
)
func findCDKTFRootDir() string {
_, mainFile, _, ok := runtime.Caller(0)
if !ok {
panic("could find file")
}
return path.Dir(mainFile)
}
func makeIAMRole(stack cdktf.TerraformStack) (iam.IamRole, error) {
policyFile := path.Join(findCDKTFRootDir(), "policies", "lambda_policy.json")
file, err := ioutil.ReadFile(policyFile)
if err != nil {
return nil, err
}
return iam.NewIamRole(stack, jsii.String(roleName), &iam.IamRoleConfig{
AssumeRolePolicy: jsii.String(string(file)),
Name: jsii.String("lambdaExecutionRole"),
}), nil
}
func NewMyStack(scope constructs.Construct, id string) cdktf.TerraformStack {
stack := cdktf.NewTerraformStack(scope, &id)
aws.NewAwsProvider(stack, jsii.String("aws"), &aws.AwsProviderConfig{
Region: jsii.String("us-west-1"),
})
//Creating the role
lambdaRole, err := makeIAMRole(stack)
if err != nil{
return nil
}
// here should be compiled binary
filename := path.Join(findCDKTFRootDir(), "bin", "main.zip")
// Creating the lambda
lambdafunction.NewLambdaFunction(stack, jsii.String("Terraform-LambdaFunction"), &lambdafunction.LambdaFunctionConfig{
FunctionName: jsii.String("Hello-world"),
Runtime: jsii.String("go1.x"),
Handler: jsii.String("main"),
Role: lambdaRole.Arn(),
Filename: &filename,
})
return stack
}
func main() {
app := cdktf.NewApp(nil)
NewMyStack(app, "CDKTF-tutorial")
app.Synth()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment