code_deploy.yaml 15 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
Parameters:
  BranchName:
    Description: GitHub branch name
    Type: String
    Default: 'master'
  RepositoryName:
    Description: GitHub repository name
    Type: String
    # Default: '깃허브 repo name'
  GitHubOwner:
    Type: String
    # Default: '깃허브 ID'
  GitHubOAuthToken:
    Type: String
    # Default: '깃허브 OAuth Token'
    NoEcho: true
  GitHubSecret:
    Type: String
    # Default: '깃허브 비밀번호'
    NoEcho: true
  KeyName:
    Type: String
    Default: iot
  VPC:
    Type: String
    Default: vpc-aab1aac2
  WebappSubnets:
    Type: CommaDelimitedList
    Default: subnet-c44697bf, subnet-e8756180, subnet-e87f07a4
  ALBSubnets:
    Type: CommaDelimitedList
    Default: subnet-c44697bf, subnet-e8756180, subnet-e87f07a4
  AMIID:
    Type: String
    Default: ami-08ab3f7e72215fe91
  MinSize:
    Type: Number
    Default: 2
  MaxSize:
    Type: Number
    Default: 3
  NamePrefix:
    AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*'
    Default: bluegreen
    Description: Prefix for resource tags made by this template (2-15 chars).
    MaxLength: 15
    MinLength: 2
    Type: String
  CommitId:
    Type: String
    Default: 'ddd'
  Repository:
    Type: String
    Default: 'ddd'
  HashKeyElementName:
    Description: HashType PrimaryKey Name
    Default: test
    Type: String
    AllowedPattern: '[a-zA-Z0-9]*'
    MinLength: 1
    MaxLength: 2048
    ConstraintDescription: must contain only alphanumberic characters
  HashKeyElementType:
    Description: HashType PrimaryKey Type
    Type: String
    Default: S
    AllowedPattern: '[S|N]'
    MinLength: 1
    MaxLength: 1
    ConstraintDescription: must be either S or N
  ReadCapacityUnits:
    Description: Provisioned read throughput
    Type: Number
    Default: 5
    MinValue: 5
    MaxValue: 10000
    ConstraintDescription: must be between 5 and 10000
  WriteCapacityUnits:
    Description: Provisioned write throughput
    Type: Number
    Default: 10
    MinValue: 5
    MaxValue: 10000
    ConstraintDescription: must be between 5 and 10000
Resources:
  CodeDeployRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          -
            Effect: "Allow"
            Principal:
              Service:
                - "codedeploy.amazonaws.com"
            Action:
              - "sts:AssumeRole"
      Policies:
        -
          PolicyName: allow-autoscaling
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              -
                Effect: Allow
                Action:
                  - ec2:*
                  - autoscaling:*
                Resource: "*"
        -
          PolicyName: allow-loadbalance
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              -
                Effect: Allow
                Action:
                  - ec2:*
                  - autoscaling:*
                Resource: "*"
              -
                Effect: Allow
                Action:
                  - iam:CreateServiceLinkedRole
                Resource: "*"
              -
                Effect: Allow
                Action:
                  - elasticloadbalancing:*
                Resource: "*"
  WebappRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          -
            Effect: "Allow"
            Principal:
              Service:
                - "ec2.amazonaws.com"
                - "codedeploy.amazonaws.com"
                - "events.amazonaws.com"
                - "dynamodb.amazonaws.com"
            Action:
              - "sts:AssumeRole"
      Policies:
        -
          PolicyName: "allow-webapp-deployment-bucket-bucket"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              -
                Effect: "Allow"
                Action: "s3:getObject"
                Resource: !Sub arn:aws:s3:::${CodePipelineArtifactStoreBucket}/*
              -
                Effect: Allow
                Action:
                  - autoscaling:*
                  - cloudwatch:*
                  - logs:*
                  - sns:*
                  - dynamodb:*
                Resource: "*"
  WebappInstanceProfile:
    Type: "AWS::IAM::InstanceProfile"
    Properties:
      Roles:
        - Ref: WebappRole
  ALBSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: allow access to ALB from internet
      VpcId:
        Ref: VPC
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: '80'
        ToPort: '80'
        CidrIp: 0.0.0.0/0
  WebappSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: allow access to Webapp from ALB
      VpcId:
        Ref: VPC
      SecurityGroupIngress:
      - IpProtocol: tcp
        FromPort: '3000'
        ToPort: '3000'
        SourceSecurityGroupId:
          Ref: ALBSecurityGroup
      - IpProtocol: tcp
        FromPort: '22'
        ToPort: '22'
        CidrIp: 0.0.0.0/0
  WebappLaunchConfig:
    Type: AWS::AutoScaling::LaunchConfiguration
    Properties:
      AssociatePublicIpAddress: true
      ImageId:
        Ref: AMIID
      InstanceType: t2.micro
      KeyName:
        Ref: KeyName
      SecurityGroups:
        - Ref: WebappSecurityGroup
      IamInstanceProfile:
        Ref: WebappInstanceProfile
      UserData:
        Fn::Base64:
          !Sub |
            #! /bin/bash -xe
            # update yum just in case
            yum update -y
            # install codedeploy agent
            yum install -y ruby
            yum install -y wget
            cd /home/ec2-user
            # you have to notice region in url
            curl -O https://aws-codedeploy-ap-northeast-2.s3.amazonaws.com/latest/install
            chmod +x ./install
            ./install auto
            # install cloudwatch logs agent 
            sudo yum install -y awslogs
            # set config file sending log to right region
            echo -e "[general]\ndatetime_format = %Y-%m-%d %H:%M:%S\nfile = /var/log/aws/codedeploy-agent/codedeploy-agent.log\nlog_stream_name = {instance_id}-codedeploy-agent-log\nlog_group_name = codedeploy-agent-log\n\n[codedeploy-agent-logs]\ndatetime_format = %Y-%m-%d %H:%M:%S\nfile = /var/log/aws/codedeploy-agent/codedeploy-agent.log\nlog_stream_name = {instance_id}-codedeploy-agent-log\nlog_group_name = codedeploy-agent-log\n\n[codedeploy-updater-logs]\nfile = /tmp/codedeploy-agent.update.log\nlog_stream_name = {instance_id}-codedeploy-updater-log\nlog_group_name = codedeploy-updater-log\n\n[codedeploy-deployment-logs]\nfile = /opt/codedeploy-agent/deployment-root/deployment-logs/codedeploy-agent-deployments.log\nlog_stream_name = {instance_id}-codedeploy-deployments-log\nlog_group_name = codedeploy-deployments-log" > codedeploy_logs.conf
            echo -e "[plugins]\ncwlogs = cwlogs\n[default]\nregion = ap-northeast-2" > codedeploy_cli.conf
            sudo cp ./codedeploy_logs.conf /etc/awslogs/awslogs.conf
            sudo cp ./codedeploy_cli.conf /etc/awslogs/awscli.conf
            # start cloudwatch agent
            sudo systemctl start awslogsd
            # get node into yum
            curl --silent --location https://rpm.nodesource.com/setup_8.x | bash -
            # install node and npm in one line
            yum install -y nodejs
            # install pm2 to restart node app
            npm i -g pm2@2.4.3
  AutoScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      HealthCheckType: ELB
      HealthCheckGracePeriod: 300
      MinSize:
        Ref: MinSize
      MaxSize:
        Ref: MaxSize
      LaunchConfigurationName:
        Ref: WebappLaunchConfig
      VPCZoneIdentifier:
        Ref: WebappSubnets
      TargetGroupARNs:
        - Ref: ALBTargetGroup
      Tags:
        - Key: Name
          Value: webapp-example
          PropagateAtLaunch: true
  ALBListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      DefaultActions:
        -
          Type: forward
          TargetGroupArn:
            Ref: ALBTargetGroup
      LoadBalancerArn:
        Ref: LoadBalancer
      Port: 80
      Protocol: HTTP
  LoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Name: testLoadbalancer
      Scheme: internet-facing
      Subnets:
        Ref: ALBSubnets
      SecurityGroups:
        - Ref: ALBSecurityGroup
      Tags:
      - Key: Name
        Value:
          !Join ["", [ Ref: NamePrefix, "-elb"] ]
  ALBTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      TargetGroupAttributes:
        - Key: deregistration_delay.timeout_seconds
          Value: 30
      HealthCheckIntervalSeconds: 30
      UnhealthyThresholdCount: 2
      HealthyThresholdCount: 2
      HealthCheckPath: /
      Port: 3000
      Protocol: HTTP
      VpcId:
        Ref: VPC
  WebappApplication:
    Type: "AWS::CodeDeploy::Application"
    Properties:
      ApplicationName: testApp
  WebappDeploymentGroup:
    Type: "AWS::CodeDeploy::DeploymentGroup"
    Properties:
      DeploymentGroupName: test-group
      ApplicationName: !Ref WebappApplication
      ServiceRoleArn: !GetAtt CodeDeployRole.Arn
      DeploymentConfigName: CodeDeployDefault.OneAtATime
      DeploymentStyle:
        DeploymentType: IN_PLACE
        DeploymentOption: WITH_TRAFFIC_CONTROL
      LoadBalancerInfo:
        TargetGroupInfoList:
          - Name: !GetAtt ALBTargetGroup.TargetGroupName
      AutoScalingGroups:
      - Ref: AutoScalingGroup
  CodePipelineArtifactStoreBucket:
    Type: 'AWS::S3::Bucket'
  CodePipelineArtifactStoreBucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      Bucket: !Ref CodePipelineArtifactStoreBucket
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid: DenyUnEncryptedObjectUploads
            Effect: Deny
            Principal: '*'
            Action: 's3:PutObject'
            Resource: !Join 
              - ''
              - - !GetAtt 
                  - CodePipelineArtifactStoreBucket
                  - Arn
                - /*
            Condition:
              StringNotEquals:
                's3:x-amz-server-side-encryption': 'aws:kms'
          - Sid: DenyInsecureConnections
            Effect: Deny
            Principal: '*'
            Action: 's3:*'
            Resource: !Join 
              - ''
              - - !GetAtt 
                  - CodePipelineArtifactStoreBucket
                  - Arn
                - /*
            Condition:
              Bool:
                'aws:SecureTransport': false
  AppPipelineWebhook:
    Type: 'AWS::CodePipeline::Webhook'
    Properties:
      Authentication: GITHUB_HMAC
      AuthenticationConfiguration:
        SecretToken: !Ref GitHubSecret
      Filters:
        - JsonPath: $.ref
          MatchEquals: 'refs/heads/{Branch}'
      TargetPipeline: !Ref AppPipeline
      TargetAction: SourceAction
      Name: AppPipelineWebhook
      TargetPipelineVersion: !GetAtt 
        - AppPipeline
        - Version
      RegisterWithThirdParty: true
  AppPipeline:
    Type: 'AWS::CodePipeline::Pipeline'
    Properties:
      Name: github-events-pipeline
      RoleArn: !GetAtt 
        - CodePipelineServiceRole
        - Arn
      Stages:
        - Name: Source
          Actions:
            - Name: SourceAction
              ActionTypeId:
                Category: Source
                Owner: ThirdParty
                Version: 1
                Provider: GitHub
              OutputArtifacts:
                - Name: SourceOutput
              Configuration:
                Owner: !Ref GitHubOwner
                Repo: !Ref RepositoryName
                Branch: !Ref BranchName
                OAuthToken: !Ref GitHubOAuthToken
                PollForSourceChanges: false
              RunOrder: 1
        - Name: Beta
          Actions:
            - Name: BetaAction
              InputArtifacts:
                - Name: SourceOutput
              ActionTypeId:
                Category: Deploy
                Owner: AWS
                Version: 1
                Provider: CodeDeploy
              Configuration:
                ApplicationName: !Ref WebappApplication
                DeploymentGroupName: !Ref WebappDeploymentGroup
              RunOrder: 1
      ArtifactStore:
        Type: S3
        Location: !Ref CodePipelineArtifactStoreBucket
  CodePipelineServiceRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - codepipeline.amazonaws.com
            Action: 'sts:AssumeRole'
      Path: /
      Policies:
        - PolicyName: AWS-CodePipeline-Service-3
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - 'codecommit:CancelUploadArchive'
                  - 'codecommit:GetBranch'
                  - 'codecommit:GetCommit'
                  - 'codecommit:GetUploadArchiveStatus'
                  - 'codecommit:UploadArchive'
                Resource: '*'
              - Effect: Allow
                Action:
                  - 'codedeploy:CreateDeployment'
                  - 'codedeploy:GetApplicationRevision'
                  - 'codedeploy:GetDeployment'
                  - 'codedeploy:GetDeploymentConfig'
                  - 'codedeploy:RegisterApplicationRevision'
                Resource: '*'
              - Effect: Allow
                Action:
                  - 'codebuild:BatchGetBuilds'
                  - 'codebuild:StartBuild'
                Resource: '*'
              - Effect: Allow
                Action:
                  - 'devicefarm:ListProjects'
                  - 'devicefarm:ListDevicePools'
                  - 'devicefarm:GetRun'
                  - 'devicefarm:GetUpload'
                  - 'devicefarm:CreateUpload'
                  - 'devicefarm:ScheduleRun'
                Resource: '*'
              - Effect: Allow
                Action:
                  - 'lambda:InvokeFunction'
                  - 'lambda:ListFunctions'
                Resource: '*'
              - Effect: Allow
                Action:
                  - 'iam:PassRole'
                Resource: '*'
              - Effect: Allow
                Action:
                  - 'elasticbeanstalk:*'
                  - 'ec2:*'
                  - 'elasticloadbalancing:*'
                  - 'autoscaling:*'
                  - 'cloudwatch:*'
                  - 's3:*'
                  - 'sns:*'
                  - 'cloudformation:*'
                  - 'rds:*'
                  - 'sqs:*'
                  - 'ecs:*'
                Resource: '*'

Outputs:
  WebappUrl:
    Description: Webapp URL
    Value: !GetAtt LoadBalancer.DNSName
  DeploymentGroup:
    Description: Webapp Deployment Group
    Value: !Ref WebappDeploymentGroup
  DeploymentBucket:
    Description: Deployment bucket
    Value: !Ref CodePipelineArtifactStoreBucket
  ApplicationName:
    Description: CodeDeploy Application name
    Value: !Ref WebappApplication