LoginSignup
3
2

More than 1 year has passed since last update.

K8sで使うECRアクセス用のSecretを自動更新する

Last updated at Posted at 2021-04-23

ECRのアクセストークンは12時間で切れてしまう。なのでdocker-registryタイプのsecretを作成しても12時間後には使えない。このsecretを自動更新する。ちょうどいい感じのhelmチャートがあったのでそれを使用する。使用するhelmチャートはこちらのaws-ecr-credentialです。

ちなみにHelmはv3を使用しています。

helmレポジトリを追加

$ helm repo add architectminds https://architectminds.github.io/helm-charts/

valueを確認したいので以下コマンド

$ helm show values architectminds/aws-ecr-credential
# targetNamespace is where the aws-registry secret will be created and maintained
targetNamespace: default

# aws.account is the aws account number of the ECR (string)
# aws.region is the aws region where the ECR exists
# aws.accessKeyId is the credential of a read-only user for the ECR
# aws.secretAccessKey is the credential of a read-only user for the ECR
aws:
  account: ""
  region: ""
  accessKeyId: ""        # base64
  secretAccessKey: ""    # base64

jobImage: architectminds/aws-kubectl
jobImageTag: 1.1

上記の通り、AWS関連のアカウントIDやIAMユーザのアクセスキーが必要になる。そのため、事前にECRアクセス用のIAMユーザを作成しておく。また、secretを置きたいnamespaceも必要なら指定する。なお、アクセスキーなどをbase64エンコードする時は以下の様に改行コードを入れない様に注意する。

$ echo -n "hoge" | base64

valueを指定しつつ以下コマンドでチャートからマニフェストを生成

$ helm install aws-ecr-credential architectminds/aws-ecr-credential \
  --set-string aws.account=<aws account nubmer> \
  --set aws.region=<aws region> \
  --set aws.accessKeyId=<base64> \
  --set aws.secretAccessKey=<base64> \
  --set targetNamespace=default \
  --dry-run --debug

表示されたマニフェストを適当な名前のマニフェストファイルに保存する。マニフェストにはCronJobとJobが含まれている。ここで、DOCKER_REGISTRY_SERVERの指定にhttps://が含まれてしまっているためhttps://を削除する。削除したらマニフェストをkubectl applyでデプロイする。

上記デプロイするとnamespace:aws-ecr-credential-nsにcronjob:aws-ecr-credential-cronが作成される。8時間おきにsecretを更新してくれる

$ kubectl get cronjob -n aws-ecr-credential-ns
NAME                      SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
aws-ecr-credential-cron   * */8 * * *   False     0        <none>          31m

指定したnamespaesにsecret:aws-registryができていることを確認

$ kubectl get secret -n default | grep aws-registry
aws-registry                              kubernetes.io/dockerconfigjson        1      20m
3
2
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
3
2