Skip to content

Instantly share code, notes, and snippets.

@matthewdowney
Created August 10, 2022 22:32
Show Gist options
  • Save matthewdowney/234a97adc6dbfe6259a80788ab52b6c0 to your computer and use it in GitHub Desktop.
Save matthewdowney/234a97adc6dbfe6259a80788ab52b6c0 to your computer and use it in GitHub Desktop.
Clojure: deploy an AWS API Gateway endpoint with a VPC private link to a Fargate task using the CDK.
(ns deploy
(:import (software.amazon.awscdk App CfnOutput$Builder Stack)
(software.amazon.awscdk.services.apigatewayv2.alpha AddRoutesOptions HttpApi$Builder HttpMethod)
(software.amazon.awscdk.services.apigatewayv2.authorizers.alpha HttpIamAuthorizer)
(software.amazon.awscdk.services.apigatewayv2.integrations.alpha HttpAlbIntegration)
(software.amazon.awscdk.services.ec2 Vpc$Builder)
(software.amazon.awscdk.services.ecs Cluster$Builder ContainerImage)
(software.amazon.awscdk.services.ecs.patterns ApplicationLoadBalancedFargateService$Builder ApplicationLoadBalancedTaskImageOptions)
(software.amazon.awscdk.services.iam AnyPrincipal)))
(def app (App.))
(def stack (Stack. app "TestStack"))
;; VPC + ECS cluster to run a fargate task
(def vpc (-> (Vpc$Builder/create stack "vpc") (.maxAzs 3) (.natGateways 1) .build))
(def ecs-cluster (-> (Cluster$Builder/create stack "ecs-cluster") (.vpc vpc) .build))
(def fargate-service
(let [docker-image (-> (ApplicationLoadBalancedTaskImageOptions/builder)
(.image (ContainerImage/fromAsset "server"))
(.enableLogging true)
.build)]
(-> (ApplicationLoadBalancedFargateService$Builder/create stack "fargate-service")
(.cluster ecs-cluster)
(.taskImageOptions docker-image)
(.desiredCount 1)
(.cpu 256)
(.memoryLimitMiB 1024)
(.publicLoadBalancer false)
.build)))
;;; API Gateway + a route that points to the Fargate ALB (builds VPC Link automatically)
(def api-endpoint
(-> (HttpApi$Builder/create stack "HttpProxyPrivateAPI")
(.defaultAuthorizer (HttpIamAuthorizer.))
.build))
(def default-route
(-> (AddRoutesOptions/builder)
(.integration (HttpAlbIntegration. "DefaultIntegration" (.getListener fargate-service)))
(.path "/{proxy+}")
(.methods [(HttpMethod/ANY)])
.build))
;; Add the route to the API and grant access to any IAM users in this account
(let [route (first (.addRoutes api-endpoint default-route))]
(.grantInvoke route (AnyPrincipal.)))
;; Add the URL to the outputs
(-> (CfnOutput$Builder/create stack "apiGatewayURL")
(.value (.getUrl api-endpoint))
(.description "The API gateway URL.")
(.exportName "apiGatewayURL")
.build)
(defn synth [& args]
(println "Synthesized to:" (.getDirectory (.synth app)))
(.getDirectory (.synth app)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment