Skip to content

Instantly share code, notes, and snippets.

@ghsatpute
Created October 17, 2023 08:39
Show Gist options
  • Save ghsatpute/0a2fab728a4cae493fcac1c91964b5df to your computer and use it in GitHub Desktop.
Save ghsatpute/0a2fab728a4cae493fcac1c91964b5df to your computer and use it in GitHub Desktop.

CloudFormation Template for ALB -> Target Group -> Lambda

Copied from here: https://gist.github.com/alexcasalboni/9f118ac10a59a5c4eb6bfd75d0a65773

AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Parameters:
  Subnets:
    Type: List<AWS::EC2::Subnet::Id>
  VpcId:
      Type: AWS::EC2::VPC::Id

Resources:

  myFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      # ... 
      # all the other properties here
      # ...
      
  myLoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Scheme: internet-facing 
      Subnets: !Ref Subnets      
      SecurityGroups: [!Ref mySecurityGroup]

  myTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    DependsOn: myLambdaPermission
    Properties:
      TargetType: lambda
      Targets:
        - Id: !GetAtt myFunction.Arn

  myHttpListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref myLoadBalancer
      Port: 80
      Protocol: HTTP
      DefaultActions:
        - TargetGroupArn: !Ref myTargetGroup
          Type: forward

  mySecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allow http on port 80
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0

  myLambdaPermission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !GetAtt myFunction.Arn
      Action: lambda:InvokeFunction
      Principal: elasticloadbalancing.amazonaws.com

Outputs:
  DNSName:
    Value: !GetAtt myLoadBalancer.DNSName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment