Since 03-03, the last stage of orders-api has been called Deploy to dev, but all it does is print an echo that starts with "SIMULATION". That was the prudent choice: there was no target server, no real SSH credential and no published artifact. Now you have all of that except the server. In this lesson you will turn the simulation into a real deployment to dev-01.tecnoshop.local: you will prepare the server with a least-privilege deployment user and a systemd unit for the service, create the ssh-dev credential, verify the server's identity with known_hosts instead of disabling the check, and use the SSH Agent plugin to copy the jar, restart the service and check its health with retries. Then you will see when it makes sense to move to Ansible, with a playbook and its inventories, and take a quick tour of Terraform and cloud tooling. All with one principle: the pipeline orchestrates; the tool deploys.
Deployment Tools: An Overview
| Tool | What it does | When it fits | In the course |
|---|---|---|---|
| SSH / scp / rsync | Copy files and run commands on a server | A few servers, simple deployments of a single artifact | This lesson |
| Ansible | Configure servers and deploy declaratively and idempotently, over SSH and with no agents on the target | Several servers or environments, system configuration (packages, users, services) | This lesson |
| Terraform / OpenTofu | Create and modify infrastructure (machines, networks, databases, DNS) from code | Cloud or virtualized infrastructure | Overview in this lesson |
| kubectl / Helm | Deploy applications to Kubernetes | Applications in orchestrated containers | Jenkins and Kubernetes |
Cloud CLIs (aws, az, gcloud) |
Operate managed services (functions, containers, storage) | Deployments to the services of a specific cloud | Overview in this lesson |
| Jenkins-specific deployment plugins | Deploy to a specific application server through a form | Legacy cases | Discouraged: they tie the deployment to Jenkins |
Look at the last row. There are Jenkins plugins for deploying to almost anything, but each one adds a plugin to maintain (05-04) and, above all, means the deployment can only be done from Jenkins. If tomorrow someone has to deploy by hand in an emergency, or switch CI tools, the knowledge is locked inside a plugin's configuration.
The Pipeline Orchestrates, the Tool Deploys
This is the same rule as in 04-07 ("build logic lives in the tools"), applied to deployment:
| Responsibility | Who | Where it lives |
|---|---|---|
| When to deploy (branch, result, parameters) | The pipeline | The Jenkinsfile's when |
| What to deploy (the tested jar, its version) | The pipeline | unstash, APP_VERSION, BUILD_NUMBER |
| With what permissions (credentials) | Jenkins | Credentials and sshagent |
| How to deploy (copy, activate, restart, check) | The tool | deploy/deploy.sh or an Ansible playbook, versioned in the repository |
| What happened (result, links, notifications) | The pipeline | Build status, log, 06-07 |
The proof that the split is right: Laura can run the same script from her terminal, with her own key, if Jenkins is unavailable.
The Target: dev-01.tecnoshop.local
TecnoShop has three environments: dev, staging and production. This lesson only deploys to dev, to the dev-01.tecnoshop.local server, from the main branch. The staging server, staging-01.tecnoshop.local, exists and has the ssh-staging credential from 04-04, but promotion between environments, with its approvals, is the subject of Setting Up a CD Pipeline.
flowchart LR
subgraph J["Jenkins"]
A["linux-agent-01<br/>main build"]
end
subgraph D["dev-01.tecnoshop.local"]
S["sshd<br/>deploy user"]
R["/opt/orders-api/releases/"]
U["orders-api.service<br/>orders user, port 8081"]
end
A -->|"scp of the jar (ssh-dev key)"| S
S --> R
A -->|"ssh: activate version and<br/>sudo systemctl restart"| S
S --> U
A -->|"curl /actuator/health<br/>with retries"| U
Preparing the Server: Users, Directories and Least Privilege
On a real server with systemd (Debian, Ubuntu, RHEL...), Laura prepares dev-01 once, with two separate users:
| User | What for | Can | Cannot |
|---|---|---|---|
orders |
Run the application | Read the jar and its configuration | Log in (nologin shell), write to /opt/orders-api |
deploy |
Deploy: the one Jenkins uses over SSH | Upload jars to releases/, change the link to the active version, restart only orders-api.service |
Be root, edit the systemd unit, touch other services |
Separating whoever runs the application from whoever deploys it means that, if the application had a vulnerability, an attacker holding the orders user could not replace the jar; and if the Jenkins key leaked, the attacker could deploy a different jar, but not take over the server.
# On dev-01, as the administrator (once)
sudo apt-get install -y openjdk-21-jre-headless
sudo useradd --system --home-dir /opt/orders-api --shell /usr/sbin/nologin orders
sudo useradd --create-home --shell /bin/bash deploy
sudo mkdir -p /opt/orders-api/releases /etc/orders-api
sudo chown -R deploy:orders /opt/orders-api
sudo chmod 750 /opt/orders-api /opt/orders-api/releasesopenjdk-21-jre-headless: the Java 21 runtime, without graphical components. The package name varies by distribution.useradd --system ... --shell /usr/sbin/nologin orders: a system user with no interactive session.chown -R deploy:ordersandchmod 750:deploy(the owner) can write; theordersgroup can read and enter; everyone else, nothing.
The service's configuration file, /etc/orders-api/orders-api.env:
# orders-api configuration on dev-01
PORT=8081
JAVA_OPTS="-Xms128m -Xmx256m"
SPRING_PROFILES_ACTIVE=devPORT: the same8081the application uses by default.JAVA_OPTS: JVM memory. The quotes are needed so the value with spaces is read correctly.SPRING_PROFILES_ACTIVE=dev: Spring Boot enables thedevprofile; if there is ever anapplication-dev.properties, it will be applied.
She protects it with sudo chown root:orders /etc/orders-api/orders-api.env && sudo chmod 640 /etc/orders-api/orders-api.env: the service reads it, the deployment does not change it.
And the restart permission, in /etc/sudoers.d/deploy (always edited with sudo visudo -f /etc/sudoers.d/deploy, which checks the syntax before saving):
deploy ALL=(root): thedeployuser can run asroot...NOPASSWD:: ...without a password (Jenkins cannot type one).../usr/bin/systemctl restart orders-api.service: ...exactly this command, with these arguments.sudo systemctl stop sshdorsudo bashare rejected.
The orders-api.service Systemd Unit
systemd is the service manager of most Linux distributions: it starts services at boot, restarts them if they fail and collects their logs. A service is described with a unit file. The orders-api one is versioned in the repository, in deploy/orders-api.service, and installed in /etc/systemd/system/:
[Unit]
Description=TecnoShop orders-api (orders REST API)
Documentation=https://github.com/tecnoshop/orders-api
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=orders
Group=orders
WorkingDirectory=/opt/orders-api
EnvironmentFile=/etc/orders-api/orders-api.env
ExecStart=/usr/bin/java $JAVA_OPTS -jar /opt/orders-api/orders-api.jar --server.port=${PORT}
SuccessExitStatus=143
Restart=on-failure
RestartSec=5
TimeoutStopSec=30
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
[Install]
WantedBy=multi-user.targetSection by section:
[Unit]: metadata and startup order.DescriptionandDocumentation: shown bysystemctl status.After=andWants=network-online.target: start once the network is available.
[Service]: how it runs.Type=simple: theExecStartprocess is the service (it does not fork into the background).User=ordersandGroup=orders: it runs as the unprivileged user.WorkingDirectory: the process's working directory.EnvironmentFile: loads the variables from the.envfile above.ExecStart: the command.$JAVA_OPTS(without braces) is split into words, so-Xms128m -Xmx256marrives as two options;${PORT}is substituted as a single one. It points to/opt/orders-api/orders-api.jar, a symbolic link to the active version: deploying will mean changing the link and restarting.SuccessExitStatus=143: when systemd stops the service, it sendsSIGTERM, and the JVM exits with code 143 (128 + 15). Without this line, every normal stop would be logged as a failure.Restart=on-failureandRestartSec=5: if the application dies because of an error, systemd starts it again after 5 seconds.TimeoutStopSec=30: time for Spring Boot to shut down gracefully before the stop is forced.NoNewPrivileges,PrivateTmp,ProtectSystem=strict,ProtectHome: hardening. The process cannot gain privileges, has its own/tmp, sees the file system as read-only and cannot see home directories.orders-apionly needs to read its jar and write temporary files.
[Install]:WantedBy=multi-user.targetmakes the service start at boot once it is enabled.
The application's output goes to the systemd journal. To view it: journalctl -u orders-api.service -n 100 (or -f to follow it live).
Installation, once and as the administrator:
sudo cp orders-api.service /etc/systemd/system/orders-api.service
sudo systemctl daemon-reload
sudo systemctl enable orders-api.servicedaemon-reload: systemd rereads its units after one is added or changed.enable: it will start at boot. It is not started yet: there is no jar yet.
Optional Lab: The dev-01 Container
If you do not have a test server, you can simulate dev-01.tecnoshop.local with a container on the Compose network. Keep in mind the main limitation: a normal container does not run systemd. To keep the pipeline identical to the one for a real server, the container includes a small script that imitates systemctl restart|status orders-api.service. It is a lab simulation, and every file says so.
Create the ~/tecnoshop-jenkins/lab/dev-01/ directory with these files.
Dockerfile:
# LAB ONLY: simulates the dev-01.tecnoshop.local server (no systemd)
FROM eclipse-temurin:21-jre
RUN apt-get update \
&& apt-get install -y --no-install-recommends openssh-server sudo curl procps \
&& rm -rf /var/lib/apt/lists/* \
&& mkdir -p /run/sshd \
&& ssh-keygen -A \
&& useradd --system --home-dir /opt/orders-api --shell /usr/sbin/nologin orders \
&& useradd --create-home --shell /bin/bash deploy \
&& mkdir -p /opt/orders-api/releases /etc/orders-api /var/log/orders-api /home/deploy/.ssh \
&& chown -R deploy:orders /opt/orders-api \
&& chmod 750 /opt/orders-api /opt/orders-api/releases \
&& chown orders:orders /var/log/orders-api \
&& chown deploy:deploy /home/deploy/.ssh \
&& chmod 700 /home/deploy/.ssh
COPY sshd-tecnoshop.conf /etc/ssh/sshd_config.d/tecnoshop.conf
COPY sudoers-deploy /etc/sudoers.d/deploy
COPY systemctl-lab.sh /usr/bin/systemctl
COPY orders-api.env /etc/orders-api/orders-api.env
COPY --chown=deploy:deploy authorized_keys /home/deploy/.ssh/authorized_keys
RUN chmod 440 /etc/sudoers.d/deploy \
&& chmod 755 /usr/bin/systemctl \
&& chmod 600 /home/deploy/.ssh/authorized_keys \
&& chown root:orders /etc/orders-api/orders-api.env \
&& chmod 640 /etc/orders-api/orders-api.env
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D", "-e"]FROM eclipse-temurin:21-jre: an image with Java 21 (based on Ubuntu).openssh-server sudo curl procps: the SSH server,sudo,curland thepkill/pgreputilities the simulation uses.ssh-keygen -A: generates the SSH server's host keys when the image is built. That way they stay stable as long as you do not rebuild the image, and you can register them inknown_hosts.- The users, directories and permissions are the same as on the real server.
CMD ["/usr/sbin/sshd", "-D", "-e"]: runssshdin the foreground (-D) with its log on standard error (-e), which you will see withdocker compose logs dev-01.
sshd-tecnoshop.conf:
Key-only authentication, never as root and only for the deploy user.
sudoers-deploy: the same line as on the real server.
orders-api.env: the same configuration file as in the previous section.
systemctl-lab.sh:
#!/bin/sh
# LAB ONLY. Imitates "systemctl restart|status orders-api.service" in a container
# without systemd. On real servers, systemctl is the systemd one and this file does not exist.
set -eu
ACTION="${1:-}"
UNIT="${2:-}"
if [ "$UNIT" != "orders-api.service" ]; then
echo "systemctl (lab): only orders-api.service is supported" >&2
exit 1
fi
case "$ACTION" in
restart)
pkill -u orders -f 'orders-api.jar' || true
sleep 2
su -s /bin/sh orders -c 'set -a; . /etc/orders-api/orders-api.env; set +a;
cd /opt/orders-api &&
nohup java $JAVA_OPTS -jar /opt/orders-api/orders-api.jar --server.port=$PORT \
>> /var/log/orders-api/orders-api.log 2>&1 &'
echo "orders-api.service restarted (lab simulation)"
;;
status)
if pgrep -u orders -f 'orders-api.jar' > /dev/null; then
echo "orders-api.service: active (running) [lab simulation]"
else
echo "orders-api.service: inactive (dead) [lab simulation]"
exit 3
fi
tail -n 20 /var/log/orders-api/orders-api.log 2>/dev/null || true
;;
*)
echo "systemctl (lab): unsupported action: $ACTION" >&2
exit 1
;;
esacrestart: stops theordersuser's Java process (if there is one), waits and starts it again asorders, loading the same.envfile (set -aexports every variable read) and with the same command as the unit'sExecStart.status: says whether the process is alive and shows the end of the log, assystemctl statuswould.- Any other unit or action is rejected.
authorized_keys: the public key you will generate in the next section.
And the service in docker-compose.yml:
dev-01:
build: ./lab/dev-01
image: tecnoshop/lab-dev-01:1
container_name: dev-01
hostname: dev-01.tecnoshop.local
restart: unless-stopped
networks:
default:
aliases:
- dev-01.tecnoshop.localbuild+image: as with the controller in 05-04, Compose builds the image and tags it.networks.default.aliases: inside the Compose network, the namedev-01.tecnoshop.localresolves to this container. The pipeline will use the same name as at TecnoShop.- No published ports: the agent reaches
dev-01over the internal network (SSH on 22 and the application on 8081). If you want to see the API from your browser, you can addports: ["127.0.0.1:8181:8081"]; do not use the host's8081, which belongs toorders-apiwhen you run it locally.
The ssh-dev Credential
In 04-04 you created ssh-staging. For dev, TecnoShop creates a separate credential, ssh-dev, instead of reusing it:
- One key per environment: if the
devkey leaks (for example, becausedevhas looser controls), it does not grant access tostaging. - Independent rotation and revocation: you can change one without touching the other environment.
- Different usage:
ssh-devis used by everymainbuild;ssh-stagingonly by the CD pipeline, after approval (07-03).
Generate the key on your machine:
ssh-keygen -t ed25519 -f ./ssh-dev -N '' -C 'jenkins@tecnoshop-dev'
cp ./ssh-dev.pub ~/tecnoshop-jenkins/lab/dev-01/authorized_keys
cat ./ssh-devssh-dev(private) goes to Jenkins;ssh-dev.pub(public), to the server. On a real server, add it to/home/deploy/.ssh/authorized_keys.- In the lab, the public key is copied to
authorized_keysin thedev-01directory before the image is built.
In Jenkins, Add Credentials:
| Field | Value |
|---|---|
| Kind | SSH Username with private key |
| Scope | Global |
| ID | ssh-dev |
| Description | SSH for the deploy user on dev-01.tecnoshop.local. main builds only. Owner: Laura. |
| Username | deploy |
| Private Key | Enter directly → the full contents of ssh-dev |
Then delete the files from your machine (the public key is already in authorized_keys). Build and start the container:
Verifying the Server's Identity: known_hosts
When an SSH client connects to a server for the first time, the server presents its host key. If the client does not know it, it asks "do you trust this fingerprint?". Jenkins cannot answer, and the temptation is obvious:
# ANTI-PATTERN: never do this
ssh -o StrictHostKeyChecking=no [email protected] ...Disabling the check makes Jenkins connect to any server that responds under that name. If someone impersonated dev-01 (a tampered DNS record, a reassigned IP), Jenkins would hand over the jar and run its commands there without batting an eye. It is the same risk as the Non verifying strategy for the SSH agents in 05-01.
The solution is to register the server's key in advance, through a trusted channel:
- On the server itself (or, in the lab, in the container), get the fingerprint of its key:
256 SHA256:Xq3n...fake...k9U [email protected] (ED25519)
- From the agent, get the key as the network sees it and check that the fingerprint matches:
docker compose exec linux-agent-01 sh -c \
'ssh-keyscan -t ed25519 dev-01.tecnoshop.local 2>/dev/null | tee /tmp/kh && ssh-keygen -lf /tmp/kh'ssh-keyscan -t ed25519: asks the server for its ed25519 key.ssh-keygen -lf: computes the fingerprint of what was received.- If the two fingerprints (step 1 and step 2) are the same, the key is authentic.
- Save the line
ssh-keyscanprints (something likedev-01.tecnoshop.local ssh-ed25519 AAAAC3...) in thedeploy/known_hostsfile of theorders-apirepository and push it through a PR.
Why in the repository? A host key is public, not a secret. Versioning it has advantages: it travels with the code that uses it, any change goes through review (if it changes one day, someone has to approve it and ask why) and it does not depend on the state of the agent. If you rebuild the dev-01 image in the lab, its key will change and the deployment will fail with a changed-key warning: that is the correct behavior. Repeat the steps and update the file.
Before using SSH, check that the agent has the client:
The jenkins/inbound-agent image includes the OpenSSH client, because Git needs it. If it were missing in your version, the solution is not to install it by hand in the container (05-01), but a custom agent image (08-01).
The SSH Agent Plugin and sshagent
Install the SSH Agent plugin (ssh-agent) and add it to plugins.txt. It provides the sshagent step:
sshagent(credentials: ['ssh-dev']) {
sh 'ssh -o BatchMode=yes [email protected] hostname'
}sshagent(credentials: ['ssh-dev']): starts an ssh-agent (the standard OpenSSH program that holds keys in memory), loads the credential's private key into it and defines theSSH_AUTH_SOCKvariable inside the block.- Every
ssh,scp,rsync,gitover SSH oransiblerun inside the block uses the key without it ever existing as a file in the workspace. - When the block exits, the SSH agent stops and the key disappears from memory.
- The list accepts several credentials, in case a process needs to hop through several servers.
withCredentials([sshUserPrivateKey(...)]) (04-04) |
sshagent(credentials: [...]) |
|
|---|---|---|
| How it delivers the key | A temporary file and its path in a variable | Loaded into an in-memory ssh-agent |
Use with ssh |
You have to pass -i "$SSH_KEY" on every command |
Automatic |
| Tools that launch SSH on their own (Ansible, rsync, Git) | You have to configure them to use the file | They work unchanged |
| Additional plugin | No (Credentials Binding) | Yes (SSH Agent) |
The Deployment Script
Following the rule from section 2, the "how" lives in a versioned script, deploy/deploy.sh, in the orders-api repository:
#!/bin/sh
# Deploys the orders-api jar to a server over SSH and checks its health.
# Usage: deploy/deploy.sh <server>
# Requires: the SSH key loaded (sshagent in Jenkins, or ssh-agent locally)
# and the APP_VERSION and BUILD_NUMBER variables.
set -eu
SERVER="$1"
DEPLOY_USER="deploy"
APP_PORT="8081"
LOCAL_JAR=$(ls target/orders-api-*.jar)
DEPLOY_VERSION="${APP_VERSION}-${BUILD_NUMBER}"
RELEASE_PATH="/opt/orders-api/releases/orders-api-${DEPLOY_VERSION}.jar"
SSH_OPTS="-o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=deploy/known_hosts -o ConnectTimeout=10"
echo "==> Copying $LOCAL_JAR to $SERVER:$RELEASE_PATH"
scp $SSH_OPTS "$LOCAL_JAR" "$DEPLOY_USER@$SERVER:$RELEASE_PATH"
echo "==> Activating version $DEPLOY_VERSION and restarting orders-api.service"
ssh $SSH_OPTS "$DEPLOY_USER@$SERVER" "
set -e
ln -sfn '$RELEASE_PATH' /opt/orders-api/orders-api.jar
sudo systemctl restart orders-api.service
ls -1t /opt/orders-api/releases/orders-api-*.jar | tail -n +6 | xargs -r rm -f
"
echo "==> Checking health at http://$SERVER:$APP_PORT/actuator/health"
attempt=1
while [ "$attempt" -le 30 ]; do
if curl -sf "http://$SERVER:$APP_PORT/actuator/health" | grep -q '"status":"UP"'; then
echo "Deployment OK: orders-api $DEPLOY_VERSION is responding on $SERVER (attempt $attempt)"
exit 0
fi
attempt=$((attempt + 1))
sleep 2
done
echo "ERROR: orders-api is not responding UP on $SERVER after 60 seconds"
ssh $SSH_OPTS "$DEPLOY_USER@$SERVER" "systemctl status orders-api.service --no-pager" || true
exit 1Step by step:
set -eu: the script stops on any error and on undefined variables, likesmoke-spring-boot.shin 04-07.SERVER="$1": the server comes in as an argument; the same script will work for other environments.LOCAL_JAR=$(ls target/orders-api-*.jar): the jar the stage recovers withunstash.DEPLOY_VERSION: version and build number (1.1.0-SNAPSHOT-57), just like theIMAGE_TAGimage tag. Each deployment leaves a different file inreleases/.SSH_OPTS: the options common tosshandscp:BatchMode=yes: never ask anything (passwords, confirmations); if something requires interaction, it fails.StrictHostKeyChecking=yesandUserKnownHostsFile=deploy/known_hosts: it only connects if the server's key matches the one in the versioned file.ConnectTimeout=10: do not wait indefinitely if the server does not respond.- It is used unquoted (
$SSH_OPTS) on purpose, so the shell splits it into several options.
scp: copies the jar toreleases/under its versioned name.- The
ssh "..."block: commands on the server, in double quotes so that$RELEASE_PATHis substituted on the agent before they are sent.ln -sfn: points theorders-api.jarlink at the new version (-ssymbolic,-freplaces the existing one,-ntreats the link as a file rather than a directory).sudo systemctl restart orders-api.service: the only commandsudoersallows. It is synchronous: when it finishes, the previous process has stopped and the new one is starting.ls -1t ... | tail -n +6 | xargs -r rm -f: keeps the 5 most recent versions and deletes the older ones, so the disk does not fill up. Having the previous ones at hand makes rolling back easier, a topic for 07-04.
- The health loop: up to 30 attempts every 2 seconds against
/actuator/health, the same endpoint the integration test from 06-03 verified. Spring Boot takes a few seconds to start; a single immediate attempt would almost always fail. - If it does not respond, it shows the service status for diagnosis and exits with an error.
The check is done from the agent, over the network: that way it also verifies that the service is reachable from outside the server. If a firewall prevented that, the alternative is to check over SSH against localhost on the server itself.
For Laura, the same script works from her terminal: APP_VERSION=1.1.0-SNAPSHOT BUILD_NUMBER=manual sh deploy/deploy.sh dev-01.tecnoshop.local, with her own key in her ssh-agent.
The Real Deploy to dev Stage
The simulated stage:
stage('Deploy to dev') {
when {
allOf {
branch 'main'
expression { params.ENVIRONMENT == 'dev' }
expression { params.RUN_TESTS }
}
}
steps {
unstash 'jar'
echo "SIMULATION: this is where ... would be deployed ..."
}
}becomes:
stage('Deploy to dev') {
when {
allOf {
branch 'main'
expression { params.ENVIRONMENT == 'dev' }
expression { params.RUN_TESTS }
}
}
options {
timeout(time: 5, unit: 'MINUTES')
}
environment {
DEV_SERVER = 'dev-01.tecnoshop.local'
}
steps {
unstash 'jar'
sshagent(credentials: ['ssh-dev']) {
sh label: 'Deploy to dev-01 over SSH', script: 'sh deploy/deploy.sh "$DEV_SERVER"'
}
}
}whenunchanged: onlymain, only withENVIRONMENT=dev(the default) and only if the tests have run. No PR, branch or tag deploys.- A 5-minute
timeout: copying, restarting and waiting for health fits comfortably; if the server does not respond, the build does not hang. DEV_SERVERin the stage'senvironment: the target, in one place.unstash 'jar': the jar that was packaged, passedSmokeand was published to Nexus in this same build. Thanks to the reproducible jars from 06-05, it is identical to the one in Nexus. In the CD pipeline in 07-03, promotion tostagingwill download the artifact from Nexus by its version: "build once, deploy many times".sshagent(credentials: ['ssh-dev']): the key only exists during the deployment.sh deploy/deploy.sh "$DEV_SERVER": the script withshin front, so it does not depend on the execute bit in Git. The server comes in as a shell variable, in quotes.
The order of the pipeline guarantees that only what has passed everything before it gets deployed: Build, Checks, Integration tests, Quality analysis, Quality Gate, Package, Smoke and Publish. And disableConcurrentBuilds() prevents two main builds from deploying to dev-01 at the same time. (If several different jobs deployed to the same server, the Lockable Resources plugin and its lock step, which you met in 04-01, would keep them from stepping on each other.)
In the console of a main build:
[Pipeline] sshagent [ssh-agent] Using credentials deploy (SSH for the deploy user on dev-01.tecnoshop.local...) [ssh-agent] Looking for ssh-agent implementation... $ ssh-agent SSH_AUTH_SOCK=/tmp/ssh-XXXXfake/agent.1234 Identity added: /home/jenkins/agent/workspace/orders-api_main@tmp/private_key_...key (jenkins@tecnoshop-dev) [Pipeline] sh (Deploy to dev-01 over SSH) ==> Copying target/orders-api-1.1.0-SNAPSHOT.jar to dev-01.tecnoshop.local:/opt/orders-api/releases/orders-api-1.1.0-SNAPSHOT-57.jar ==> Activating version 1.1.0-SNAPSHOT-57 and restarting orders-api.service orders-api.service restarted (lab simulation) ==> Checking health at http://dev-01.tecnoshop.local:8081/actuator/health Deployment OK: orders-api 1.1.0-SNAPSHOT-57 is responding on dev-01.tecnoshop.local (attempt 6)
The Identity added line shows that the plugin uses a temporary file outside the workspace (in the @tmp directory) only to load the key into the SSH agent, and then deletes it; the exact detail depends on the plugin version. The "lab simulation" line only appears with the dev-01 container.
Check the result:
docker compose exec linux-agent-01 curl -s http://dev-01.tecnoshop.local:8081/api/orders
docker compose exec dev-01 ls -l /opt/orders-api/The second command shows the link orders-api.jar -> /opt/orders-api/releases/orders-api-1.1.0-SNAPSHOT-57.jar.
Ansible: When and How
The SSH script works well for one server and one artifact. It starts to fall short when:
- There are several servers per environment (two or more
staging-0N) and you have to deploy to them one at a time. - The deployment includes system configuration: installing Java, creating users, installing or changing the systemd unit, opening ports. Today Laura did it by hand; on the next server someone will forget a step.
- You want idempotence: running the deployment twice leaves the server the same as running it once, and it only restarts if something changed.
Ansible solves this with playbooks (YAML files that describe the desired state) that run over SSH from a control machine, without installing anything on the servers except Python.
Structure
In the orders-api repository:
deploy/
├── deploy.sh
├── known_hosts
├── orders-api.service
└── ansible/
├── deploy-orders-api.yml
├── inventory/
│ ├── dev.ini
│ └── staging.ini
└── roles/
└── orders_api/
├── defaults/main.yml
├── handlers/main.yml
├── tasks/main.yml
└── templates/orders-api.service.j2Inventories
deploy/ansible/inventory/dev.ini:
[orders_api]
dev-01.tecnoshop.local
[orders_api:vars]
ansible_user=deploy
ansible_ssh_common_args=-o UserKnownHostsFile=deploy/known_hosts -o StrictHostKeyChecking=yes
deploy_env=devdeploy/ansible/inventory/staging.ini:
[orders_api]
staging-01.tecnoshop.local
[orders_api:vars]
ansible_user=deploy
ansible_ssh_common_args=-o UserKnownHostsFile=deploy/known_hosts -o StrictHostKeyChecking=yes
deploy_env=staging[orders_api]: a group of servers. Addingstaging-02means adding one line.ansible_user: the SSH user.ansible_ssh_common_args: the same host key verification as the script (the path is relative to the directory Ansible runs from: the root of the workspace).deploy_env: a variable the templates will use.
The Playbook and the Role
deploy/ansible/deploy-orders-api.yml:
hosts: orders_api: the inventory group.become: true: tasks run withsudo(installing the unit, managing services).serial: 1: one server at a time. If the first one fails, the rest are not touched.roles: the logic lives in the reusableorders_apirole.
roles/orders_api/defaults/main.yml:
orders_api_jar_local: "" # path to the jar on the control machine (required)
orders_api_version: "" # e.g. 1.1.0-SNAPSHOT-57 (required)
orders_api_port: 8081
orders_api_java_opts: "-Xms128m -Xmx256m"
orders_api_dir: /opt/orders-apiroles/orders_api/tasks/main.yml:
- name: Check the required parameters
ansible.builtin.assert:
that:
- orders_api_jar_local | length > 0
- orders_api_version | length > 0
- name: Runtime user
ansible.builtin.user:
name: orders
system: true
shell: /usr/sbin/nologin
home: "{{ orders_api_dir }}"
create_home: false
- name: Application directories
ansible.builtin.file:
path: "{{ item }}"
state: directory
owner: deploy
group: orders
mode: "0750"
loop:
- "{{ orders_api_dir }}"
- "{{ orders_api_dir }}/releases"
- name: Configuration directory
ansible.builtin.file:
path: /etc/orders-api
state: directory
owner: root
group: orders
mode: "0750"
- name: Environment file
ansible.builtin.copy:
dest: /etc/orders-api/orders-api.env
content: |
PORT={{ orders_api_port }}
JAVA_OPTS="{{ orders_api_java_opts }}"
SPRING_PROFILES_ACTIVE={{ deploy_env }}
owner: root
group: orders
mode: "0640"
notify: Restart orders-api
- name: Systemd unit
ansible.builtin.template:
src: orders-api.service.j2
dest: /etc/systemd/system/orders-api.service
mode: "0644"
notify: Restart orders-api
- name: Copy the jar for this version
ansible.builtin.copy:
src: "{{ orders_api_jar_local }}"
dest: "{{ orders_api_dir }}/releases/orders-api-{{ orders_api_version }}.jar"
owner: deploy
group: orders
mode: "0640"
- name: Activate the version
ansible.builtin.file:
src: "{{ orders_api_dir }}/releases/orders-api-{{ orders_api_version }}.jar"
dest: "{{ orders_api_dir }}/orders-api.jar"
state: link
notify: Restart orders-api
- name: Service enabled at boot
ansible.builtin.systemd:
name: orders-api.service
enabled: true
daemon_reload: true
- name: Apply the pending restart now
ansible.builtin.meta: flush_handlers
- name: Wait for the application to respond UP
ansible.builtin.uri:
url: "http://localhost:{{ orders_api_port }}/actuator/health"
return_content: true
register: health
until: health.status == 200 and (health.json.status | default('')) == 'UP'
retries: 30
delay: 2roles/orders_api/handlers/main.yml:
- name: Restart orders-api
ansible.builtin.systemd:
name: orders-api.service
state: restarted
daemon_reload: truetemplates/orders-api.service.j2 is the unit from section 5 with {{ orders_api_dir }} instead of /opt/orders-api.
What is worth understanding, rather than memorizing:
- Each task describes a state ("this user exists", "this file has this content"), not an action. If it is already true, Ansible does nothing and marks it as
ok; if not, it applies it and marks it aschanged. notify: Restart orders-api+ handler: the restart only happens if a task that notifies it has changed something, and only once. If you deploy the same version twice, the second run restarts nothing: that is idempotence.meta: flush_handlers: runs the pending restart before checking health.uriwithuntil,retriesanddelay: the health check with retries, now from the server itself.- The server configuration (user, directories, unit) no longer depends on what Laura did by hand: it lives in the role.
Running It from the Pipeline
sshagent(credentials: ['ssh-dev']) {
sh '''
ansible-playbook -i deploy/ansible/inventory/dev.ini deploy/ansible/deploy-orders-api.yml \
-e "orders_api_jar_local=$(ls "$WORKSPACE"/target/orders-api-*.jar)" \
-e "orders_api_version=$APP_VERSION-$BUILD_NUMBER"
'''
}-i .../dev.ini: the inventory selects the environment. Forstaging, another inventory and another credential.-e: extra variables; the jar and the version, as in the script.sshagent: Ansible uses the ssh-agent automatically.
There is also an Ansible plugin for Jenkins, with the ansiblePlaybook step (playbook, inventory, credential and variables as parameters). It works, but it adds a plugin and a tool installation for something sh does just as well and that runs exactly as it does in Laura's terminal; TecnoShop prefers sh with sshagent.
Two considerations before adopting it:
- The agent needs Ansible, and
linux-agent-01does not have it (nor should it be installed by hand). It will run on an agent or container prepared for it, which you will see in Jenkins with Docker. In the lab, treat this section as reading material. become: trueneeds broadsudo: Ansible runs its modules withsudogenerically, so it cannot be restricted to "onlysystemctl restart" like the script'sdeployuser. The Ansible user is, in practice, an administrator of the server: its key must be different for each environment, be used only frommain(and, forstagingandproduction, after approval) and be protected accordingly.
| Criterion | SSH script (deploy.sh) |
Ansible |
|---|---|---|
| Servers | One or a few | Many, by groups and environments |
| System configuration | No (manual preparation) | Yes, declarative |
| Idempotence | You have to program it | Built in |
| Permissions on the server | Minimal (one specific sudo) |
Broad sudo |
| Requirements on the agent | SSH client and curl |
Ansible and its collections |
| TecnoShop's decision | dev today |
Once there are several servers per environment |
Terraform and the Cloud: An Overview
Ansible configures servers that exist. Terraform (and its open fork, OpenTofu) creates the infrastructure: virtual machines, networks, load balancers, databases, DNS records, from .tf files. The cycle is init (download providers), plan (work out what would change) and apply (apply it).
stage('Infrastructure: plan') {
steps {
withCredentials([string(credentialsId: 'cloud-terraform', variable: 'CLOUD_TOKEN')]) {
sh 'terraform -chdir=infra init -input=false'
sh 'terraform -chdir=infra plan -input=false -out=plan.tfplan'
}
stash name: 'terraform-plan', includes: 'infra/plan.tfplan'
}
}-chdir=infra: the Terraform files live ininfra/.-input=false: never prompt.-out=plan.tfplan: saves the plan so that exactly what was reviewed gets applied. A plan file can contain sensitive values: it is passed along withstash, not archived.cloud-terraformis an illustrative ID; how you authenticate depends on the provider.
The usual pattern in Jenkins is plan on every build (including PRs, to review the infrastructure change) and apply only on main and after approval, with the wait that does not hold executors you saw in 04-07. The Terraform state must be stored in remote storage with locking, never in the workspace.
To deploy to a cloud's managed services, the CLIs (aws, az, gcloud) are used like any other tool: on the agent, with sh, and with Jenkins credentials (each cloud's credential plugins provide specific types) or, better still, with short-lived federated identities, which avoid storing long-lived keys in Jenkins. Kubernetes deployments with kubectl and Helm arrive in 08-02.
The orders-api Delivery Stages
With this lesson, orders-api has its complete delivery chain for dev:
flowchart LR
E["Package<br/>jar + stash"] --> H["Smoke<br/>starts the jar"]
H --> P["Publish<br/>Nexus (main and tags)"]
P --> D["Deploy to dev<br/>dev-01 over SSH (main only)"]
| Stage | Branches | What it does |
|---|---|---|
Package |
All | Builds the jar and build-info.txt, archives them and saves the stash |
Smoke |
All | Starts the jar on the agent and checks that it responds |
Publish |
main (SNAPSHOT) and vX.Y.Z tags |
Uploads the artifact to Nexus |
Deploy to dev |
main |
Copies the jar to dev-01, restarts orders-api.service and checks /actuator/health |
You will see the complete Jenkinsfile, with the module's last piece (notifications), at the end of 06-07. Make the stage change on a branch with a PR: the PR build will not deploy (it is not main); after merging, the main build will do the first real deployment.
Common Mistakes and Tips
Host key verification failed: thedev-01key is not indeploy/known_hostsor it has changed (in the lab, when the image is rebuilt). Verify the fingerprint and update the file; never "fix" it withStrictHostKeyChecking=no.Permission denied (publickey): the public key is not in thedeployuser'sauthorized_keys, the credential has a different username, or the permissions on~/.sshare too open (sshd rejects them).sudo: a terminal is required to read the passwordorsorry, user deploy is not allowed to execute...: the command does not match the one insudoersexactly (a differentsystemctlpath, a different unit name, extra arguments).- The deployment "works" but the health check always fails: the service does not start (look at
journalctl -u orders-api.service), it listens on a different port or a firewall blocks 8081 from the agent. - Checking health only once, right after restarting: Spring Boot takes a few seconds to start. Without retries, the deployment fails even when it is fine.
- Using the same key for every environment: a leak in
devopens upstagingandproduction. - Deploying from a PR "to try it out": the
branch 'main'condition is there for a reason; to test deployments, use an ephemeral environment or a test server of your own. - Tip: leave everything needed to answer "what is in
devright now?" in the deployment log: version, build number and server. In 06-07 that same information will reach the team.
Exercises
Exercise 1. Set up the dev-01 container, create ssh-dev, register the host key in deploy/known_hosts and replace the simulated stage. After the first deployment, make two more commits on main. How many versions are there in /opt/orders-api/releases/ and which one does the link point to? Then rebuild the dev-01 image (docker compose up -d --build --force-recreate dev-01) and run a main build: what happens, and how do you resolve it correctly?
Exercise 2. A colleague proposes simplifying the deployment script like this: connect as root "so we don't have to fight with sudoers" and use -o StrictHostKeyChecking=no "because the container keeps changing its key". Write Laura's reply.
Exercise 3. TecnoShop is going to have two staging servers (staging-01 and staging-02). Diego proposes running deploy.sh twice in a row in the pipeline, once per server. Compare that with the Ansible playbook with serial: 1 and explain what happens in each case if the deployment to the first server fails the health check.
Solutions
Solution 1. After three deployments there are three jars in releases/ (for example, ...-57.jar, ...-58.jar and ...-59.jar; the cleanup only kicks in from the sixth one onward), and orders-api.jar points to the one from the last build, as ls -l /opt/orders-api/ shows. When you rebuild the image, ssh-keygen -A generates new host keys, and the next deployment fails at the scp with a warning that the server's identification has changed (REMOTE HOST IDENTIFICATION HAS CHANGED or Host key verification failed). The correct resolution is to repeat the verification procedure: get the new fingerprint in the container with ssh-keygen -lf, compare it with the one the agent sees with ssh-keyscan, and update deploy/known_hosts with a PR that explains why ("the dev-01 lab image was rebuilt"). On a real server, a key that changes without anyone having announced it is a reason to investigate before deploying anything.
Solution 2. "No. With root, the ssh-dev key would stop being a key for 'deploying orders-api' and would become an administration key for dev-01: anyone who got hold of it (or any PR that managed to run code with it) could do anything on the server. The deploy user with a single command in sudoers limits the damage to deploying a different jar. Besides, PermitRootLogin no is configured on purpose. As for StrictHostKeyChecking=no, it would make Jenkins hand over the jar and run commands on any machine that answered to the name dev-01.tecnoshop.local. The key changing when the lab container is rebuilt is exactly the warning we want to see: it is resolved by verifying the new fingerprint and updating known_hosts through a PR, in two minutes."
Solution 3. With two consecutive calls to deploy.sh, if the health check on staging-01 fails, the script exits with an error, the sh step fails and the pipeline stops: staging-02 is not touched, which is good. But staging-01 is left with the new version (which does not respond) active, and nothing about the servers' configuration (Java, user, unit) is guaranteed to be identical on both. With Ansible and serial: 1, the behavior on failure is the same (the uri task exhausts its retries, Ansible marks the server as failed and does not continue with staging-02), and in addition: the configuration is applied identically on both servers, adding a third one is one line in staging.ini, and redeploying the same version restarts nothing if there are no changes. In both cases, staging-01 is left in a state that needs fixing: what to do then (go back to the previous version, take it out of the load balancer) is the subject of Automating Deployments: Strategies and Rollback.
Conclusion
orders-api is now deployed for real. You know the landscape of tools (SSH, Ansible, Terraform, Kubernetes, cloud CLIs) and the principle that organizes them: the pipeline decides when, what and with which permissions; the tool, versioned in the repository, knows how. dev-01.tecnoshop.local runs the application as the systemd service orders-api.service with the unprivileged orders user, hardened and with the active version as a symbolic link; the deploy user can only upload versions and restart that service. In the lab, the dev-01 container simulates it, with a clearly labeled imitation systemctl. The ssh-dev credential, separate from ssh-staging, is used with the SSH Agent plugin and sshagent; the server's identity is verified with a versioned known_hosts, never by disabling the check; and deploy/deploy.sh copies the jar, activates the version, restarts and checks /actuator/health with retries in the Deploy to dev stage, only from main. You know when to move to an Ansible playbook with per-environment inventories, and what role Terraform and the cloud play. With a real deployment, the result of every main build matters more than ever: if it fails, someone needs to find out in time, and if it works again, they need to know that too. That is what you will solve in the module's last lesson, Notifications and Team Feedback.
