AWSTemplateFormatVersion: 2010-09-09
Description: Launch Highly Available Active/Passive FortiProxy-VM cluster within your VPC
Metadata:
  'AWS::CloudFormation::Interface':
    ParameterGroups:
      - Label:
          default: VPC Configuration
        Parameters:
          - VPCID
          - VPCCIDR
          - PublicSubnet1
          - PublicSubnet1RouterIP
          - PrivateSubnet1
          - PrivateSubnet1RouterIP
      - Label:
          default: FortiProxy Instance Configuration
        Parameters:
          - AZForFXPA
          - FXPInstanceType
          - FortiProxyVersion
          - LicenseType
          - CIDRForFXPAccess
          - KeyPair
      - Label:
          default: FortiProxy IP Configuration
        Parameters:
          - IPAPublicSubnet1
          - IPAPrivateSubnet1
    ParameterLabels:
      FortiProxyVersion:
        default: FotiOS Version
Parameters:
  VPCID:
    Type: 'AWS::EC2::VPC::Id'
    Description: Enter the VPC CIDR that you are using
  VPCCIDR:
    Type: String
    Description: 'Enter the VPC CIDR of the above VPC. Ex: 10.0.0.0/16'
  AZForFXPA:
    Type: 'AWS::EC2::AvailabilityZone::Name'
    Description: Select the first AZ for FortiProxyA
  PublicSubnet1:
    Type: 'AWS::EC2::Subnet::Id'
    Description: Select the Public1 subnet
  IPAPublicSubnet1:
    Type: String
    Description: >-
      Indicate the IP of the interface of FXPA attached to public subnet1. Ex:
      10.0.1.12/24
  PublicSubnet1RouterIP:
    Type: String
    Default: 10.0.1.1
    Description: Provide the IP of the gateway for the public subnet1
  PrivateSubnet1:
    Type: 'AWS::EC2::Subnet::Id'
    Description: Select the private subnet1
  IPAPrivateSubnet1:
    Type: String
    Description: >-
      Indicate the IP of the interface of FXPA attached to private subnet1. Ex:
      10.0.2.12/24
  PrivateSubnet1RouterIP:
    Type: String
    Default: 10.0.2.1
    Description: Provide the IP of the gateway for the private subnet1
  FXPInstanceType:
    Type: String
    Default: c5.xlarge
    Description: Select the instance type for the FortiProxys
    AllowedValues:
      - c5.large
      - c5.xlarge
      - c5.2xlarge
      - c5.4xlarge
      - c5.9xlarge
      - m5.large
      - m5.xlarge
      - m5.2xlarge
      - m5.4xlarge
      - m5.9xlarge
  FortiProxyVersion:
    Type: String
    Default: 7.6.x
    Description: Select the verion of FortiProxyOS to use (latest GA AMI will be used)
    AllowedValues:
      - 7.0.x
      - 7.2.x
      - 7.4.x
      - 7.6.x
  LicenseType:
    Type: String
    Description: Select the license type for the FortiProxys
    AllowedValues:
      - BYOL
  CIDRForFXPAccess:
    Type: String
    Default: 0.0.0.0/0
    Description: Enter the CIDR from which FortiProxy instances need to be accessed from
  KeyPair:
    Type: 'AWS::EC2::KeyPair::KeyName'
    Description: Select the keypair for the FortiProxys
Mappings:
  FortiProxyAMISearchString:
    7.0.x:
      BYOL: FortiProxy-AWS *v7.0.**|7o0pk87hw95asmwl3610sidil
    7.2.x:
      BYOL: FortiProxy-AWS *v7.2.**|7o0pk87hw95asmwl3610sidil
    7.4.x:
      BYOL: FortiProxy-AWS *7.4.**|7o0pk87hw95asmwl3610sidil
    7.6.x:
      BYOL: FortiProxy-AWS *7.6.**|7o0pk87hw95asmwl3610sidil
Conditions: {}
Resources:
  InstanceRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - ec2.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      Policies:
        - PolicyName: ApplicationPolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - 'ec2:Describe*'
                  - 'ec2:AssociateAddress'
                  - 'ec2:AssignPrivateIpAddresses'
                  - 'ec2:UnassignPrivateIpAddresses'
                  - 'ec2:ReplaceRoute'
                  - 's3:GetObject'
                Resource: '*'
  InstanceProfile:
    Type: 'AWS::IAM::InstanceProfile'
    Properties:
      Path: /
      Roles:
        - !Ref InstanceRole
  FXPSecGrpBase:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      VpcId: !Ref VPCID
      GroupDescription: FXPSecGrp
      SecurityGroupIngress:
        - Description: Allow remote access to FXP
          IpProtocol: '-1'
          FromPort: 0
          ToPort: 65535
          CidrIp: !Ref CIDRForFXPAccess
        - Description: Allow local VPC access to FXP
          IpProtocol: '-1'
          FromPort: 0
          ToPort: 65535
          CidrIp: !Ref VPCCIDR
  FXPSecGrpFXPRule:
    Type: 'AWS::EC2::SecurityGroupIngress'
    Properties:
      GroupId: !Ref FXPSecGrpBase
      Description: Allow FXPs to access each other
      IpProtocol: '-1'
      FromPort: 0
      ToPort: 65535
      SourceSecurityGroupId: !Ref FXPSecGrpBase
  FXPA:
    Type: 'AWS::EC2::Instance'
    Properties:
      ImageId: !GetAtt RunImageFunction.ami
      InstanceType: !Ref FXPInstanceType
      IamInstanceProfile: !Ref InstanceProfile
      KeyName: !Ref KeyPair
      NetworkInterfaces:
        - NetworkInterfaceId: !Ref FXPAENI0
          DeviceIndex: '0'
        - NetworkInterfaceId: !Ref FXPAENI1
          DeviceIndex: '1'
      Tags:
        - Key: Name
          Value: !Join 
            - ''
            - - !Ref 'AWS::StackName'
              - '-FXPA'
      UserData: !Base64 
        'Fn::Join':
          - |+

          - - config system vdom-exception
            - edit 0
            - set object router.static
            - next
            - edit 0
            - set object system.interface
            - end
            - config system global
            - set hostname FXPA
            - end
            - config system interface
            - edit port1
            - set alias public
            - set mode static
            - !Join 
              - ''
              - - 'set ip '
                - !Ref IPAPublicSubnet1
            - set allowaccess ping https ssh
            - set mtu-override enable
            - set mtu 9001
            - next
            - edit port2
            - set alias private
            - set mode static
            - !Join 
              - ''
              - - 'set ip '
                - !Ref IPAPrivateSubnet1
            - set allowaccess ping https ssh
            - set mtu-override enable
            - set mtu 9001
            - next
            - end
            - config router static
            - edit 1
            - set device port1
            - !Join 
              - ''
              - - 'set gateway '
                - !Ref PublicSubnet1RouterIP
            - next
            - edit 2
            - !Join 
              - ''
              - - 'set dst '
                - !Ref VPCCIDR
            - set device port2
            - !Join 
              - ''
              - - 'set gateway '
                - !Ref PrivateSubnet1RouterIP
            - next
            - end
            - config firewall policy
            - edit 1
            - set name outbound-all
            - set srcintf port2
            - set dstintf port1
            - set srcaddr all
            - set dstaddr all
            - set action accept
            - set schedule always
            - set service ALL
            - set logtraffic all
            - set nat enable
            - next
            - end
  FXPAENI0:
    Type: 'AWS::EC2::NetworkInterface'
    Properties:
      Description: port1
      GroupSet:
        - !Ref FXPSecGrpBase
      SourceDestCheck: false
      SubnetId: !Ref PublicSubnet1
      PrivateIpAddress: !Select 
        - '0'
        - !Split 
          - /
          - !Ref IPAPublicSubnet1
      Tags:
        - Key: Name
          Value: !Join 
            - ''
            - - !Ref 'AWS::StackName'
              - FXPAENI0
        - Key: Interface
          Value: eth0
  FXPAENI1:
    Type: 'AWS::EC2::NetworkInterface'
    Properties:
      Description: port2
      GroupSet:
        - !Ref FXPSecGrpBase
      SourceDestCheck: false
      SubnetId: !Ref PrivateSubnet1
      PrivateIpAddress: !Select 
        - '0'
        - !Split 
          - /
          - !Ref IPAPrivateSubnet1
      Tags:
        - Key: Name
          Value: !Join 
            - ''
            - - !Ref 'AWS::StackName'
              - FXPAENI1
  ClusterEIP:
    Type: 'AWS::EC2::EIP'
    Properties:
      Domain: vpc
    DependsOn: FXPA
  FXPAMgmtEIP:
    Type: 'AWS::EC2::EIP'
    Properties:
      Domain: vpc
    DependsOn: FXPA
  ClusterAEIPASSOCIATION:
    Type: 'AWS::EC2::EIPAssociation'
    Properties:
      AllocationId: !GetAtt 
        - ClusterEIP
        - AllocationId
      NetworkInterfaceId: !Ref FXPAENI0
  LambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      Policies:
        - PolicyName: S3AccessRole
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - ec2:DescribeImages
                  - s3:PutObject
                Resource: '*'
              - Effect: Allow
                Action:
                  - logs:*
                Resource: '*'
  ImageFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: !Join
          - |+

          - - import boto3
            - import cfnresponse
            - import logging
            - import json
            - logger = logging.getLogger()
            - logger.setLevel(logging.INFO)
            - client = boto3.client('ec2')
            - ''
            - 'def handler(event, context):'
            - '    if event[''RequestType''] == ''Create'':'
            - '        logger.info(''<-- event received: {}''.format(json.dumps(event)))'
            - '        searchString = event[''ResourceProperties''][''SearchString'']'
            - '        productCode =  event[''ResourceProperties''][''ProductCode'']'
            - '    else:'
            - '        responseData = {''msg'':''200''}'
            - '        cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)'
            - '        return None'
            - ''
            - '    try:'
            - '        resp = client.describe_images('
            - '            Filters=[{''Name'': ''name'', ''Values'': [searchString]}, {''Name'': ''product-code'', ''Values'': [productCode]}],'
            - '            Owners=[''aws-marketplace'']'
            - '        )'
            - '    except Exception as error:'
            - '        logger.error(''<--!! Exception: {}''.format(error))'
            - '        responseData = {''msg'':''Exception: {}''.format(error)}'
            - '        cfnresponse.send(event, context, cfnresponse.FAILED, responseData)'
            - ''
            - '    if resp[''ResponseMetadata''][''HTTPStatusCode''] == 200 and resp[''Images''] != []:'
            - '        ami_dict = {}'
            - '        ami_list = []'
            - '        for entry in resp[''Images'']:'
            - '            key = entry[''CreationDate'']'
            - '            ami_dict[key] = entry[''ImageId'']'
            - '        ami_list = sorted(ami_dict, reverse = True)'
            - '        logger.info(''--> found latest AMI: {}, {}, {} {}''.format(ami_dict[ami_list[0]], ami_list[0], searchString, productCode))'
            - '        responseData = {''ami'': ami_dict[ami_list[0]]}'
            - '        cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)'
            - '    else:'
            - '        logger.error(''!!--> Unable to find AMI {} {} in describe_images response! {}''.format(searchString, productCode, resp))'
            - '        responseData = {''msg'':''Unable to find AMI {} {} in describe_images response! {}''.format(searchString, productCode,resp)}'
            - '        cfnresponse.send(event, context, cfnresponse.FAILED, responseData)'
            - ''
      Role: !GetAtt LambdaRole.Arn
      Timeout: 120
      Handler: index.handler
      Runtime: python3.9
      MemorySize: 128
  RunImageFunction:
    Type: Custom::ImageFunction
    Properties:
      ServiceToken: !GetAtt ImageFunction.Arn
      SearchString: !Select
        - '0'
        - !Split
          - '|'
          - !FindInMap
            - FortiProxyAMISearchString
            - !Ref FortiProxyVersion
            - !Ref LicenseType
      ProductCode: !Select
        - '1'
        - !Split
          - '|'
          - !FindInMap
            - FortiProxyAMISearchString
            - !Ref FortiProxyVersion
            - !Ref LicenseType
Outputs:
  FXPAURL:
    Value: !Join 
      - ''
      - - 'https://'
        - !Ref FXPAMgmtEIP
    Description: URL to access FortiProxyA
  FXPUsername:
    Value: admin
    Description: Username to access FortiProxys
  FXPAPassword:
    Value: !Ref FXPA
    Description: Password to access FortiProxyA