---
AWSTemplateFormatVersion: '2010-09-09'
Description: Handel-created Lambda function

Resources:
  Role:
    Type: AWS::IAM::Role
    Properties:
      RoleName: {{functionName}}
      Path: "/services/"
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Principal:
              Service:
              - "lambda.amazonaws.com"
            Action:
            - "sts:AssumeRole"
      {{#if permissionsBoundary}}
      PermissionsBoundary: {{permissionsBoundary}}
      {{/if}}
  Policy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: {{functionName}}
      Roles:
      - !Ref Role
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
        {{#each policyStatements}}
        - Effect: {{Effect}}
          Action:
          {{#each Action}}
          - '{{{this}}}'
          {{/each}}
          Resource:
          {{#each Resource}}
          - '{{{this}}}'
          {{/each}}
        {{/each}}
  Function:
    DependsOn:
    - Policy # Explicitly required for VPC lambdas, otherwise policy isn't ready and attached before Lambda creation
    Type: AWS::Lambda::Function
    Properties: 
      Code:
        S3Bucket: {{s3ArtifactBucket}}
        S3Key: {{s3ArtifactKey}}
      Description: {{description}}
      {{#if environmentVariables}}
      Environment:
        Variables:
          {{#each environmentVariables}}
          {{@key}}: {{this}}
          {{/each}}
      {{/if}}
      FunctionName: {{functionName}}
      Handler: {{handler}}
      MemorySize: {{memorySize}}
      Role: !GetAtt Role.Arn
      Runtime: {{runtime}}
      Timeout: {{timeout}}
      {{#if vpc}}
      VpcConfig:
        SecurityGroupIds: 
        {{#each vpcSecurityGroupIds}}
        - {{this}}
        {{/each}}
        SubnetIds: 
        {{#each vpcSubnetIds}}
        - {{this}}
        {{/each}}
      {{/if}}
      {{#if tags}}
      Tags:
      {{#each tags}}
      - Key: {{@key}}
        Value: {{this}}
      {{/each}}
      {{/if}}
      # No VPC support for now
Outputs:
  FunctionName:
    Description: The name of the function
    Value: !Ref Function
  FunctionArn:
    Description: The ARN of the function
    Value: 
      Fn::GetAtt: 
        - "Function"
        - "Arn"
