AWS CodeDeploy Multiple Environments Shell Scripts

In a use case where you happen to have an instance that is used to deploy your application to a /development and /production directory(environment).

Note: Ideally you should have separate instance(s) for your different environments.

appspec.yml:

version: 0.0
os: linux
files:
- source: /
destination: /var/www/html
permissions:
- object: /home/ec2-user
owner: ec2-user
group: ec2-user
type:
- directory
- file
hooks:
AfterInstall:
- location: code_deploy/post_install.sh
timeout: 600
runas: ec2-user
ApplicationStart:
- location: code_deploy/run.sh
timeout: 120
runas: ec2-user

Here we check the environment variable $DEPLOYMENT_GROUP_NAME provided by the code deploy agent.

post_install.sh
# Copy source files to DEVELOPMENT environment
if [ "$DEPLOYMENT_GROUP_NAME" == "development" ]; then
sudo rsync -av /var/www/html/ /var/www/development/domain.com
cd /var/www/development/domain.com && npm install
fi
# Copy source files to PRODUCTION environment
if [ "$DEPLOYMENT_GROUP_NAME" == "production" ]; then
sudo rsync -av /var/www/html/ /var/www/production/domain.com
cd /var/www/production/domain.com && npm install
fi

Here we build our application.

# Build application in DEVELOPMENT
if [ "$DEPLOYMENT_GROUP_NAME" == "development" ]; then
cd /var/www/development/domain.com && yarn build
fi
# Build application in PRODUCTION
if [ "$DEPLOYMENT_GROUP_NAME" == "production" ]; then
cd /var/www/production/domain.com && yarn build
fi