diff --git a/files/nginx.conf b/files/nginx.conf index b714aac..c7c707a 100644 --- a/files/nginx.conf +++ b/files/nginx.conf @@ -18,8 +18,21 @@ http { # this is necessary for us to be able to disable request buffering in all cases proxy_http_version 1.1; + lua_shared_dict token_dict 1m; + # will run before forking out nginx worker processes - init_by_lua_block { require "cjson" } + init_by_lua_block { + require "cjson" + + local token_file = io.open('/usr/local/openresty/nginx/token.txt', 'r') + if token_file then + local data = token_file:read() + ngx.shared.token_dict:set("ecr_token", data) + token_file:close() + else + ngx.log(ngx.ERR, "Failed to open token file: /usr/local/openresty/nginx/token.txt") + end + } #https://docs.docker.com/registry/recipes/nginx/#setting-things-up map $upstream_http_docker_distribution_api_version $docker_distribution_api_version { @@ -29,6 +42,10 @@ http { server { listen PORT SSL_LISTEN default_server; + set_by_lua_block $http_authorization { + return ngx.shared.token_dict:get("ecr_token") + } + SSL_INCLUDE # Cache diff --git a/files/renew_token.sh b/files/renew_token.sh index 8de0a33..8fe1609 100755 --- a/files/renew_token.sh +++ b/files/renew_token.sh @@ -6,17 +6,17 @@ set -xe CONFIG=/usr/local/openresty/nginx/conf/nginx.conf AUTH=$(grep X-Forwarded-User $CONFIG | awk '{print $4}'| uniq|tr -d "\n\r") + # retry till new get new token while true; do - TOKEN=$(aws ecr get-login --no-include-email | awk '{print $6}') + TOKEN=$(aws ecr get-authorization-token --query 'authorizationData[*].authorizationToken' --output text) [ ! -z "${TOKEN}" ] && break echo "Warn: Unable to get new token, wait and retry!" sleep 30 done - -AUTH_N=$(echo AWS:${TOKEN} | base64 |tr -d "[:space:]") - -sed -i "s|${AUTH%??}|${AUTH_N}|g" $CONFIG +set +x +echo $TOKEN > /usr/local/openresty/nginx/token.txt +set -x nginx -s reload diff --git a/files/startup.sh b/files/startup.sh index b56052b..5743a94 100755 --- a/files/startup.sh +++ b/files/startup.sh @@ -77,12 +77,14 @@ if [ -z "$AWS_USE_EC2_ROLE_FOR_AUTH" ] || [ "$AWS_USE_EC2_ROLE_FOR_AUTH" != "tru fi chmod 600 -R ${AWS_FOLDER} +set +x # add the auth token in default.conf AUTH=$(grep X-Forwarded-User $CONFIG | awk '{print $4}'| uniq|tr -d "\n\r") -TOKEN=$(aws ecr get-login --no-include-email | awk '{print $6}') -AUTH_N=$(echo AWS:${TOKEN} | base64 |tr -d "[:space:]") -sed -i "s|${AUTH%??}|${AUTH_N}|g" $CONFIG +TOKEN=$(aws ecr get-authorization-token --query 'authorizationData[*].authorizationToken' --output text) +echo $TOKEN > /usr/local/openresty/nginx/token.txt + +set -x # make sure cache directory has correct ownership chown -R nginx:nginx /cache