appspec_versioned_stop_server

Learn how to stop a server process using a bash script for CodeDeploy. This utility helps manage application deployments efficiently.

CodeDeploy AppSpec Versioned Stop Server Script

This section provides a bash script designed to be used within an AWS CodeDeploy AppSpec file. Its primary purpose is to gracefully stop a running server process, ensuring a clean shutdown before subsequent deployment steps are executed. This script is particularly useful for versioned deployments where you need to ensure the old version is fully stopped before the new one starts.

Bash Script for Stopping Server Processes

The following script checks for the existence of a systemd service named python-app.service. If found, it initiates a stop command using systemctl. A brief delay is included to allow the service to stop gracefully. The script then enters a loop, polling the service status until it is no longer active, confirming the server has been stopped.

Script Details and Usage

This script is typically placed in the AfterInstall or BeforeInstall hooks of your CodeDeploy AppSpec file. It leverages standard Linux commands and systemctl for service management.

#!/usr/bin/env bash
DATESTAMP="$(date +%FT%H:%m)"

if [ -f "/etc/systemd/system/python-app.service" ]
then
  sudo systemctl stop python-app
  sleep 5
  while [ "$(sudo systemctl is-active python-app)" == "active" ] 
  do
    sleep 5
  done
  echo "[${DATESTAMP}] application stopped"
fi

CodeDeploy AppSpec Integration

Integrating this script into your CodeDeploy workflow ensures that your application instances are properly managed during deployments. By stopping the server before proceeding, you minimize the risk of conflicts or downtime.

Best Practices for Deployment Scripts

Always test your deployment scripts thoroughly in a staging environment before deploying to production. Ensure that error handling is robust and that logs are informative for debugging purposes. For more information on CodeDeploy AppSpec files, refer to the AWS CodeDeploy documentation.