Right now my Jenkins runs without any errors with this commands;
stage("Deliver for Development"){
agent any
when {
branch "development"
}
steps{
sh 'sudo rm -rf /var/www/jenkins-weather-app'
sh "sudo cp -r ${env.WORKSPACE}/build /var/www/jenkins-weather-app"
sh "sudo ls /var/www/jenkins-weather-app"
// sh './scripts/kill.sh'
}
}
It ran because I add this line of code to my sudoers file in ubuntu
jenkins ALL=(ALL) NOPASSWD: ALL
Somehow I believe this is not the right way to go about this. Without the sudo I get
errors like this
+ cp -r /var/lib/jenkins/workspace/react-weather-app_development/build /var/www/jenkins-weather-app
cp: cannot create directory '/var/www/jenkins-weather-app': Permission denied
script returned exit code 1
Is there a way of running the sh commands without sudo.
2
Answers
I discovered the jenkins user had no permission to write i.e modify the contents of the /var/www/ folder. What I did was to change the owner of the folder to jenkins, give it the permission of 740, and then I could modify the folder without using sudo. I don't know if this is the right approach but it worked without sudo.
Firstly, you don’t need sudo to work with any file/directory inside jenkins workspace; because they’d all belong to jenkins user.
In this your situation that you want to deploy to web directory, you should create a user that has privileges to web deployment and belong to jenkins group to be able to r/w in jenkins workspace, like webmasters with ssh credential. SSh into the user to deployment the artifacts to the directory.
This also helps you to use the same codebase to deploy to a remote machine with just change to credentialID using withCredential function.