本文整理汇总了Python中boto.ec2.autoscale.AutoScaleConnection.get_all_groups方法的典型用法代码示例。如果您正苦于以下问题:Python AutoScaleConnection.get_all_groups方法的具体用法?Python AutoScaleConnection.get_all_groups怎么用?Python AutoScaleConnection.get_all_groups使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类boto.ec2.autoscale.AutoScaleConnection
的用法示例。
在下文中一共展示了AutoScaleConnection.get_all_groups方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
def main():
parser = optparse.OptionParser()
parser.add_option( "-c", "--config", dest="config_file", help="AutoScale config INI", metavar="FILE" )
(options, args) = parser.parse_args()
logging.info( "Using config file [%s]" % options.config_file )
config = parse_config( options.config_file )
aws_access = config.get("AWS", 'access')
aws_secret = config.get("AWS", 'secret')
logging.debug( "Connecting to AWS with access [%s] and secret [%s]" % ( aws_access, aws_secret ) )
aws_connection = AutoScaleConnection( aws_access, aws_secret )
print "AutoScalingGroups:"
print aws_connection.get_all_groups().__dict__
示例2: create_autoscaling_group
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
def create_autoscaling_group():
global img
conn = AutoScaleConnection(os.environ['AWS_ACCESS_KEY_ID'], os.environ['AWS_SECRET_ACCESS_KEY'])
autoscale = boto.ec2.autoscale.connect_to_region('us-east-1')
print conn.get_all_groups()
timestamp = time.time()
value = datetime.datetime.fromtimestamp(timestamp)
humanreadabledate = value.strftime('%Y-%m-%d_%H.%M.%S')
config_name = 'live_launch_config'+humanreadabledate
init_script = "#!/bin/sh /home/ec2-user/sds/deployment_scripts/initialize_server.py"
lc = LaunchConfiguration(name=config_name, image_id=img,
key_name='SDSEastKey',
security_groups=['sg-a7afb1c2'],
user_data=init_script)
conn.create_launch_configuration(lc)
ag = AutoScalingGroup(group_name=config_name, load_balancers=['SDSLiveLoadBalancer'], availability_zones=['us-east-1a'], launch_config=lc, min_size=2, max_size=2, connection=conn)
conn.create_auto_scaling_group(ag)
示例3: autoscale_group_hosts
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
def autoscale_group_hosts(group_name):
import boto.ec2
from boto.ec2.autoscale import AutoScaleConnection
ec2 = boto.connect_ec2()
conn = AutoScaleConnection()
groups = conn.get_all_groups(names=[])
groups = [ group for group in groups if group.name.startswith(group_name) ]
instance_ids = []
instances = []
for group in groups:
print group.name
instance_ids.extend([i.instance_id for i in group.instances])
instances.extend(ec2.get_only_instances(instance_ids))
return [i.private_ip_address for i in instances], instances[0].id, instances[0].tags.get("aws:autoscaling:groupName")
示例4: _is_up_to_date
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
def _is_up_to_date():
"""
Returns True if this instance is up to date.
"""
# Retrieve instance information.
conn = AutoScaleConnection()
pool = conn.get_all_groups(["LSDA Worker Pool"])[0]
config = conn.get_all_launch_configurations(
names=[pool.launch_config_name])[0]
# Retrive the AMI for this instance and for others.
config_ami = config.image_id
my_ami = urllib.urlopen("http://169.254.169.254/latest/"
"meta-data/ami-id").read()
return config_ami == my_ami
示例5: launch_auto_scaling
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
def launch_auto_scaling(stage = 'development'):
config = get_provider_dict()
from boto.ec2.autoscale import AutoScaleConnection, AutoScalingGroup, LaunchConfiguration, Trigger
conn = AutoScaleConnection(fabric.api.env.conf['AWS_ACCESS_KEY_ID'], fabric.api.env.conf['AWS_SECRET_ACCESS_KEY'], host='%s.autoscaling.amazonaws.com' % config['location'][:-1])
for name, values in config.get(stage, {}).get('autoscale', {}):
if any(group.name == name for group in conn.get_all_groups()):
fabric.api.warn(fabric.colors.orange('Autoscale group %s already exists' % name))
continue
lc = LaunchConfiguration(name = '%s-launch-config' % name, image_id = values['image'], key_name = config['key'])
conn.create_launch_configuration(lc)
ag = AutoScalingGroup(group_name = name, load_balancers = values.get('load-balancers'), availability_zones = [config['location']], launch_config = lc, min_size = values['min-size'], max_size = values['max-size'])
conn.create_auto_scaling_group(ag)
if 'min-cpu' in values and 'max-cpu' in values:
tr = Trigger(name = '%s-trigger' % name, autoscale_group = ag, measure_name = 'CPUUtilization', statistic = 'Average', unit = 'Percent', dimensions = [('AutoScalingGroupName', ag.name)],
period = 60, lower_threshold = values['min-cpu'], lower_breach_scale_increment = '-1', upper_threshold = values['max-cpu'], upper_breach_scale_increment = '2', breach_duration = 60)
conn.create_trigger(tr)
示例6: delete_autoscaling
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
def delete_autoscaling():
con = AutoScaleConnection(aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
aws_access_key_id=AWS_ACCESS_KEY,
region=RegionInfo(name=REGION,
endpoint='autoscaling.%s.amazonaws.com' % REGION))
print "Deleting autoscaling group.."
group = con.get_all_groups(names=[AUTOSCALING_GROUP_NAME])[0]
print "shutting down instances"
group.shutdown_instances()
time.sleep(LONG_SLEEP_PERIOD)
print "Deleting autoscaling group itself"
con.delete_auto_scaling_group(AUTOSCALING_GROUP_NAME, force_delete=True)
print "Deleting launch configuration"
con.delete_launch_configuration(AUTOSCALING_GROUP_NAME)
con.close()
示例7: get_asg_connection
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
def get_asg_connection():
conn = AutoScaleConnection()
autoscale_groups = conn.get_all_groups(max_records=1)
return conn
示例8: EbsHelper
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
#.........这里部分代码省略.........
cname_prefix=cname_prefix,
description=description,
option_settings=option_settings,
tier_type=tier_type,
tier_name=tier_name,
tier_version=tier_version)
def environment_exists(self, env_name, include_deleted=False):
"""
Returns whether or not the given environment exists
"""
response = self.ebs.describe_environments(application_name=self.app_name, environment_names=[env_name],
include_deleted=include_deleted)
return len(response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments']) > 0 \
and response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments'][0][
'Status'] != 'Terminated'
def environment_resources(self, env_name):
"""
Returns the description for the given environment's resources
"""
resp = self.ebs.describe_environment_resources(environment_name=env_name)
return resp['DescribeEnvironmentResourcesResponse']['DescribeEnvironmentResourcesResult']['EnvironmentResources']
def get_env_sizing_metrics(self, env_name):
asg = self.get_asg(env_name)
if asg:
return asg.min_size, asg.max_size, asg.desired_capacity
else:
return None, None, None
def get_asg(self, env_name):
asg_name = self.get_asg_name(env_name)
asgs = self.autoscale.get_all_groups(names=[asg_name])
asg = None
if asgs:
asg = asgs[0]
return asg
def get_asg_name(self, env_name):
resources = self.environment_resources(env_name)
name = resources["AutoScalingGroups"][0]["Name"]
return name
def set_env_sizing_metrics(self, env_name, min_size, max_size):
self.update_environment(env_name, option_settings=[
("aws:autoscaling:asg", "MinSize", min_size), ("aws:autoscaling:asg", "MaxSize", max_size)])
def environment_data(self, env_name):
"""
Returns the description for the given environment
"""
response = self.ebs.describe_environments(application_name=self.app_name, environment_names=[env_name],
include_deleted=False)
return response['DescribeEnvironmentsResponse']['DescribeEnvironmentsResult']['Environments'][0]
def rebuild_environment(self, env_name):
"""
Rebuilds an environment
"""
out("Rebuilding " + str(env_name))
self.ebs.rebuild_environment(environment_name=env_name)
def get_environments(self):
"""
Returns the environments
示例9: __init__
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
class WatchData:
datafile = "/tmp/watchdata.p"
dry = False
low_limit = 70
high_limit = 90
high_urgent = 95
stats_period = 120
history_size = 0
def __init__(self):
self.name = ''
self.instances = 0
self.new_desired = 0
self.desired = 0
self.instances_info = None
self.previous_instances = 0
self.action = ""
self.action_ts = 0
self.changed_ts = 0
self.total_load = 0
self.avg_load = 0
self.max_load = 0
self.up_ts = 0
self.down_ts= 0
self.max_loaded = None
self.loads = {}
self.measures = {}
self.emergency = False
self.history = None
def __getstate__(self):
""" Don't store these objets """
d = self.__dict__.copy()
del d['ec2']
del d['cw']
del d['autoscale']
del d['group']
del d['instances_info']
return d
def connect(self, groupname):
self.ec2 = boto.connect_ec2()
self.cw = CloudWatchConnection()
self.autoscale = AutoScaleConnection()
self.group = self.autoscale.get_all_groups(names=[groupname])[0]
self.instances = len(self.group.instances)
self.desired = self.group.desired_capacity
self.name = groupname
def get_instances_info(self):
ids = [i.instance_id for i in self.group.instances]
self.instances_info = self.ec2.get_only_instances(instance_ids = ids)
def get_CPU_loads(self):
""" Read instances load and store in data """
for instance in self.group.instances:
load = self.get_instance_CPU_load(instance.instance_id)
if load is None:
continue
self.total_load += load
self.loads[instance.instance_id] = load
if load > self.max_load:
self.max_load = load
self.max_loaded = instance.instance_id
self.avg_load = self.total_load/self.instances
def get_instance_CPU_load(self, instance):
end = datetime.datetime.now()
start = end - datetime.timedelta(seconds=300)
m = self.cw.get_metric_statistics(self.stats_period, start, end, "CPUUtilization", "AWS/EC2", ["Average"], {"InstanceId": instance})
if len(m) > 0:
self.measures[instance] = len(m)
ordered = sorted(m, key=lambda x: x['Timestamp'], reverse=True)
return ordered[0]['Average']
return None
@classmethod
def from_file(cls):
try:
data = pickle.load( open(cls.datafile, "rb" ))
except:
data = WatchData()
return data
def store(self, annotation = False):
if self.history_size > 0:
if not self.history: self.history = []
self.history.append([int(time.time()), len(self.group.instances), int(round(self.total_load))])
self.history = self.history[-self.history_size:]
pickle.dump(self, open(self.datafile, "wb" ))
if annotation:
import utils
text = json.dumps(self.__getstate__(), skipkeys=True)
utils.store_annotation("ec2_watch", text)
#.........这里部分代码省略.........
示例10: __init__
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
#.........这里部分代码省略.........
if instance_ids:
lb.register_instances(instance_ids)
params = {
"LoadBalancerNames.member.1": lb.name,
"Tags.member.1.Key": "15619project",
"Tags.member.1.Value": project_tag_value,
}
lb.connection.get_status("AddTags", params, verb="POST")
return lb
def remove_elb(self, name):
self.elb_conn.delete_load_balancer(name)
def create_launch_configuration(self, name, image, key_name, security_groups, instance_type):
lcs = [l for l in self.auto_scale_conn.get_all_launch_configurations() if l.name == name]
lc = lcs[0] if lcs else None
if not lc:
lc = LaunchConfiguration(
name=name,
image_id=image,
key_name=key_name,
security_groups=[security_groups],
instance_type=instance_type,
)
self.auto_scale_conn.create_launch_configuration(lc)
return lc
def remove_launch_configuration(self, name):
self.auto_scale_conn.delete_launch_configuration(name)
def create_autoscaling_group(self, name, lb_name, zone, tags, instance_ids=None):
lc = self.create_launch_configuration()
as_groups = [a for a in self.auto_scale_conn.get_all_groups() if a.name == name]
as_group = as_groups[0] if as_groups else None
if not as_group:
as_group = AutoScalingGroup(
group_name=name,
load_balancers=[lb_name],
availability_zones=[zone],
launch_config=lc,
min_size=4,
max_size=4,
health_check_type="ELB",
health_check_period=120,
connection=self.auto_scale_conn,
default_cooldown=self.default_cooldown,
desired_capacity=4,
tags=tags,
)
self.auto_scale_conn.create_auto_scaling_group(as_group)
if instance_ids:
self.auto_scale_conn.attach_instances(name, instance_ids)
scale_up_policy = ScalingPolicy(
name="scale_up",
adjustment_type="ChangeInCapacity",
as_name=name,
scaling_adjustment=1,
cooldown=self.default_cooldown,
)
scale_down_policy = ScalingPolicy(
name="scale_down",
adjustment_type="ChangeInCapacity",
as_name=name,
示例11: BotoScaleInterface
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
class BotoScaleInterface(ScaleInterface):
conn = None
saveclcdata = False
def __init__(self, clc_host, access_id, secret_key, token):
#boto.set_stream_logger('foo')
path='/services/AutoScaling'
port=8773
if clc_host[len(clc_host)-13:] == 'amazonaws.com':
clc_host = clc_host.replace('ec2', 'autoscaling', 1)
path = '/'
reg = None
port=443
reg = RegionInfo(name='eucalyptus', endpoint=clc_host)
self.conn = AutoScaleConnection(access_id, secret_key, region=reg,
port=port, path=path,
is_secure=True, security_token=token, debug=0)
self.conn.https_validate_certificates = False
self.conn.http_connection_kwargs['timeout'] = 30
def __save_json__(self, obj, name):
f = open(name, 'w')
json.dump(obj, f, cls=BotoJsonScaleEncoder, indent=2)
f.close()
##
# autoscaling methods
##
def create_auto_scaling_group(self, as_group):
return self.conn.create_auto_scaling_group(as_group)
def delete_auto_scaling_group(self, name, force_delete=False):
return self.conn.delete_auto_scaling_group(name, force_delete)
def get_all_groups(self, names=None, max_records=None, next_token=None):
obj = self.conn.get_all_groups(names, max_records, next_token)
if self.saveclcdata:
self.__save_json__(obj, "mockdata/AS_Groups.json")
return obj
def get_all_autoscaling_instances(self, instance_ids=None, max_records=None, next_token=None):
obj = self.conn.get_all_autoscaling_instances(instance_ids, max_records, next_token)
if self.saveclcdata:
self.__save_json__(obj, "mockdata/AS_Instances.json")
return obj
def set_desired_capacity(self, group_name, desired_capacity, honor_cooldown=False):
group = self.conn.get_all_groups([group_name])[0];
# notice, honor_cooldown not supported.
return group.set_capacity(desired_capacity)
def set_instance_health(self, instance_id, health_status, should_respect_grace_period=True):
return self.conn.set_instance_health(instance_id, health_status,
should_respect_grace_period)
def terminate_instance(self, instance_id, decrement_capacity=True):
return self.conn.terminate_instance(instance_id, decrement_capacity)
def update_autoscaling_group(self, as_group):
as_group.connection = self.conn
return as_group.update()
def create_launch_configuration(self, launch_config):
return self.conn.create_launch_configuration(launch_config)
def delete_launch_configuration(self, launch_config_name):
return self.conn.delete_launch_configuration(launch_config_name)
def get_all_launch_configurations(self, config_names, max_records, next_token):
obj = self.conn.get_all_launch_configurations(names=config_names, max_records=max_records, next_token=next_token)
if self.saveclcdata:
self.__save_json__(obj, "mockdata/AS_LaunchConfigs.json")
return obj
示例12: create_autoscaling
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
def create_autoscaling(ami_id, sns_arn):
"""
Creates the autoscaling group for proxy instances
Inspired by boto autoscaling tutorial.
"""
con = AutoScaleConnection(aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
aws_access_key_id=AWS_ACCESS_KEY,
region=RegionInfo(name=REGION,
endpoint='autoscaling.%s.amazonaws.com' % REGION))
print "Creating autoscaling configuration.."
config = LaunchConfiguration(name=AUTOSCALING_GROUP_NAME,
image_id=ami_id,
key_name=KEY_NAME,
security_groups=[EC2_SECURITY_GROUP_NAME],
instance_type=INSTANCE_TYPE)
con.create_launch_configuration(config)
print "Create autoscaling group..."
ag = AutoScalingGroup(name=AUTOSCALING_GROUP_NAME,
launch_config=config,
availability_zones=["{0}a".format(REGION)],
load_balancers=[ELB_NAME],
min_size=AUTOSCALING_MIN_INSTANCES,
max_size=AUTOSCALING_MAX_INSTANCES,
group_name=AUTOSCALING_GROUP_NAME)
con.create_auto_scaling_group(ag)
# fetch the autoscale group after it is created (unused but may be necessary)
_ = con.get_all_groups(names=[AUTOSCALING_GROUP_NAME])[0]
# Create tag name for autoscaling-created machines
as_tag = Tag(key='Name', value=AUTOSCALING_GROUP_NAME, propagate_at_launch=True, resource_id=AUTOSCALING_GROUP_NAME)
con.create_or_update_tags([as_tag])
print "Creating autoscaling policy..."
scaleup_policy = ScalingPolicy(name='scale_up',
adjustment_type='ChangeInCapacity',
as_name=AUTOSCALING_GROUP_NAME,
scaling_adjustment=1,
cooldown=AUTOSCALING_COOLDOWN_PERIOD)
scaledown_policy = ScalingPolicy(name='scale_down',
adjustment_type='ChangeInCapacity',
as_name=AUTOSCALING_GROUP_NAME,
scaling_adjustment=-1,
cooldown=AUTOSCALING_COOLDOWN_PERIOD)
con.create_scaling_policy(scaleup_policy)
con.create_scaling_policy(scaledown_policy)
# Get freshened policy objects
scaleup_policy = con.get_all_policies(as_group=AUTOSCALING_GROUP_NAME, policy_names=['scale_up'])[0]
scaledown_policy = con.get_all_policies(as_group=AUTOSCALING_GROUP_NAME, policy_names=['scale_down'])[0]
print "Creating cloudwatch alarms"
cloudwatch_con = CloudWatchConnection(aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
aws_access_key_id=AWS_ACCESS_KEY,
region=RegionInfo(name=REGION,
endpoint='monitoring.%s.amazonaws.com' % REGION))
alarm_dimensions = {"AutoScalingGroupName": AUTOSCALING_GROUP_NAME}
scaleup_alarm = MetricAlarm(name='scale_up_on_cpu',
namespace='AWS/EC2',
metric='CPUUtilization',
statistic='Average',
comparison='>',
threshold=AUTOSCALING_CPU_MAX_THRESHOLD,
period='60',
evaluation_periods=1,
alarm_actions=[scaleup_policy.policy_arn, sns_arn],
dimensions=alarm_dimensions)
# Don't send SNS on scaledown policy
scaledown_alarm = MetricAlarm(name='scale_down_on_cpu',
namespace='AWS/EC2',
metric='CPUUtilization',
statistic='Average',
comparison='<',
threshold=AUTOSCALING_CPU_MIN_THRESHOLD,
period='60',
evaluation_periods=1,
alarm_actions=[scaledown_policy.policy_arn],
dimensions=alarm_dimensions)
cloudwatch_con.create_alarm(scaleup_alarm)
cloudwatch_con.create_alarm(scaledown_alarm)
示例13: test_basic
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
def test_basic(self):
# NB: as it says on the tin these are really basic tests that only
# (lightly) exercise read-only behaviour - and that's only if you
# have any autoscale groups to introspect. It's useful, however, to
# catch simple errors
print('--- running %s tests ---' % self.__class__.__name__)
c = AutoScaleConnection()
self.assertTrue(repr(c).startswith('AutoScaleConnection'))
groups = c.get_all_groups()
for group in groups:
self.assertIsInstance(group, AutoScalingGroup)
# get activities
activities = group.get_activities()
for activity in activities:
self.assertIsInstance(activity, Activity)
# get launch configs
configs = c.get_all_launch_configurations()
for config in configs:
self.assertIsInstance(config, LaunchConfiguration)
# get policies
policies = c.get_all_policies()
for policy in policies:
self.assertIsInstance(policy, ScalingPolicy)
# get scheduled actions
actions = c.get_all_scheduled_actions()
for action in actions:
self.assertIsInstance(action, ScheduledUpdateGroupAction)
# get instances
instances = c.get_all_autoscaling_instances()
for instance in instances:
self.assertIsInstance(instance, Instance)
# get all scaling process types
ptypes = c.get_all_scaling_process_types()
for ptype in ptypes:
self.assertTrue(ptype, ProcessType)
# get adjustment types
adjustments = c.get_all_adjustment_types()
for adjustment in adjustments:
self.assertIsInstance(adjustment, AdjustmentType)
# get metrics collection types
types = c.get_all_metric_collection_types()
self.assertIsInstance(types, MetricCollectionTypes)
# create the simplest possible AutoScale group
# first create the launch configuration
time_string = '%d' % int(time.time())
lc_name = 'lc-%s' % time_string
lc = LaunchConfiguration(name=lc_name, image_id='ami-2272864b',
instance_type='t1.micro')
c.create_launch_configuration(lc)
found = False
lcs = c.get_all_launch_configurations()
for lc in lcs:
if lc.name == lc_name:
found = True
break
assert found
# now create autoscaling group
group_name = 'group-%s' % time_string
group = AutoScalingGroup(name=group_name, launch_config=lc,
availability_zones=['us-east-1a'],
min_size=1, max_size=1)
c.create_auto_scaling_group(group)
found = False
groups = c.get_all_groups()
for group in groups:
if group.name == group_name:
found = True
break
assert found
# now create a tag
tag = Tag(key='foo', value='bar', resource_id=group_name,
propagate_at_launch=True)
c.create_or_update_tags([tag])
found = False
tags = c.get_all_tags()
for tag in tags:
if tag.resource_id == group_name and tag.key == 'foo':
found = True
break
assert found
c.delete_tags([tag])
# shutdown instances and wait for them to disappear
#.........这里部分代码省略.........
示例14:
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
conn_cw = boto.ec2.cloudwatch.connect_to_region(regionName)
conn_cw = boto.ec2.cloudwatch.connect_to_region(
regionName,
aws_access_key_id = AWS_ACCESS_KEY,
aws_secret_access_key = AWS_SECRET_KEY
)
######################### end configuration ################################
# balancers = elb.get_all_load_balancers()
# print balancers[0]
# retrieve the instances in the autoscale group
group = conn_as.get_all_groups(names=[autoscaling_group['name']])[0]
instanceids = [i.instance_id for i in group.instances]
instances = conn_ec2.get_only_instances(instanceids)
print instances
# # shutdown all the instances in the autogroup instances
ag = conn_as.get_all_groups()[0]
print "shutdown the instances in the autoscaling group"
ag.shutdown_instances()
sleep(20)
# # delete the autoscale group
print "delete the autoscaling group"
ag.delete()
开发者ID:BlackSugarr,项目名称:HybridCloudInteroperabilityExplorationProject,代码行数:33,代码来源:AWS_stop_autoscaling.py
示例15: Cloud
# 需要导入模块: from boto.ec2.autoscale import AutoScaleConnection [as 别名]
# 或者: from boto.ec2.autoscale.AutoScaleConnection import get_all_groups [as 别名]
class Cloud(object):
def __init__(self, cloud_config):
self.config = cloud_config
self.all_instances = []
self.failed_launch = False
self.failed_count = 0
self.failed_last_valid_count = 0
self._conn = None
self._as_conn = None
self._lc = None
self._asg = None
self._last_asg_launch_attempt = None
self.maxed = False
self._last_launch_attempt = datetime.datetime.utcnow()
self._initialize()
def _create_connection(self):
LOG.debug("Creating connection for %s" % self.config.name)
self._conn = boto.connect_ec2(self.config.access_id,
self.config.secret_key,
validate_certs=False)
self._conn.host = self.config.cloud_uri
self._conn.port = self.config.cloud_port
def _create_autoscale_connection(self):
LOG.debug("Creating autoscale connection for %s" % self.config.name)
region = RegionInfo(name=self.config.cloud_type,
endpoint=self.config.as_uri)
self._as_conn = AutoScaleConnection(
aws_access_key_id=self.config.access_id,
aws_secret_access_key=self.config.secret_key,
is_secure=True,
port=self.config.as_port,
region=region,
validate_certs=False)
def _create_or_set_launch_configuration(self):
name = self.config.lc_name
if not self._lc:
LOG.debug("Attempting to load launch configuration: %s" % (name))
lc = self._as_conn.get_all_launch_configurations(names=[name])
if len(lc) == 1:
LOG.debug("Launch configuration %s found." % (name))
self._lc = lc[0]
if not self._lc:
#TODO(pdmars): key and security groups are hardcoded for now, gross
if self.config.user_data_file is not None:
user_data_file = self.config.user_data_file
with open(user_data_file) as f:
user_data = f.read()
else:
user_data = None
LOG.debug("Creating launch configuration %s" % name)
LOG.debug("\tname: %s" % name)
LOG.debug("\timage_id: %s" % self.config.image_id)
LOG.debug("\tinstance_type: %s" % self.config.instance_type)
LOG.debug("\tuser_data: %s" % user_data)
self._lc = LaunchConfiguration(
name=name,
image_id=self.config.image_id,
key_name="phantomkey",
security_groups=['default'],
instance_type=self.config.instance_type,
user_data=user_data)
self._as_conn.create_launch_configuration(self._lc)
def _create_or_set_autoscale_group(self):
name = self.config.asg_name
if not self._asg:
LOG.debug("Attempting to load autoscale group: %s" % name)
asg = self._as_conn.get_all_groups(names=[name])
LOG.debug("Autoscale group: %s" % asg)
if len(asg) == 1:
LOG.debug("Autoscale group %s found." % name)
self._asg = asg[0]
if not self._asg:
# TODO(pdmars): more hard coded grossness, for now
try:
cloud_guess = self.config.lc_name.split("@")[1].strip()
except Exception as e:
LOG.warn("Unable to guess cloud for auto scale tags")
LOG.warn("Setting cloud to hotel")
cloud_guess = "hotel"
policy_name_key = "PHANTOM_DEFINITION"
policy_name = "error_overflow_n_preserving"
ordered_clouds_key = "clouds"
n_preserve_key = "minimum_vms"
ordered_clouds = cloud_guess + ":-1"
n_preserve = 0
policy_tag = Tag(connection=self._as_conn, key=policy_name_key,
value=policy_name, resource_id=name)
clouds_tag = Tag(connection=self._as_conn, key=ordered_clouds_key,
value=ordered_clouds, resource_id=name)
npreserve_tag = Tag(connection=self._as_conn, key=n_preserve_key,
value=n_preserve, resource_id=name)
tags = [policy_tag, clouds_tag, npreserve_tag]
zones = [self.config.az]
LOG.debug("Creating autoscale group %s" % name)
LOG.debug("\tname: %s" % name)
LOG.debug("\tavailability_zones: %s" % zones)
#.........这里部分代码省略.........