我正在学习使用 Fabric 和 Boto 到目前为止,我已设法登录并创建了一个新实例。我现在如何在相同的fab文件中使用Python在新创建的服务器上安装Gunicorn?
即。我希望从这个文件中获取新实例和pip install。
这是我的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
答案 0 :(得分:2)
过去我必须做类似的事情。我结合了我认为重要的部分。完成设置后,您可以通过传递hosts参数列表,在主机或主机组上运行结构命令。希望这有帮助
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")
将新方法添加到结构函数类以运行pip命令
应该非常简单