I’m in the process of migrating my CI/CD pipeline from GitHub Actions to Jenkins. I’ve set up the Jenkins server and configured Git. My current project is built with Node.js and uses numerous environment variables, which are stored in a .env file. I’ve uploaded these variables as secrets in Jenkins credentials and am trying to access them in my Jenkins pipeline.
When building the project, Jenkins uses the Dockerfile, which includes a command to migrate the database using Prisma. Prisma relies on the DATABASE_URL variable specified in the .env file. However, this environment variable is not being properly loaded in the Jenkins pipeline.
Here is my pipeline configuration:
pipeline {
agent any
environment {
registry = "my_ecr_registry"
}
stages {
stage('Load Environment') {
steps {
script {
withCredentials([file(credentialsId: 'my_credentail_id', variable: 'ENV_FILE')]) {
def envContents = readFile(ENV_FILE)
def envVars = envContents.split('n').collectEntries { line ->
def parts = line.split('=')
if (parts.size() == 2) {
[(parts[0].trim()): parts[1].trim()]
} else {
[:]
}
}
envVars.each { key, value ->
env."${key}" = value
}
}
}
}
}
stage('Print All Environment Variables') {
steps {
script {
sh 'env'
}
}
}
stage('Checkout Code') {
steps {
git branch: 'dev',
url: 'my_github_url.git',
credentialsId: 'my_credentail_id'
}
}
stage('Building image') {
steps {
script {
docker.build(
"${registry}:dev_latest",
"--build-arg DATABASE_URL=${DATABASE_URL} ."
)
echo "Build successful"
}
}
}
// }
stage('Configure AWS Credentials') {
steps {
sh '''
aws configure set aws_access_key_id ${AWS_ACCESS_KEY_ID}
aws configure set aws_secret_access_key ${AWS_SECRET_ACCESS_KEY}
aws configure set region us-east-1
'''
}
}
stage('Login to ECR') {
steps {
sh '''
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin ${ECR_REGISTRY}
'''
}
}
stage('Push Docker Image') {
steps {
sh '''
docker-compose push
'''
}
}
stage('Deploy to Development Server') {
steps {
sshagent(['jenkins-ssh-key']) {
sh """
ssh -o StrictHostKeyChecking=no ${USERNAME}@${HOST_NAME_DEV} '
sudo docker system prune -a -f
sudo docker pull ${ECR_REGISTRY}/project:dev_latest
cd /home/ubuntu/project
bash docker-pull.sh
'
"""
}
}
}
}
}
I need the Jenkins pipeline to build the code, push it to Amazon ECR, and deploy the project to an EC2 instance.