AWSTemplateFormatVersion: '2010-09-09'
Description: 'Amazon EKS - Master'

Parameters:
  ProjectName:
    Type: String
    Default: "app"
  VPCStackName:
    Type: String
    Description: VPC Stack Name
    Default: "eks-vpc"
  ClusterVersion:
    Type: String
    Description: The version of EKS to start up
    Default: "1.11"
Resources:

  #
  # IAM Role needed by the cluster
  #
  ClusterRole:
    Description: Allows EKS to manage clusters on your behalf.
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "${ProjectName}-ClusterRole"
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
            Effect: Allow
            Principal:
              Service:
                - eks.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonEKSClusterPolicy
        - arn:aws:iam::aws:policy/AmazonEKSServicePolicy

  ClusterControlPlaneSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: !Sub "${ProjectName}-ClusterSecurityGroup"
      GroupDescription: Cluster communication with worker nodes
      VpcId:
        Fn::ImportValue:
          !Sub "${VPCStackName}-VPCID"

  Cluster:
    Type: "AWS::EKS::Cluster"
    Properties:
      Name: !Sub "${ProjectName}-master"
      Version: !Ref ClusterVersion
      RoleArn: !GetAtt ClusterRole.Arn
      ResourcesVpcConfig:
        SecurityGroupIds:
          - !Ref ClusterControlPlaneSecurityGroup
        SubnetIds:
          - Fn::ImportValue:
              !Sub "${VPCStackName}-subnetAID"
          - Fn::ImportValue:
              !Sub "${VPCStackName}-subnetBID"

Outputs:
  ClusterName:
    Value: !Ref Cluster
    Description: Cluster Name
    Export:
      Name:
        Fn::Sub: "${AWS::StackName}-ClusterName"

  ClusterArn:
    Value: !GetAtt Cluster.Arn
    Description: Cluster Arn
    Export:
      Name:
        Fn::Sub: "${AWS::StackName}-ClusterArn"

  ClusterEndpoint:
    Value: !GetAtt Cluster.Endpoint
    Description: Cluster Endpoint
    Export:
      Name:
        Fn::Sub: "${AWS::StackName}-ClusterEndpoint"

  ClusterControlPlaneSecurityGroup:
    Value: !Ref ClusterControlPlaneSecurityGroup
    Description: ClusterControlPlaneSecurityGroup
    Export:
      Name:
        Fn::Sub: "${AWS::StackName}-ClusterControlPlaneSecurityGroup"
