- Prerequisites
- Adding the Deploy Stage
- Stopping & Removing the Existing Container
- Running the New Container
- Wrapping in a
scriptBlock - Conditional Execution with
when - Verifying the Deployment
- Links and References
Prerequisites
- A Jenkins instance with the SSH Agent plugin installed
- An AWS EC2 Ubuntu server accessible via SSH
- A Dockerized application pushed to a Docker registry
- Jenkins credentials configured for:
- SSH key (e.g.,
aws-dev-deploy-ec2-instance) - MongoDB username & password (
mongo-db-username,mongo-db-password)
- SSH key (e.g.,
1. Adding the Deploy Stage
After yourPush Docker Image stage, insert a new stage called Deploy - AWS EC2. Here’s the skeleton of your declarative pipeline:
We’ll use the SSH Agent plugin to authenticate to EC2 using the private key credential
aws-dev-deploy-ec2-instance.
2. Stopping & Removing the Existing Container
Use an SSH one-liner to detect if thesolar-system container is running, then stop and remove it:
Suppressing
StrictHostKeyChecking avoids interactive host key prompts, which is essential for unattended CI/CD pipelines.3. Running the New Container
Next, start a fresh container with your environment variables. These variables come from the globalenvironment block in your Jenkinsfile:
4. Wrapping in a script Block
Because we’re using conditional logic (if), wrap the SSH commands in a script step inside the declarative stage:
5. Conditional Execution with when
Run the deploy stage only on feature branches by adding a when condition. You can also configure this filter in the Jenkins UI:
Using
when { branch 'feature/*' } ensures that deployment only triggers for feature branches, preventing accidental prod deployments.6. Verifying the Deployment
-
Check Jenkins Console
Sample logs:
-
On the EC2 Instance
Expected output:
-
Access the Application
Open a browser and navigate to: