How to use the boto.ec2.connect_to_region function in boto

To help you get started, we’ve selected a few boto examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github spulec / moto / tests / test_cloudformation / test_cloudformation_stack_integration.py View on Github external
"Fn::If": [
                            "EnvEqualsPrd",
                            "ami-00000000",
                            "ami-ffffffff"
                        ]
                    },
                },
                "Type": "AWS::EC2::Instance"
            },
        }
    }
    dummy_template_json = json.dumps(dummy_template)

    conn = boto.cloudformation.connect_to_region("us-west-1")
    conn.create_stack('test_stack1', template_body=dummy_template_json)
    ec2_conn = boto.ec2.connect_to_region("us-west-1")
    reservation = ec2_conn.get_all_instances()[0]
    ec2_instance = reservation.instances[0]
    ec2_instance.image_id.should.equal("ami-ffffffff")
    ec2_instance.terminate()

    conn = boto.cloudformation.connect_to_region("us-west-2")
    conn.create_stack(
        'test_stack1', template_body=dummy_template_json, parameters=[("ENV", "prd")])
    ec2_conn = boto.ec2.connect_to_region("us-west-2")
    reservation = ec2_conn.get_all_instances()[0]
    ec2_instance = reservation.instances[0]
    ec2_instance.image_id.should.equal("ami-00000000")
github aws / aws-parallelcluster / node / sqswatcher / sqswatcher.py View on Github external
eventType = message_attrs['Event']
                except KeyError:
                    log.warn("Unable to read message. Deleting.")
                    q.delete_message(result)
                    break

                log.info("eventType=%s" % eventType)
                if eventType == 'autoscaling:TEST_NOTIFICATION':
                    q.delete_message(result)

                if eventType != 'autoscaling:TEST_NOTIFICATION':
                    instanceId = message_attrs['EC2InstanceId']
                    log.info("instanceId=%s" % instanceId)
                    if eventType == 'cfncluster:COMPUTE_READY':
                        ec2 = boto.connect_ec2()
                        ec2 = boto.ec2.connect_to_region(region,proxy=boto.config.get('Boto', 'proxy'),
                                          proxy_port=boto.config.get('Boto', 'proxy_port'))

                        retry = 0
                        wait = 15
                        while retry < 3:
                            try:
                                hostname = ec2.get_all_instances(instance_ids=instanceId)

                                if not hostname:
                                    log.warning("Unable to find running instance %s." % instanceId)
                                else:
				    log.info("Adding Hostname: %s" % hostname)
                                    hostname = hostname[0].instances[0].private_dns_name.split('.')[:1][0]
                                    s.addHost(hostname,cluster_user)

                                    t.put_item(data={
github electroniceagle / ansible-dc-ec2-tutorial / inventory / ec2.py View on Github external
def get_instances_by_region(self, region):
        ''' Makes an AWS EC2 API call to the list of instances in a particular
        region '''

        try:
            if self.eucalyptus:
                conn = boto.connect_euca(host=self.eucalyptus_host)
                conn.APIVersion = '2010-08-31'
            else:
                conn = ec2.connect_to_region(region)

            # connect_to_region will fail "silently" by returning None if the region name is wrong or not supported
            if conn is None:
                print("region name: %s likely not supported, or AWS is down.  connection to region failed." % region)
                sys.exit(1)

            reservations = []
            if self.ec2_instance_filters:
                for filter_key, filter_values in self.ec2_instance_filters.iteritems():
                    reservations.extend(conn.get_all_instances(filters = { filter_key : filter_values }))
            else:
                reservations = conn.get_all_instances()

            for reservation in reservations:
                for instance in reservation.instances:
                    self.add_instance(instance, region)
github compatibleone / accords-platform / pyaccords / pysrc / ec2client.py View on Github external
def ec2_get_image(accesskey, secretkey,imgname, zone):
	EC2_IMAGE_TO_AMI = {
		"ubuntu" : "ami-ad184ac4",
		"debian" : "ami-3428ba5d",
		"suse" : "ami-e8084981",
		"redhat" : "ami-a25415cb",
		"centos" : "ami-07b73c6e",
		"windows" : "ami-7527031c",
	}
	imgos = ec2_get_os(imgname)
	conn = boto.ec2.connect_to_region(zone,aws_access_key_id=accesskey,aws_secret_access_key=secretkey)
	image = conn.get_all_images(filters={'name' : imgname})
	if (image):
		if (image[0]):
			imagestr = str(image[0]).split(":")
			ec2imageid = imagestr[1]
			return ec2imageid
		else:
			images = conn.get_all_images()
			for myimage in images:
				if(myimage.name):
					if imgname in myimage.name:
						imagestr = str(myimage).split(":")
						ec2imageid = imagestr[1]
						return ec2imageid
	if(EC2_IMAGE_TO_AMI.has_key(imgos)):
			return EC2_IMAGE_TO_AMI[imgos]
github EverythingMe / fabric-aws / fabric_aws / __init__.py View on Github external
"""
    Hosts generator for running a task on all instances matching `*args` and `**kwargs`
    `*args` and `**kwargs` are passed-through to the underlying boto.ec2.get_all_instances() function

    :param region: AWS region
    :type region: str
    :param hostname_attribute: `boto.ec2.instance.Instance` attribute to use as hostname for fabric connection
    :type hostname_attribute: str
    :param *args: pass-through arguments to the underlying boto.ec2.get_all_instances() function
    :param *kwargs: pass-through keyword arguments to the underlying boto.ec2.get_all_instances() function
    :return: Generates a list of hosts
    :rtype: list[str]
    """

    hostname_attribute = kwargs.pop('hostname_attribute', 'public_dns_name')
    ec2_connection = boto.ec2.connect_to_region(region)

    reservations = ec2_connection.get_all_instances(*args, **kwargs)

    hosts = [getattr(instance, hostname_attribute)
             for reservation in reservations
             for instance in reservation.instances]

    # this will make our function lazy
    for host in hosts:
        yield host
github znb / Elastic-Elephant / Transforms / GetEgressDestination.py View on Github external
# Pull all the egress destinations attached to an egress rule

from MaltegoTransform import *
import boto.ec2
import sys
from init import load_credentials

creds = load_credentials()
REGION = creds[2]

m = MaltegoTransform()
m.parseArguments(sys.argv)
egress_dst = m.getVar("GroupID")

try:
    conn = boto.ec2.connect_to_region(REGION, aws_access_key_id=creds[0], aws_secret_access_key=creds[1])

    reservations = conn.get_all_instances()

    for i in reservations:
        group_nums = len(i.instances[0].groups)
        for z in range(group_nums):
            group_id = i.instances[0].groups[z].id
            if str(group_id) == str(egress_dst):
                egress_rules = conn.get_all_security_groups(group_ids=group_id)[0].rules_egress
                number_of_egress = len(egress_rules)
                for g in range(number_of_egress):
                    ent = m.addEntity('matterasmus.AmazonEC2IngressSource', str(conn.get_all_security_groups(group_ids=group_id)[0].rules[g].grants))
                    ent.addAdditionalFields("Source", "Source", "strict", str(conn.get_all_security_groups(group_ids=group_id)[0].rules[g].grants))
                    ent.addAdditionalFields("GroupID", "Group ID", "strict", str(group_id))

    m.addUIMessage("Completed.")
github omidm / nimbus / ec2 / obsolete / ec2.py View on Github external
def stop_instances(location, placement_group='*'):
  ec2 = boto.ec2.connect_to_region(location)
  instances = ec2.get_only_instances(
      filters={"placement-group-name":placement_group})
  for inst in instances:
    ec2.stop_instances(instance_ids=[inst.id])
github ashokfernandez / Django-Fabric-AWS---amazon_app / fabfile / django_fabric_aws.py View on Github external
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))
github daniellawrence / aws-map / main.py View on Github external
def get_subnet_list(vpc_conn, vpc_id):
    raw_subnet_list = vpc_conn.get_all_subnets(filters={'vpc_id': vpc_id})
    subnet_list = []
    
    ec2_conn = boto.ec2.connect_to_region('ap-southeast-2',
        aws_access_key_id=AWS_ACCESS_KEY_ID,
        aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
    
    for s in raw_subnet_list:
        id = s.id
        cidr_block = s.cidr_block
        name = s.tags['Name']
        #print "\t", name, cidr_block

        if SHOW_IP:
            childern_list = get_network_interfaces(ec2_conn, filters={'subnet_id': id})
        else:    
            childern_list = get_ec2_list(ec2_conn, filters={'subnet_id': id})
        so = Subnet(id, name, cidr_block, child=childern_list)

        #print so.dot()