HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python deploy function using Fabric

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fabricfunctiondeployusingpython

Problem

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)

#

Solution


  • Using % for string formatting is deprecated. You should be using str.format() instead. Here's how one would use str.format(): print "Hello {0}.".format("world"). str.format() also supports using keyword arguments. Here's an example of that: print "Hello {word}.".format(word="world").



  • Near the end of the function deploy, underneath the if block with the condition os.path.isfile(local_file), you have comments above every line. These are unnecessary and can be removed.



  • Finally, I'm not sure why you have square brackets, [], around the value of the variable env.key_filename. If these aren't needed, they can be removed.

Context

StackExchange Code Review Q#93736, answer score: 3

Revisions (0)

No revisions yet.