Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
    • Helm Chart
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log & Monitor
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[AWS] Demo “code build” with experiment easily on AWS

Posted on September 4, 2022September 26, 2022 By nim No Comments on [AWS] Demo “code build” with experiment easily on AWS

Contents

  • 1) Creating ECR to hold the docker image
  • 2) Set up Code Build to build image through Dockerfile
  • 3) Recheck log of Code Build on CloudWatch
  • 4) Provisioning CodeBuild(aws) through terraform

1) Creating ECR to hold the docker image

Bạn sẽ change ở đây.

2) Set up Code Build to build image through Dockerfile

Code của mình đang trên github nên mình chọn github
Ở đây mình chọn Personal access token
Lăn xuống chọn chỗ này để nếu có change code thì aws auto build cho bạn.
Bạn chọn các sự kiện trigger.
đây mình chọn push
Bạn chọn chạy trên hệ điều hành nào
nó run trên con code build có hệ điều hành tương ứng.
Chỗ này thì aws sẽ tạo role cho bạn
bạn chỉ để ý thôi
Chỗ này nếu bạn để buildspec.yml ở folder root rồi thì không cần input gì cả.
Bạn config như trên để bắn log sang cloudWatch
Đã tạo xong Code Build
giờ vào phần Build detail để khám phá
Chúng ta khám phá role
Hiện tại 2 code build đang được cấp 2 permission là code build và push log sang cloud watch
add thêm permission access ECR
Hiện tại demo thì mình cho nó quền full access vào ECR luôn
Đã chạy thành công

3) Recheck log of Code Build on CloudWatch

Bạn có thể vào cloud watch để quan log nhé

File buildspec.yml

version: 0.2

phases:
  pre_build:
    commands:
      - echo Connecting to Amazon ECR...
      - aws --version
      # - $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)
      - aws ecr get-login-password --region us-east-1 | docker login
        --username AWS --password-stdin
        250887682577.dkr.ecr.us-east-1.amazonaws.com
      - REPOSITORY_URI=250887682577.dkr.ecr.us-east-1.amazonaws.com/demo-codebuild
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=build-$(echo $CODEBUILD_BUILD_ID | awk -F":" '{print $2}')
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
      - docker build --platform linux/amd64 -t $REPOSITORY_URI:latest .
      - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker images...
      - docker push $REPOSITORY_URI:latest
      - docker push $REPOSITORY_URI:$IMAGE_TAG
      - echo Writing image definitions file...
      - printf '[{"name":"simple-app","imageUri":"%s"}]'
        $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
      - cat imagedefinitions.json
artifacts:
  files: imagedefinitions.json

4) Provisioning CodeBuild(aws) through terraform

Giờ chúng ta sẽ đến với việc demo code build bằng terraform.
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/codebuild_project

Đầu Tiên là file demo_codebuild.tf

resource "aws_codebuild_project" "demo_codebuild" {
  name          = "demo_codebuild_${var.environment}"
  service_role  = aws_iam_role.codebuild_role.arn

  environment {
    compute_type                = var.linux_compute_type
    image                       = var.linux_compute_image
    type                        = "LINUX_CONTAINER"
    image_pull_credentials_type = "CODEBUILD"
    privileged_mode             = true
    # dynamic "environment_variable" {
    #   for_each = var.env_variables_deploy_image
    #   content {
    #     name  = environment_variable.value["name"]
    #     type  = "PLAINTEXT"
    #     value = environment_variable.value["value"]
    #   }
    # }
  }

  artifacts {
    type      = "NO_ARTIFACTS"
  }

  logs_config {
    cloudwatch_logs {
      group_name = aws_cloudwatch_log_group.demo_codebuild_group.name
    }
  }

  source {
    type = "NO_SOURCE"
    buildspec = <<EOT
version: 0.2
env:
  # parameter-store:
  #   BEARER_TOKEN:             "/nimtechnology-provision/BEARER_TOKEN"
  #   build_ssh_key:            "/nimtechnology-provision/build_ssh_key"
  variables:
    ENVIRONMENT:              "${var.environment}"
phases:
  pre_build:
    commands:
      - echo "ahihi pre_build"
  build:
    commands:
      - echo "ahihi build"
EOT
  }

  tags = {
    Owner = "CloudOps"
    Env = var.environment
  }

  cache {
    type  = var.cache_type
    modes = var.cache_modes
  }

  lifecycle { ignore_changes = [project_visibility] }

}

Đầu tiên bạn để ý service_role = aws_iam_role.codebuild_role.arn
Trong đây là mình sẽ các role để codebuild này có thể access vào các resource khác (cloudwatch, SSM,…)
Chúng ta có 1 file iam.tf

# ## Role: codebuild_role

resource "aws_iam_role" "codebuild_role" {
  name = "${var.environment}-${var.aws_region}-codebuild-role"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "codebuild.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_iam_role_policy" "codebuild_policy" {
  name = "${var.environment}-codebuild-policy"
  role = aws_iam_role.codebuild_role.id

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Resource": [
        "*"
      ],
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents",
        "ssm:GetParameters"
      ]
    }
  ]
}
EOF
}

Ở trên thì mình cấp quyền cho CodeBuild được phép tương tác với CloudWatch.

vời block environment {} thì cũng khá dễ hiều là biến môi trường.
và bạn cần chú ý dynamic Blocks: Nó đơn giản bạn dụng for để load nhiều biến môi trường
https://www.terraform.io/language/expressions/dynamic-blocks

Phần logs_config {} chúng ta tạo 1 log_group cụ thể để cho codebuild gửi sang.
Mình có file logging.tf

resource "aws_cloudwatch_log_group" "demo_codebuild_group" {
  name              = "${var.environment}-deploy"
  retention_in_days = 14
  tags = {
    Owner = "CloudOps"
    Env = var.environment
  }
}

AWS - Amazon Web Service

Post navigation

Previous Post: [Teamcity] Kotlin codes on Git(repository) are conflicted with the TeamCity UI.
Next Post: [AWS] Encrypting your data easily via KMS on AWS

More Related Articles

[AWS] Encrypting data when stored in S3 AWS - Amazon Web Service
[AWS] Configure Ingress SSL and SSL Redirect on Load Balancer Controller AWS - Amazon Web Service
[AWS] Provision AWS IAM Admin User as EKS Admin AWS - Amazon Web Service
[AWS] These are the helpful commands in AWS – awscli AWS - Amazon Web Service
[AWS/EKS] EFS CSI Driver – Create Persistent Volume Clain with ReadWriteMany type on EKS AWS - Amazon Web Service
[Terraform] – Terraform Beginner – Lesson 5: Terraform Provisioners and creating EC2 AWS - Amazon Web Service

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • Experiences for IP Addresses Shortage on EKS Clusters March 29, 2023
  • [Talisman] Discover the sensitive information in your code. March 28, 2023
  • [Prometheus/Grafana] Install Prometheus and Grafana on ubuntu. March 27, 2023
  • [Kong Gateway] WebSocket connection failed March 26, 2023
  • [Nextcloud] Can’t download files to have a size bigger than 2Gi on NextCloud – RaspBerry March 24, 2023

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • Golang
    • Jquery & JavaScript
    • Laravel
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
    • Longhorn – Storage
    • MetalLB
    • Vault
    • VictoriaMetrics
  • Log & Monitor
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2023 NimTechnology.