附: buildspec.yaml详解

CodeBuild执行时, 所有命令都是从buildspec.yaml中获取。

install部分

  install:
    commands:
      - curl -sS -o aws-iam-authenticator https://amazon-eks.s3-us-west-2.amazonaws.com/1.10.3/2018-07-26/bin/linux/amd64/aws-iam-authenticator
      - curl -sS -o kubectl https://amazon-eks.s3-us-west-2.amazonaws.com/1.14.6/2019-08-22/bin/linux/amd64/kubectl
      - chmod +x ./kubectl ./aws-iam-authenticator
      - export PATH=$PWD/:$PATH
      - apt-get update && apt-get -y install jq python3-pip python3-dev && pip3 install --upgrade awscli

这一部分,安装了kubectl和aws cli等基础软件

pre_build部分

  pre_build:
      commands:
        - TAG="$REPOSITORY_NAME.$REPOSITORY_BRANCH.$ENVIRONMENT_NAME.$(date +%Y-%m-%d.%H.%M.%S).$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | head -c 8)"
        - sed -i 's@CONTAINER_IMAGE@'"$REPOSITORY_URI:$TAG"'@' hello-k8s.yml
        - $(aws ecr get-login --no-include-email)
        - export KUBECONFIG=$HOME/.kube/config

在创建CodeBuild时我们添加了以下环境变量,

  • REPOSITORY_URI: 使用创建ECR一节中,最后部分复制的URI
  • REPOSITORY_NAME: 和github保持一致
  • REPOSITORY_BRANCH: master
  • EKS_CLUSTER_NAME: 当前使用的EKS集群名称
  • EKS_KUBECTL_ROLE_ARNarn:aws:iam::{account_id}:role/EksWorkshopCodeBuildKubectlRole, 第一节中已经复制过

生成的镜像TAG示例:

eks-with-codepipeline.master..2022-03-13.10.07.01.f692b21b

sed -i 's@CONTAINER_IMAGE@'"$REPOSITORY_URI:$TAG"'@' hello-k8s.yml: 将新生成的镜像地址替换到hello-k8s.yaml

build部分

 build:
    commands:
      - docker build --tag $REPOSITORY_URI:$TAG .

执行构建镜像

post_build部分

  post_build:
    commands:
      - docker push $REPOSITORY_URI:$TAG
      - CREDENTIALS=$(aws sts assume-role --role-arn $EKS_KUBECTL_ROLE_ARN --role-session-name codebuild-kubectl --duration-seconds 900)
      - export AWS_ACCESS_KEY_ID="$(echo ${CREDENTIALS} | jq -r '.Credentials.AccessKeyId')"
      - export AWS_SECRET_ACCESS_KEY="$(echo ${CREDENTIALS} | jq -r '.Credentials.SecretAccessKey')"
      - export AWS_SESSION_TOKEN="$(echo ${CREDENTIALS} | jq -r '.Credentials.SessionToken')"
      - export AWS_EXPIRATION=$(echo ${CREDENTIALS} | jq -r '.Credentials.Expiration')
      - aws eks update-kubeconfig --name $EKS_CLUSTER_NAME
      - kubectl apply -f hello-k8s.yml
      - printf '[{"name":"hello-k8s","imageUri":"%s"}]' $REPOSITORY_URI:$TAG > build.json
  • docker push $REPOSITORY_URI:$TAG:将构建好的镜像上传到ECR
  • CREDENTIALS=$(aws sts assume-role --role-arn $EKS_KUBECTL_ROLE_ARN --role-session-name codebuild-kubectl --duration-seconds 900): 获取assume role
  • aws eks update-kubeconfig --name $EKS_CLUSTER_NAME: 获取eks集群的credentials
  • kubectl apply -f hello-k8s.yml,执行部署