Simple task - deploy war-file from TeamCity agent to remote web-server.
I realized it with Fabric
, because of it make readable output, and give opportunity to login via SSH with RSA-key. Also - during deploy - build agent must make some additional steps - create backup, stop-start Tomcat service etc.
URL to deploy to can be passed via variable on build-server.
import os
import sys
import time
from fabric.api import run, env, put
VAR_PREFIX = 'bamboo_'
"""Cloudlibrary functions"""
def deploy(logger, rds_basedir):
"""Deploy cloudlibrary.war to remote box, passed via BASE_URL"""
logger.logger.info('Running cloudlibrary.war deploy')
# file to deploy
local_file = 'target/cloudlibrary.war'
# local_file = 'd:\\RDS\\rdsmanager\\file.txt'
# file will be created during backup command
back_file = '/home/ec2-user/backups/cloudlibrary/cloudlibrary_%s.war' % time.strftime('%Y-%m-%d')
# commands list
status = 'sudo service tomcat7 status'
backup = 'cp /var/lib/tomcat7/webapps/cloudlibrary.war %s' % back_file
check_bkp = 'file %s' % back_file
tomcat_kill = 'sudo kill -9 $(cat /var/run/tomcat7.pid)'
tomcat_start = 'sudo /etc/init.d/tomcat7 start'
try:
base_url = os.environ[VAR_PREFIX + 'BASE_URL']
logger.logger.info('\nURL found %s' % base_url)
except KeyError:
base_url = 'www.dev.domain.com'
logger.logger.info('URL variable not found, will default - %s' % base_url)
# Fabric connection settings
env.host_string = base_url
env.key_filename = [os.path.join(rds_basedir, '.ssh', 'rdsmanager_priv.openssh')]
env.user = 'user'
env.project_root = '/var/lib/tomcat7/webapps'
logger.logger.info('Using URL: %s, user: %s, RDS-key: %s, Tomcat webapps: %s' % (env.host_string, env.user, env.key_filename[0], env.project_root))
if os.path.isfile(local_file):
# make backup of current cloudlibrary.war to ~/backup/cloulibrary
run(backup)
# if new file doesn't found - Fabric will exit
run(check_bkp)
# stop Omcat before put new war-file
run(tomcat_kill)
# put new builded war-file
put(local_file, env.project_root)
# start Tomcat
run(tomcat_start)
# cgeck it's status
run(status)
else:
logger.logger.error('ERROR: file %s not found. Exit.' % local_file)
sys.exit(1)