How to add .env file while deploying app using Jenkins Pipeline script from SCM?

43 Views Asked by At

I have created a new pipeline in Jenkins and used "Pipeline script from SCM". It will clone the repository and run the Jenkinsfile that exists in that repository. But my repository does not have .env file because it is included in .gitignore.

So my question is how can I add .env file?

I have came up with two approaches,

  1. Go to var/lib/jenkins/workspaces/project_name and add .env file there directly.
  2. Adding environment variables from Jenkinks credentials like this,
# Jenkinsfile
pipeline {
    agent 'any'

     environment {
        DATABASE_URL = credentials('DATABASE_URL')
    }

    stages {
        stage('Build') {
            steps {
                script {
                    sh "echo 'DATABASE_URL=${DATABASE_URL}' > .env"
                }
            }
        }

        stage('Deploy') {
            steps {
                sh 'docker compose down'
                sh 'docker compose up -d --build staging'
            }
        }
    }
} 

I want to know how things are done properly to tackle this problem. Are the solutions that I came up with correct? or is there any better way?

1

There are 1 best solutions below

0
Nimesh Shrestha On BEST ANSWER

Interesting question! We can resolve this issue by copying the .env file from another directory on the server to the Jenkins workspace.

Note: Don't forget to add

Jenkins ALL=(ALL) NOPASSWD: ALL

inside /etc/sudoers file

For example, in Jenkinsfile:

 pipeline {
    agent 'any'

    stages {
        stage('Dependencies') {
            steps {
                script {
                    sh "sudo cp /root/env/project_name/.env /var/lib/jenkins/workspace/project_name"
                }
            }
        }
        stage('Deploy') {
            steps {
                sh 'docker compose down'
                sh 'docker compose up -d --build staging'
            }
        }
    }
}