---
AWSTemplateFormatVersion: 2010-09-09

Description: CFN Template to deploy CodePipeline to build Docker Image, push to ECR and deploy EKS cluster.

Parameters:

  GitSourceRepo:
    Type: String
    Description: GitHub source repository - must contain a Dockerfile in the base
    Default: mywebsite
    MinLength: 1
    MaxLength: 100
    ConstraintDescription: You must enter a GitHub repository name

  GitBranch:
    Type: String
    Default: main
    Description: GitHub git repository branch - change triggers a new build
    MinLength: 1
    MaxLength: 100
    ConstraintDescription: You must enter a GitHub repository branch name

  GitHubToken:
    Type: String
    NoEcho: true
    Description: GitHub API token from https://github.com/settings/tokens
    MinLength: 3
    MaxLength: 100
    ConstraintDescription: You must enter a GitHub personal access token

  GitHubUser:
    Type: String
    Description: GitHub username or organization
    MinLength: 3
    MaxLength: 100
    ConstraintDescription: You must enter a GitHub username or organization

  EksCluster:
    Type: String
    Description: AWS EKS Cluster Name
    Default: k8s-demo
    MinLength: 3
    MaxLength: 100
    ConstraintDescription: You must enter a EKS Cluster Name
  
  EksDeployment:
    Type: String
    Description: EKS K8S Deployment Name
    Default: fcj-workshop
    MinLength: 3
    MaxLength: 100
    ConstraintDescription: You must enter a EKS K8S Deployment Name to be deloyed
  
  EksNamespace:
    Type: String
    Description: EKS K8S Set Namespace 
    Default: default
    MinLength: 3
    MaxLength: 100
    ConstraintDescription: You must enter a EKS K8S namespace

  EksImageName:
    Type: String
    Description: Image used in Deployment
    Default: "000062"
    MinLength: 3
    MaxLength: 100
    ConstraintDescription: You must enter the image name you used when you deploy sample application on EKS Cluster

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: GitHub
        Parameters:
          - GitHubUser
          - GitHubToken
          - GitSourceRepo
          - GitBranch            
      - Label:
          default: EKS Cluster
        Parameters:
          - EksCluster
          - EksDeployment
          - EksNamespace
          - EksImageName          
    ParameterLabels:
      GitHubUser:
        default: Username
      GitHubToken:
        default: Access token
      GitSourceRepo:
        default: Repository
      GitBranch:
        default: Branch

Resources:

  EcrDockerRepository:
    Type: AWS::ECR::Repository
    DeletionPolicy: Retain
    Properties:
      RepositoryName: !Ref GitSourceRepo

  CodeBuildProject:
    Type: AWS::CodeBuild::Project
    Properties:
      Artifacts:
        Type: CODEPIPELINE
      Source:
        Type: CODEPIPELINE
        BuildSpec: |
          version: 0.2
          phases:
            install:
              runtime-versions:
                docker: 18
              commands:
                - curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - || true
                - apt-get -y update || true
                - apt-get -y install jq || true
                - echo "Installing kubectl"
                - curl -o kubectl https://amazon-eks.s3.us-west-2.amazonaws.com/1.15.10/2020-02-22/bin/linux/amd64/kubectl   
                - chmod +x ./kubectl
                - mkdir -p $HOME/bin && cp ./kubectl $HOME/bin/kubectl && export PATH=$PATH:$HOME/bin                
            pre_build:
              commands:
                - echo "Starting docker daemon..."
                - nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://127.0.0.1:2375 --storage-driver=overlay2&
                - timeout 15 sh -c "until docker info; do echo .; sleep 1; done"
                - echo "Logging into Amazon ECR..."
                - $(aws ecr get-login --no-include-email --region ${AWS_DEFAULT_REGION})
                - TAG="$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | head -c 8)"
                - echo "Login AWS EKS"
                - aws eks --region $AWS_DEFAULT_REGION update-kubeconfig --name $AWS_CLUSTER_NAME
            build:
              commands:
                - echo Build started on `date`
                - docker build -t "${REPOSITORY_URI}:latest" .
                - docker tag "${REPOSITORY_URI}:latest" "${REPOSITORY_URI}:${TAG}"
            post_build:
              commands:
                - echo Build completed on `date`
                - echo "Pushing Docker image to ECR"
                - docker push "${REPOSITORY_URI}:latest"
                - docker push "${REPOSITORY_URI}:${TAG}"
                - printf '{"Tag":"%s","RepositoryUri":"%s"}' $TAG $REPOSITORY_URI $PROJECT_NAME $ARTIFACT_BUCKET > build.json
                - echo "Deploy to EKS"
                - kubectl set image -n $NAMESPACE deployment/$DEPLOYMENT $IMAGENAME="${REPOSITORY_URI}:${TAG}"
                - kubectl get deployment -n $NAMESPACE
                - kubectl get pod -n $NAMESPACE
                - echo Deploy ended on `date`                            
      Environment:
        ComputeType: BUILD_GENERAL1_SMALL
        Type: LINUX_CONTAINER
        Image: "aws/codebuild/standard:2.0"
        PrivilegedMode: True
        EnvironmentVariables:
          - Name: AWS_DEFAULT_REGION
            Value: !Ref AWS::Region
          - Name: REPOSITORY_URI
            Value: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${EcrDockerRepository}
          - Name: AWS_CLUSTER_NAME
            Value: !Ref EksCluster
          - Name: DEPLOYMENT
            Value: !Ref EksDeployment
          - Name: NAMESPACE
            Value: !Ref EksNamespace
          - Name: IMAGENAME
            Value: !Ref EksImageName
      Name: !Ref AWS::StackName
      ServiceRole: !Sub arn:aws:iam::${AWS::AccountId}:role/eks-CodeBuildServiceRole

  CodePipelineGitHub:
    Type: AWS::CodePipeline::Pipeline
    Properties:
      RoleArn: !Sub arn:aws:iam::${AWS::AccountId}:role/eks-CodePipelineServiceRole
      ArtifactStore:
        Type: S3
        Location: !Sub eks-${AWS::AccountId}-codepipeline-artifacts
      Stages:
        - Name: Source
          Actions:
            - Name: App
              ActionTypeId:
                Category: Source
                Owner: ThirdParty
                Version: 1
                Provider: GitHub
              Configuration:
                Owner: !Ref GitHubUser
                Repo: !Ref GitSourceRepo
                Branch: !Ref GitBranch
                OAuthToken: !Ref GitHubToken
              OutputArtifacts:
                - Name: App
              RunOrder: 1
        - Name: Build
          Actions:
            - Name: Build
              ActionTypeId:
                Category: Build
                Owner: AWS
                Version: 1
                Provider: CodeBuild
              Configuration:
                ProjectName: !Ref CodeBuildProject
              InputArtifacts:
                - Name: App
              OutputArtifacts:
                - Name: BuildOutput
              RunOrder: 1
    DependsOn: CodeBuildProject
