I'm setting up a CI/CD pipeline and need to run a custom .sh script only after my build succeeds. I see the "Execute shell" option in the build section, but I specifically want this to trigger during the "Post-build Actions" phase to handle deployments or workspace cleanup. I'm using a Freestyle project, but I’m also curious how to implement this in a Declarative Pipeline using the post block. Do I need a specific plugin like "PostBuildScript," or is there a native way to do this?
3 answers
For Freestyle projects, Jenkins does not have a native "Execute Shell" option in the Post-build Actions list by default. To enable this, you should install the PostBuildScript Plugin. Once installed, you can add "Execute shell" as a post-build step and even configure it to run only if the build status is "Success" or "Unstable."
If you are using Jenkins Pipelines, you don't need a plugin. You use the post section at the end of your pipeline block. Inside success, failure, or always, you can simply use the sh step to call your script. This is the modern standard for Jenkins automation.
When running a script in the post block, does the script run on the same agent (node) where the build took place, or does it move back to the master? I'm worried about file paths if my script needs to access artifacts created during the build phase.
For Freestyle jobs, make sure your Jenkins user has execution permissions (chmod +x) for the script you are calling. I’ve seen many builds fail post-task simply because of "Permission Denied" errors in the console output.
I agree with Brenda. Also, remember to use absolute paths or environment variables like ${WORKSPACE}/myscript.sh. Jenkins doesn't always inherit the standard shell environment you might expect, so explicitly defining the path is much safer for long-term stability.
David, in a Declarative Pipeline, the post block typically executes within the same node context if it's placed inside the pipeline or stage block. This means your workspace and file paths remain intact. However, if you define the post block outside of an agent-specific scope, you might lose access to that workspace. A good rule of thumb is to keep your cleanup or deployment scripts inside the post section of the specific stage that generates the files.