appspec_versioned_start_server

Automate server startup with this bash script for CodeDeploy. Learn how to restart your Python application using systemctl.

Start Server Script

CodeDeploy AppSpec Server Start Script

This section provides a bash script designed for use with AWS CodeDeploy to manage the startup of your application. The script ensures that your application service is restarted and logs the action with a timestamp.

Bash Script for Server Restart

The following script is intended to be part of your CodeDeploy AppSpec file, typically under the AfterInstall or ApplicationStart hooks. It uses systemctl to restart a service named python-app.

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

sudo systemctl restart python-app
echo "[${DATESTAMP}] application started"

Script Explanation

This script performs two main actions:

  • Timestamp Generation: It captures the current date and time in the ISO 8601 format (YYYY-MM-DDTHH:MM) and stores it in the DATESTAMP variable. This is useful for logging and auditing deployment activities.
  • Service Restart: It uses sudo systemctl restart python-app to restart the system service named python-app. This command requires root privileges, hence the use of sudo. Ensure that a systemd service file for your Python application is correctly configured on the target instances.
  • Logging: Finally, it echoes a message to standard output indicating that the application has been started, including the generated timestamp. This output can be viewed in the CodeDeploy deployment logs.

Integrating with CodeDeploy

To use this script, include it in your appspec.yml file within the appropriate lifecycle event hook. For example, under the ApplicationStart hook:

version: 0.0
Resources:
  - TargetService:
      Type: AWS::ECS::Service
      Properties:
        TaskDefinition: arn:aws:ecs:us-east-1::task-definition/my-task-definition:1
        LoadBalancerInfo:
          ContainerName: my-app-container
          TargetGroupArn: arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/my-target-group/6d07f730a7400439
Hooks:
  ApplicationStart:
    - Location: scripts/start_server.sh
      Timeout: 300
      Runas: root

Make sure the script file (e.g., scripts/start_server.sh) is included in your deployment bundle and has execute permissions.

Further Resources