1
0

More than 1 year has passed since last update.

Codebuild での Docker build 時 に ssh キーを使う方法

Last updated at Posted at 2022-07-11

はじめに

ハマったので備忘録として。

手順

1. Systems Manager の Parameter Store で設定する

こんな感じで。
Type は String でもよいけど、セキュアなデータなので個人的にには SecureString がおすすめ。
Screen Shot 2022-07-11 at 20.18.23.png

2. buildspec.yml で使うように記述する

version: 0.2

env:
    parameter-store:
        SECRETS_GITHUB: github-deploy-key
    variables:
        DOCKER_BUILDKIT: "1"

phases:
    pre_build:
        commands:
            - echo Logging in to Amazon ECR...
            - REPOSITORY_URI=${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${IMAGE_REPO_NAME}
            - IMAGE_TAG=$(echo ${CODEBUILD_RESOLVED_SOURCE_VERSION} | head -c 7)
    build:
        commands:
            - echo "$SECRETS_GITHUB" > deploy_key.txt
            - chmod 600 deploy_key.txt
            - docker build --secret id=ssh,src=deploy_key.txt -t ${IMAGE_REPO_NAME}:${IMAGE_TAG} .
    post_build:
        commands:
            - aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | docker login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com
            - docker tag ${IMAGE_REPO_NAME}:${IMAGE_TAG} ${REPOSITORY_URI}:${IMAGE_TAG}
            - docker tag ${IMAGE_REPO_NAME}:${IMAGE_TAG} ${REPOSITORY_URI}:latest
            - docker push ${REPOSITORY_URI}:${IMAGE_TAG}

--secrets で渡すのは色んな記事で見かけるけど意外と chmod しているのは見かけなかった。
が、ここが大事で、しなかった場合に Docker build 時にエラーになる。
通常の ssh キーと同じ挙動なので、 --secrets で渡すファイルは中身だけじゃなく権限も一緒に渡している模様.

あと、どこかの記事で「改行文字があるとダメだから置換しないといけない」って記述を見かけたけど、
それは全然必要なかったので無視してよい。

3. Dockerfile 内で使う

FROM python:3.8.13-slim-bullseye
〜〜〜〜〜〜
RUN --mount=type=secret,id=ssh,dst=/root/.ssh/id_rsa poetry install
〜〜〜〜〜〜

ポイントは、ssh キーを使う処理と --mount を一緒に記述すること。

RUN --mount=type=secret,id=ssh,dst=/root/.ssh/id_rsa
RUN poetry install

のようにやると、 /root/.ssh/id_rsa が存在せず、エラーになってしまう。
ssh キーを使う処理が複数存在する場合は、以下のように複数行書く必要がある。

RUN --mount=type=secret,id=ssh,dst=/root/.ssh/id_rsa poetry install
RUN --mount=type=secret,id=ssh,dst=/root/.ssh/id_rsa poetry run pip install -r requirements.txt

4. Role に権限をつける

Systems Manager にアクセスするので Codebuild を実行する Role に ssm:Get* の権限をつける

5. 実行

あとは、Codepipeline から呼び出すなり、 Codebuild 単体で実行するなりで実行したらOK。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0