Search code examples
google-cloud-platformyamldockerfilegcloud

gcloud setting env variable for .npmrc


I know there are several posts/questions like this but nothing answered it.
I am using cloudbuild.yaml and reading a secret value from the secret manager and passing it like this.

YAML file

entrypoint: /bin/sh 
args: ['-c', 'docker build -t gcr.io/$PROJECT_ID/portal:$SHORT_SHA-${_TARGET} --build-arg token=$$TOKEN . ']
...

docker file

ARG target=production
ARG token  
 
COPY package*.json ./
COPY .npmrc .npmrc

RUN npm i -g @angular/cli
RUN npm i && mkdir /ng-app && cp -R ./node_modules ./ng-app
RUN rm -f .npmrc

WORKDIR /ng-app

COPY src ./src
COPY angular.json .
COPY tsconfig.json .
COPY tslint.json .
COPY protractor.conf.js .
 
RUN  node --max_old_space_size=8192 $(npm --global bin)/ng build --configuration $target --source-map=true
...

.npmrc file

@test:registry=https://packages.test.com/npm/js-licensed/
//packages.test.com/npm/js-licensed/:_auth=$token
...

My issue is that, it gets the value from google secret manager and populates to the docker file when I echo it out from dockerfile but .npmrc never gets the value so the $token is not valid. What am I doing wrong?


Solution

  • Just copying a file doesn't make replacement of environment variables inside it. If that would happen automatically then you would never get any shell script properly as the environment variables would be evaluated.

    The change you will make to your Dockerfile will be like below

    ARG target=production
    ARG token  
    COPY package*.json ./
    ENV token=$token
    COPY .npmrc .npmrc.env
    RUN envsubst < .npmrc.env > .npmrc && cat .npmrc
    
    RUN npm i -g @angular/cli
    RUN npm i && mkdir /ng-app && cp -R ./node_modules ./ng-app
    RUN rm -f .npmrc
    
    WORKDIR /ng-app
    
    COPY src ./src
    COPY angular.json .
    COPY tsconfig.json .
    COPY tslint.json .
    COPY protractor.conf.js .
     
    RUN  node --max_old_space_size=8192 $(npm --global bin)/ng build --configuration $target --source-map=true