def connect():
metadata = boto.utils.get_instance_metadata()
region = metadata['placement']['availability-zone'][:-1]
for role in metadata['iam']['security-credentials'].keys():
conn = boto.ec2.connection.EC2Connection(
region=boto.ec2.get_region(region),
aws_access_key_id=metadata['iam']['security-credentials'][role]['AccessKeyId'],
aws_secret_access_key=metadata['iam']['security-credentials'][role]['SecretAccessKey'],
security_token=metadata['iam']['security-credentials'][role]['Token']
)
break
return conn
#
# Print out private IPv4
#
python类ec2()的实例源码
def _get_auto_scaling_group_lbs(self):
"""Returns a list of ELBs associated with self.instance_id
indirectly through its auto scaling group membership"""
try:
asg = connect_to_aws(boto.ec2.autoscale, self.region, **self.aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
self.module.fail_json(msg=str(e))
asg_instances = asg.get_all_autoscaling_instances([self.instance_id])
if len(asg_instances) > 1:
self.module.fail_json(msg="Illegal state, expected one auto scaling group instance.")
if not asg_instances:
asg_elbs = []
else:
asg_name = asg_instances[0].group_name
asgs = asg.get_all_groups([asg_name])
if len(asg_instances) != 1:
self.module.fail_json(msg="Illegal state, expected one auto scaling group.")
asg_elbs = asgs[0].load_balancers
return asg_elbs
def find_igw(vpc_conn, vpc_id):
"""
Finds the Internet gateway for the given VPC ID.
Raises an AnsibleIgwSearchException if either no IGW can be found, or more
than one found for the given VPC.
Note that this function is duplicated in other ec2 modules, and should
potentially be moved into potentially be moved into a shared module_utils
"""
igw = vpc_conn.get_all_internet_gateways(
filters={'attachment.vpc-id': vpc_id})
if not igw:
raise AnsibleIgwSearchException('No IGW found for VPC {0}'.
format(vpc_id))
elif len(igw) == 1:
return igw[0].id
else:
raise AnsibleIgwSearchException('Multiple IGWs found for VPC {0}'.
format(vpc_id))
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
filters = dict(default=None, type='dict')
)
)
module = AnsibleModule(argument_spec=argument_spec)
if not HAS_BOTO:
module.fail_json(msg='boto required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region:
try:
connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
else:
module.fail_json(msg="region must be specified")
list_ec2_instances(connection, module)
def ec2_connect(module):
""" Return an ec2 connection"""
region, ec2_url, boto_params = get_aws_connection_info(module)
# If we have a region specified, connect to its endpoint.
if region:
try:
ec2 = connect_to_aws(boto.ec2, region, **boto_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
# Otherwise, no region so we fallback to the old connection method
elif ec2_url:
try:
ec2 = boto.connect_ec2_endpoint(ec2_url, **boto_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
module.fail_json(msg=str(e))
else:
module.fail_json(msg="Either region or ec2_url must be specified")
return ec2
django_fabric_aws.py 文件源码
项目:Django-Fabric-AWS-Py3
作者: ankit-maverick
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def _create_ec2_instance():
"""
Creates EC2 Instance
"""
print(_yellow("Creating instance"))
conn = boto.ec2.connect_to_region(ec2_region, aws_access_key_id=fabconf['AWS_ACCESS_KEY'], aws_secret_access_key=fabconf['AWS_SECRET_KEY'])
image = conn.get_all_images(ec2_amis)
reservation = image[0].run(1, 1, ec2_keypair, ec2_secgroups,
instance_type=ec2_instancetype)
instance = reservation.instances[0]
conn.create_tags([instance.id], {"Name":fabconf['INSTANCE_NAME_TAG']})
while instance.state == u'pending':
print(_yellow("Instance state: %s" % instance.state))
time.sleep(10)
instance.update()
print(_green("Instance state: %s" % instance.state))
print(_green("Public dns: %s" % instance.public_dns_name))
return instance.public_dns_name
def blk_dev_map(opts, conf, itype, snapshots):
if not int(conf.get('NO_EBS', '0')):
bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
snap = project_ebs_snapshot(conf)
snap_id = translate_snapshot_name(conf, snap, snapshots)
snap_description = []
if snap_id:
dev = utils.blkdev(0)
bdm[dev] = boto.ec2.blockdevicemapping.EBSBlockDeviceType(snapshot_id=snap_id, delete_on_termination=True)
snap_description.append((snap, snap_id, dev))
i = 0
for k in additional_ebs_iterator(conf):
i += 1
snap = parse_ebs_url(conf[k].split(',')[0])
snap_id = translate_snapshot_name(conf, snap, snapshots)
if snap_id:
dev = utils.blkdev(i)
bdm[dev] = boto.ec2.blockdevicemapping.EBSBlockDeviceType(snapshot_id=snap_id, delete_on_termination=True)
snap_description.append((snap, snap_id, dev))
istore_dev = add_instance_store(opts, conf, bdm, itype)
return bdm, snap_description, istore_dev
else:
return None, None, None
def blk_dev_map(opts, conf, itype, snapshots):
if not int(conf.get('NO_EBS', '0')):
bdm = boto.ec2.blockdevicemapping.BlockDeviceMapping()
snap = project_ebs_snapshot(conf)
snap_id = translate_snapshot_name(conf, snap, snapshots)
snap_description = []
if snap_id:
dev = utils.blkdev(0)
bdm[dev] = boto.ec2.blockdevicemapping.EBSBlockDeviceType(snapshot_id=snap_id, delete_on_termination=True)
snap_description.append((snap, snap_id, dev))
i = 0
for k in additional_ebs_iterator(conf):
i += 1
snap = parse_ebs_url(conf[k].split(',')[0])
snap_id = translate_snapshot_name(conf, snap, snapshots)
if snap_id:
dev = utils.blkdev(i)
bdm[dev] = boto.ec2.blockdevicemapping.EBSBlockDeviceType(snapshot_id=snap_id, delete_on_termination=True)
snap_description.append((snap, snap_id, dev))
istore_dev = add_instance_store(opts, conf, bdm, itype)
return bdm, snap_description, istore_dev
else:
return None, None, None
def mount_ebs_volumes(host_config):
env.host_string = helper.get_env_host_string(host_config)
env.user = helper.get_env_user(host_config)
env.key_filename = helper.get_env_key_filename(host_config)
sudo("apt-get -y install xfsprogs")
for ebs in host_config['ec2-mounts']:
device = ebs['device']
mount = ebs['mount']
sudo("mkdir -p {}".format(mount))
sudo("mv /etc/fstab /etc/fstab.old")
sudo("touch /etc/fstab")
if sudo('mkfs.xfs -f {0}'.format(device), warn_only=True):
run("echo '{0}\t{1}\txfs\tdefaults\t0\t0' | sudo tee -a /etc/fstab".format(device, mount))
sudo('sudo mount -a')
logger.info("EBS volume {} : {} mounted.".format(device, mount))
def get_recent_instances(region, profile_name):
conn = boto.ec2.connect_to_region(region,
profile_name=profile_name)
reservations = conn.get_all_reservations()
instances = []
for res in reservations:
for i in res.instances:
if i.state != 'running':
continue
name = 'Name' in i.tags and i.tags['Name'] or i.dns_name
if i.private_ip_address:
desc = i.private_ip_address + u' [' + i.instance_type + ']'
else:
desc = u' [' + i.instance_type + ']'
instances.append({'desc': desc,
'ip': i.private_ip_address,
'name': name})
return instances
def lookup_instance(self, name):
try:
ec2_conn = boto.ec2.connect_to_region(region_name=self.region, profile_name=self.profile)
except Exception as e:
raise AnsibleError(e)
filters = {self.filter: name}
reservations = ec2_conn.get_all_instances(filters={'tag:name': 'nat-main'})
instances = [i for r in reservations for i in r.instances]
for instance in instances:
if instance.state == 'terminated' or instance.state == 'stopped':
continue
return instance.id.encode('utf-8')
return name
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
filters = dict(default=None, type='dict')
)
)
module = AnsibleModule(argument_spec=argument_spec)
if not HAS_BOTO:
module.fail_json(msg='boto required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region:
try:
connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e:
module.fail_json(msg=str(e))
else:
module.fail_json(msg="region must be specified")
list_ec2_volumes(connection, module)
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
filters = dict(default=None, type='dict')
)
)
module = AnsibleModule(argument_spec=argument_spec)
if not HAS_BOTO:
module.fail_json(msg='boto required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module)
if region:
try:
connection = connect_to_aws(boto.ec2, region, **aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError), e:
module.fail_json(msg=str(e))
else:
module.fail_json(msg="region must be specified")
list_ec2_volumes(connection, module)
def _keystone_aws_get(self):
import keystoneclient.v2_0.client
keystone = keystoneclient.v2_0.client.Client(**self.ks_cred)
ec2_cred_list = keystone.ec2.list(keystone.auth_user_id)
ec2_cred = None
for cred in ec2_cred_list:
if cred.tenant_id == keystone.auth_tenant_id:
ec2_cred = cred
break
else:
ec2_cred = keystone.ec2.create(keystone.auth_user_id,
keystone.auth_tenant_id)
if not all((ec2_cred, ec2_cred.access, ec2_cred.secret)):
raise exceptions.NotFound("Unable to get access and secret keys")
return ec2_cred
def get_ec2_instances(region, filters=None):
"""
Returns all EC2 instances on the specified region.
'filters' is passed to the 'get_all_reservations' function.
"""
conn = boto.ec2.connect_to_region(region)
reservations = conn.get_all_reservations(filters=filters)
instances = [i for r in reservations for i in r.instances]
return instances
def _get_connection(self):
if self._conn is not None:
return
self._conn = boto.ec2.connect_to_region(
self._region,
aws_access_key_id=self._aws_access_key_id,
aws_secret_access_key=self._aws_secret_access_key)
def detach_ebs(aws_access_key_id, aws_secret_access_key, devices):
import boto
import boto.ec2
meta = get_aws_instance_meta(boto.utils)
connection = boto.ec2.connect_to_region(
meta['region'],
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key
)
bd_mapping = get_aws_block_device_mapping(
connection, meta['instance-id']
)
for key, bd in bd_mapping.iteritems():
if key in devices:
connection.detach_volume(bd.volume_id)
def __init__(self):
self.region = None
self.name = None
self.instance_type = None
self.quantity = 0
self.zone = None
self.ami = None
self.groups = []
self.key = None
self.ec2 = None
self.config = None
def set_region(self, region=None):
if region:
self.region = region
else:
l = [(r, r.name, r.endpoint) for r in boto.ec2.regions()]
self.region = self.choose_from_list(l, prompt='Choose Region')
def set_zone(self, zone=None):
if zone:
self.zone = zone
else:
l = [(z, z.name, z.state) for z in self.ec2.get_all_zones()]
self.zone = self.choose_from_list(l, prompt='Choose Availability Zone')
def set_ami(self, ami=None):
if ami:
self.ami = ami
else:
l = [(a, a.id, a.location) for a in self.ec2.get_all_images()]
self.ami = self.choose_from_list(l, prompt='Choose AMI')
def add_group(self, group=None):
if group:
self.groups.append(group)
else:
l = [(s, s.name, s.description) for s in self.ec2.get_all_security_groups()]
self.groups.append(self.choose_from_list(l, prompt='Choose Security Group'))
def update_config(self):
if not self.config.has_section('Credentials'):
self.config.add_section('Credentials')
self.config.set('Credentials', 'aws_access_key_id', self.ec2.aws_access_key_id)
self.config.set('Credentials', 'aws_secret_access_key', self.ec2.aws_secret_access_key)
if not self.config.has_section('Pyami'):
self.config.add_section('Pyami')
sdb_domain = get_domain()
if sdb_domain:
self.config.set('Pyami', 'server_sdb_domain', sdb_domain)
self.config.set('Pyami', 'server_sdb_name', self.name)
def enter(self, **params):
self.region = params.get('region', self.region)
if not self.region:
self.set_region()
self.ec2 = self.region.connect()
self.name = params.get('name', self.name)
if not self.name:
self.set_name()
self.instance_type = params.get('instance_type', self.instance_type)
if not self.instance_type:
self.set_instance_type()
self.zone = params.get('zone', self.zone)
if not self.zone:
self.set_zone()
self.quantity = params.get('quantity', self.quantity)
if not self.quantity:
self.set_quantity()
self.ami = params.get('ami', self.ami)
if not self.ami:
self.set_ami()
self.groups = params.get('groups', self.groups)
if not self.groups:
self.add_group()
self.key = params.get('key', self.key)
if not self.key:
self.set_key()
self.config = params.get('config', self.config)
if not self.config:
self.set_config()
self.update_config()
def __init__(self, key, secret, account_id, instance, region, rate):
# Connect to region
self.conn = boto.ec2.connect_to_region(region, aws_access_key_id=key,
aws_secret_access_key=secret)
self.instance = instance
self.rate = float(rate)
def update_image(module, ec2):
"""
Updates AMI
"""
image_id = module.params.get('image_id')
launch_permissions = module.params.get('launch_permissions')
if 'user_ids' in launch_permissions:
launch_permissions['user_ids'] = [str(user_id) for user_id in launch_permissions['user_ids']]
img = ec2.get_image(image_id)
if img == None:
module.fail_json(msg = "Image %s does not exist" % image_id, changed=False)
try:
set_permissions = img.get_launch_permissions()
if set_permissions != launch_permissions:
if ('user_ids' in launch_permissions and launch_permissions['user_ids']) or ('group_names' in launch_permissions and launch_permissions['group_names']):
res = img.set_launch_permissions(**launch_permissions)
elif ('user_ids' in set_permissions and set_permissions['user_ids']) or ('group_names' in set_permissions and set_permissions['group_names']):
res = img.remove_launch_permissions(**set_permissions)
else:
module.exit_json(msg="AMI not updated", launch_permissions=set_permissions, changed=False)
module.exit_json(msg="AMI launch permissions updated", launch_permissions=launch_permissions, set_perms=set_permissions, changed=True)
else:
module.exit_json(msg="AMI not updated", launch_permissions=set_permissions, changed=False)
except boto.exception.BotoServerError as e:
module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))
def _get_instance_lbs(self, ec2_elbs=None):
"""Returns a list of ELBs attached to self.instance_id
ec2_elbs: an optional list of elb names that will be used
for elb lookup instead of returning what elbs
are attached to self.instance_id"""
if not ec2_elbs:
ec2_elbs = self._get_auto_scaling_group_lbs()
try:
elb = connect_to_aws(boto.ec2.elb, self.region, **self.aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
self.module.fail_json(msg=str(e))
elbs = []
marker = None
while True:
try:
newelbs = elb.get_all_load_balancers(marker=marker)
marker = newelbs.next_marker
elbs.extend(newelbs)
if not marker:
break
except TypeError:
# Older version of boto do not allow for params
elbs = elb.get_all_load_balancers()
break
if ec2_elbs:
lbs = sorted(lb for lb in elbs if lb.name in ec2_elbs)
else:
lbs = []
for lb in elbs:
for info in lb.instances:
if self.instance_id == info.id:
lbs.append(lb)
return lbs
def _get_elb_connection(self):
try:
return connect_to_aws(boto.ec2.elb, self.region,
**self.aws_connect_params)
except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e:
self.module.fail_json(msg=str(e))
def _get_ec2_connection(self):
try:
return connect_to_aws(boto.ec2, self.region,
**self.aws_connect_params)
except (boto.exception.NoAuthHandlerFound, StandardError) as e:
self.module.fail_json(msg=str(e))
def _check_attribute_support(self, attr):
return hasattr(boto.ec2.elb.attributes.LbAttributes(), attr)