Example Jenkins pipeline publishing NPM package to AWS CodeArtifact

Tags:

CodeArtifact is an AWS product for storing build artifacts in the cloud, akin to Nexus or Artifactory.

The example below shows a basic Jenkins Pipeline job that builds and NPM artifact and publishes it to CodeArtifact, which I’m publishing as it was a bit tricky to figure out. The key bit is getting the access token to be generated by the CLI tools and then passing it down to the main build process via an environment variable.

First, check in a .npmrc file to the project’s source code with values configured for the repository.

@myscope:registry=https://codeartifactrepourl
//codeartifactrepourl:always-auth=true
//codeartifactrepourl:_authToken=${CODEARTIFACT_AUTH_TOKEN}

Next, configure your Jenkins build job with a pipeline script like the one below. The key points have been annotated.

pipeline {
    agent { 
        kubernetes {
      yaml """
kind: Pod
spec:
  containers:
  - name: nodejs
    image: node:16.2.0
    command:
    - cat
    tty: true
  - name: aws
    image: amazon/aws-cli:2.2.5 
    command:
    - cat
    tty: true
    env:
    - name: AWS_ACCESS_KEY_ID                                     // (1) Authentication for AWS CLI
      value: XXXXXXXXXXXXXXXXXXX                                  // required to generate CodeArtifact token.
    - name: AWS_SECRET_ACCESS_KEY
      value: XXXXXXXXXXXXXXXXXXX
"""
        }
    }
    stages {
        stages {
            stage('Init') { 
                steps {
                    container ('aws') {
                        script {
                            // (2) Use AWS CLI to get short-lived token for the build 
                            def codeArtifactAuthToken = sh(returnStdout: true, script: 'aws codeartifact get-authorization-token --domain XXXXXXXXX --domain-owner XXXXXX --query authorizationToken --output text --duration-seconds 900 --region XXXXXX').trim()

                            // (3) Configure environment variable referenced in .npmrc file
                            // Done in this style as the value is dynamically generated.
                            env.CODEARTIFACT_AUTH_TOKEN="${codeArtifactAuthToken}"
                        }
                    }
                }
            }
            stage('Build') { 
                steps {
                    container('nodejs') {
                        // (4) Run the build
                        sh 'npm install'
                        sh 'npm run build'
                    }
                }
            }
            stage('Release') {
                steps {
                    container('nodejs') {
                        // (5) Publish
                        sh 'npm publish'
                    }
                }
            }
        }
    }
}

This approach should be adaptable to other build systems which AWS CodeArtifact supports, such as Maven, as same environment variable and token format is used across the board.