Error in .gitlab-ci while trying to package

Viewed 187

So I'm trying to make conditions in my .gitlab-ci.yml if there is no package then, npm publish to pack the library in the GitLab registry I gave my pipeline the permission to the registry and the npm access token, but I still get the unauthorized error this is the part of the .gitlab-ci.yml where I create the .npmrc file and set the configurations.

script:
    - |
      if [[ ! -f .npmrc ]]; then
        echo 'No .nmprc found! Creating one now.'
        echo "@${CI_PROJECT_ROOT_NAMESPACE}:registry=${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/packages/npm/">.npmrc
        echo "//${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}">>.npmrc
        echo "//registry.npmjs.org/:_authToken=${NPM_ACCESS_TOKEN}">>.npmrc
        echo "Created the following .npmrc:"; cat .npmrc
      fi

The pipeline get me this when I try to find if there is a package with the name of : $NPM_PACKAGE_NAME

@scope:registry = "https://gitlab.example.com/api/v4/projects/project_id/packages/npm/" 
//gitlab.example.com/api/v4/projects/projet_id/packages/npm/:_authToken = (protected) 
//registry.npmjs.org/:_authToken = (protected) 
; "cli" config from command line options
long = true
$ npm config set always-auth true
$ echo $(npm view "${NPM_PACKAGE_NAME}" )
npm ERR! code E401
npm ERR! 401 Unauthorized - GET https://gitlab.example.com/api/v4/projects/project_id/packages/npm/@scope%2fmy-package

Where :

- NPM_PACKAGE_NAME=$(node -p "require('./my-package/package.json').name")
2 Answers

Instead of echo to the .npmrc, you could try the npm commands directly

npm config set -- '//gitlab.example.com/api/v4/projects/<your_project_id>/packages/npm/:_authToken' "${NPM_TOKEN}"
npm config set -- '//gitlab.example.com/api/v4/packages/npm/:_authToken' "${NPM_TOKEN}"

That way, you are sure the .npmrc is properly updated.

Could you try to create the .npmrc in your home folder instead of locally?

We do this in our pipeline and it works without any problem:

publish:
    stage: publish
    script:
        - echo "@<scope>:registry=https://${CI_SERVER_HOST}/api/v4/projects/${REGISTRY_PROJECT_ID}/packages/npm/" > ~/.npmrc
        - echo "//${CI_SERVER_HOST}/api/v4/projects/${REGISTRY_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}" >> ~/.npmrc
        - npm version --no-git-tag-version "$(<.next-version)" --allow-same-version
        - npm publish --tag ${NPM_TAG_NAME}

As you see, other than the npm version and npm publish commands, the only difference is the .npmrc file location.

Related