'How to use ${CI_JOB_TOKEN} > .netrc without messing up docker cache

I do have some repos on gitlab with CICD configured. This is the build script:

Build
  Staging:
    stage: build
    image: docker:19.03.1   
  services:
    - docker:19.03.1-dind   
  before_script:
    - apk --update --no-cache add openssh-client curl py-pip gettext
    - pip install awscli
    - echo -e "machine gitlab.com\nlogin gitlab-ci-token\npassword ${CI_JOB_TOKEN}" > .netrc   
  script:
    - $(aws ecr get-login --no-include-email --region sa-east-1)
    - docker pull $AWS_ECR:latest || true
    - docker build --cache-from $AWS_ECR:latest...

And my dockerfile is the following:

FROM golang:latest

WORKDIR $GOPATH/src/api-v2

COPY go.mod go.sum ./
COPY .netrc /root/

RUN go mod download && go mod verify

COPY . $GOPATH/src/api-v2

... 

RUN go build

EXPOSE 8080

CMD [ "api-v2" ]

With this dockerfile if my dependencies dosen't change the docker is supposed to use the cache until the 6th line, that happens if I run docker build locally

That said whenever the gitlab-ci triggers it stops using the cache on line 4

COPY .netrc /root/

That happens due to a .netrc change on this line

- echo -e "machine gitlab.com\nlogin gitlab-ci-token\npassword ${CI_JOB_TOKEN}" > .netrc

I Thought on using a fixed user/pwd that would be obtained from gitlab variables:

- echo -e "machine gitlab.com\nlogin ${gitlab-user-var}\npassword ${gitlab-pwd-var}" > .netrc

But that dosen't seems right.

What is the better / reccomended / right way of using a .netrc to authenticate against gitlab without messing up the docker image cache ???



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source