使用Fabric进行Python部署
我正在学习使用Fabric和Boto,到目前为止我已经成功登录并创建了一个新的实例。接下来,我想知道如何在下面的新服务器上使用Python在同一个fab文件中安装Gunicorn。
也就是说,我希望能够通过这个文件来获取新实例并安装包。
这是我的fab.py文件,目前的内容是:
SERVER_TYPES = {
'web' : {
'image_id' : 'ami-xxxxxx',
'instance_type' : 't1.micro',
'security_groups' : [MAIN_SG],
'key_name' : MAIN_KP,
},
}
class EC2Conn:
def __init__(self):
print(_green("Started..."))
self.ec2conn = None
self.user = 'fabUser'
self.access_key = 'xxxxxx'
self.secret_key = 'xxxxxxxxxxxx'
def connect(self):
print(_green("Connecting..."))
region = ec2.get_region('eu-west-1')
self.ec2conn = ec2.connection.EC2Connection(self.access_key,
self.secret_key, region=region)
def get_instances(self):
return self.ec2conn.get_all_instances()
def create_instance(self, instance_type='web', address=None):
reservation = self.ec2conn.run_instances( **SERVER_TYPES[instance_type])
print reservation
instance = reservation.instances[0]
time.sleep(10)
while instance.state != 'running':
time.sleep(5)
instance.update()
print "Instance state: %s" % (instance.state)
print "instance %s done!" % (instance.id)
def create_instance():
a = EC2Conn()
a.connect()
return a.create_instance()
所以我想要的效果大概是这样的:
def install_stuff(using self.ec2conn)
using ec2 instance
run('pip install gunicorn')
etc
1 个回答
2
我以前也做过类似的事情。我把我认为重要的部分结合在一起了。一旦设置好,你就可以通过传递一个主机列表来在一台或多台主机上运行fabric命令。希望这对你有帮助。
from fabric.api import *
import socket
socket.setdefaulttimeout(5)
# Setup fabric details
env.user = 'fabric-user'
env.key_filename = '/root/.ssh/fabric_rsa'
def execute_remote(command):
return run(command)
@parallel
def execute_remote_parallel(command):
return run(command)
def run_fabric(cmd,hosts,in_parallel):
""" Check the parameters and call the corresponding fabric block"""
if in_parallel:
return execute(execute_remote_parallel,command=cmd,hosts=hosts)
else:
return execute(execute_remote,command=cmd,hosts=hosts)
class FabricFunctions:
def stop_service(self,hosts,in_parallel,servicename):
cmd = "sudo /sbin/service %s stop" % servicename
run_fabric(cmd, hosts, in_parallel)
def start_service(self,hosts,in_parallel,servicename):
cmd = "sudo /sbin/service %s start" % servicename
run_fabric(cmd, hosts, in_parallel)
#
# Example - Untested!
#
f = FabricFunctions()
f.start_service("ec2-instance-ip",False,"httpd")
在fabric函数类中添加新方法来运行pip命令应该是非常简单的。