我想动态更改env.hosts,因为有时我想首先部署到一台机器,检查是否可以然后部署到许多机器。 目前我需要首先设置env.hosts,如何在方法中设置env.hosts而不在脚本启动时设置为全局?
答案 0 :(得分:32)
是的,您可以动态设置env.hosts
。我们使用的一种常见模式是:
from fabric.api import env
def staging():
env.hosts = ['XXX.XXX.XXX.XXX', ]
def production():
env.hosts = ['YYY.YYY.YYY.YYY', 'ZZZ.ZZZ.ZZZ.ZZZ', ]
def deploy():
# Do something...
您可以使用它来链接fab staging deploy
或fab production deploy
等任务。
答案 1 :(得分:7)
有点迟到了,但是我用ec2这样做了(注意在EC2你不知道ip / hostname可能是什么,一般来说 - 所以你几乎要动态去真正考虑如何环境/系统可能出现 - 另一个选择是使用dyndns,但这仍然有用):
from fabric.api import *
import datetime
import time
import urllib2
import ConfigParser
from platform_util import *
config = ConfigParser.RawConfigParser()
@task
def load_config(configfile=None):
'''
***REQUIRED*** Pass in the configuration to use - usage load_config:</path/to/config.cfg>
'''
if configfile != None:
# Load up our config file
config.read(configfile)
# Key/secret needed for aws interaction with boto
# (anyone help figure out a better way to do this with sub modules, please don't say classes :-) )
global aws_key
global aws_sec
aws_key = config.get("main","aws_key")
aws_sec = config.get("main","aws_sec")
# Stuff for fabric
env.user = config.get("main","fabric_ssh_user")
env.key_filename = config.get("main","fabric_ssh_key_filename")
env.parallel = config.get("main","fabric_default_parallel")
# Load our role definitions for fabric
for i in config.sections():
if i != "main":
hostlist = []
if config.get(i,"use-regex") == 'yes':
for x in get_running_instances_by_regex(aws_key,aws_sec,config.get(i,"security-group"),config.get(i,"pattern")):
hostlist.append(x.private_ip_address)
env.roledefs[i] = hostlist
else:
for x in get_running_instances(aws_key,aws_sec,config.get(i,"security-group")):
hostlist.append(x.private_ip_address)
env.roledefs[i] = hostlist
if config.has_option(i,"base-group"):
if config.get(i,"base-group") == 'yes':
print "%s is a base group" % i
print env.roledefs[i]
# env["basegroups"][i] = True
其中get_running_instances和get_running_instances_by_regex是使用boto(http://code.google.com/p/boto/)的实用程序函数
例如:
import logging
import re
from boto.ec2.connection import EC2Connection
from boto.ec2.securitygroup import SecurityGroup
from boto.ec2.instance import Instance
from boto.s3.key import Key
########################################
# B-O-F get_instances
########################################
def get_instances(access_key=None, secret_key=None, security_group=None):
'''
Get all instances. Only within a security group if specified., doesnt' matter their state (running/stopped/etc)
'''
logging.debug('get_instances()')
conn = EC2Connection(aws_access_key_id=access_key, aws_secret_access_key=secret_key)
if security_group:
sg = SecurityGroup(connection=conn, name=security_group)
instances = sg.instances()
return instances
else:
instances = conn.get_all_instances()
return instances
以下是我的配置的示例:
# Config file for fabric toolset
#
# This specific configuration is for <whatever> related hosts
#
#
[main]
aws_key = <key>
aws_sec = <secret>
fabric_ssh_user = <your_user>
fabric_ssh_key_filename = /path/to/your/.ssh/<whatever>.pem
fabric_default_parallel = 1
#
# Groupings - Fabric knows them as roledefs (check env dict)
#
# Production groupings
[app-prod]
security-group = app-prod
use-regex = no
pattern =
[db-prod]
security-group = db-prod
use-regex = no
pattern =
[db-prod-masters]
security-group = db-prod
use-regex = yes
pattern = mysql-[d-s]01
答案 2 :(得分:3)
旧问题的另一个新答案。 :)但我最近发现自己试图动态设置主机,并且真的不得不反对主要答案。我对 dynamic 的想法,或者至少是我尝试做的事情,是采用刚刚由boto
创建的实例DNS名称,并使用fab命令访问该实例。我无法执行fab staging deploy
,因为实例在fabfile编辑时存在。
幸运的是,fabric
支持使用execute进行真正动态的主机分配。 (当问题首先被问到时,这可能不存在,但现在确实如此)。 Execute允许您定义要调用的函数和它应该用于该命令的 env.hosts 。例如:
def create_EC2_box(data=fab_base_data):
conn = boto.ec2.connect_to_region(region)
reservations = conn.run_instances(image_id=image_id, ...)
...
return instance.public_dns_name
def _ping_box():
run('uname -a')
run('tail /var/log/cloud-init-output.log')
def build_box():
box_name = create_EC2_box(fab_base_data)
new_hosts = [box_name]
# new_hosts = ['ec2-54-152-152-123.compute-1.amazonaws.com'] # testing
execute(_ping_box, hosts=new_hosts)
现在我可以执行fab build_box
,它会触发一个创建实例的boto
调用,以及另一个在新实例上运行的fabric
调用 - 不带必须在编辑时定义实例名称。