Requests the RunInstances EC2 API call but accounts for the race between recently created
    instance profiles, IAM roles and an instance creation that refers to them.

    :rtype: list[Instance]
322099
def create_ondemand_instances(ec2, image_id, spec, num_instances=1):
    
    instance_type = spec['instance_type']
    log.info('Creating %s instance(s) ... ', instance_type)
    for attempt in retry_ec2(retry_for=a_long_time,
                             retry_while=inconsistencies_detected):
        with attempt:
            return ec2.run_instances(image_id,
                                     min_count=num_instances,
                                     max_count=num_instances,
                                     **spec).instances
43808
def is_first_instance_aws():
    
    try:
        # get instance id and aws region
        instance_details = requests.get('http://169.254.169.254/latest/dynamic/instance-identity/document',
                                        timeout=5).json()
        instance_id = instance_details['instanceId']
        instance_region = instance_details['region']
    except (requests.RequestException, ValueError, KeyError) as e:
        raise StackInterrogationException(e)

    try:
        # get instance's autoscaling group
        autoscaling_client = boto3.client('autoscaling', region_name=instance_region)
        response = autoscaling_client.describe_auto_scaling_instances(InstanceIds=[instance_id])
        assert len(response['AutoScalingInstances']) == 1
        autoscaling_group = response['AutoScalingInstances'][0]['AutoScalingGroupName']
    except ClientError as e:
        raise StackInterrogationException(e)
    except AssertionError:
        raise InstanceNotInAsgException()

    try:
        # list in-service instances in autoscaling group
        # instances being launched or terminated should not be considered
        response = autoscaling_client.describe_auto_scaling_groups(AutoScalingGroupNames=[autoscaling_group])
        assert len(response['AutoScalingGroups']) == 1
        autoscaling_group_instance_ids = sorted(
            instance['InstanceId']
            for instance in response['AutoScalingGroups'][0]['Instances']
            if instance['LifecycleState'] == 'InService'
        )
    except (ClientError, AssertionError) as e:
        raise StackInterrogationException(e)

    return bool(autoscaling_group_instance_ids and autoscaling_group_instance_ids[0] == instance_id)
328698
def get_instances_by_tag(self, tags):
        

        try:
            c = ec2.connect_to_region(self._region,
                                      aws_access_key_id=self._aws_access_key_id,
                                      aws_secret_access_key=self._aws_secret_access_key)

            # select instance by list of tags (OR used)
            reservations = c.get_all_reservations(filters=SergentSsh.tags_to_dict(tags))
            instances = list()

            for r in reservations:
                # for each instance launched by this reservation
                for instance in r.instances:
                    # we need only running instances
                    if instance.state.lower() == 'running':
                        instances.append(instance)

            return instances
        except NoAuthHandlerFound:
            raise SergentSshException('Boto said that you should check your credentials')
504632
def update_instances(self):
        
        self.log.debug('Updating EC2Instances for {}/{}'.format(self.account.account_name, self.region))
        ec2 = self.session.resource('ec2', region_name=self.region)

        try:
            existing_instances = EC2Instance.get_all(self.account, self.region)
            instances = {}
            api_instances = {x.id: x for x in ec2.instances.all()}

            try:
                for instance_id, data in api_instances.items():
                    if data.instance_id in existing_instances:
                        instance = existing_instances[instance_id]

                        if data.state['Name'] not in ('terminated', 'shutting-down'):
                            instances[instance_id] = instance

                            # Add object to transaction if it changed
                            if instance.update(data):
                                self.log.debug('Updating info for instance {} in {}/{}'.format(
                                    instance.resource.resource_id,
                                    self.account.account_name,
                                    self.region
                                ))
                                db.session.add(instance.resource)
                    else:
                        # New instance, if its not in state=terminated
                        if data.state['Name'] in ('terminated', 'shutting-down'):
                            continue

                        tags = {tag['Key']: tag['Value'] for tag in data.tags or {}}
                        properties = {
                            'launch_date': to_utc_date(data.launch_time).isoformat(),
                            'state': data.state['Name'],
                            'instance_type': data.instance_type,
                            'public_ip': getattr(data, 'public_ip_address', None),
                            'public_dns': getattr(data, 'public_dns_address', None),
                            'created': isoformat(datetime.now())
                        }

                        instance = EC2Instance.create(
                            data.instance_id,
                            account_id=self.account.account_id,
                            location=self.region,
                            properties=properties,
                            tags=tags
                        )

                        instances[instance.resource.resource_id] = instance
                        self.log.debug('Added new EC2Instance {}/{}/{}'.format(
                            self.account.account_name,
                            self.region,
                            instance.resource.resource_id
                        ))

                # Check for deleted instances
                ik = set(list(instances.keys()))
                eik = set(list(existing_instances.keys()))

                for instanceID in eik - ik:
                    db.session.delete(existing_instances[instanceID].resource)
                    self.log.debug('Deleted EC2Instance {}/{}/{}'.format(
                        self.account.account_name,
                        self.region,
                        instanceID
                    ))

                db.session.commit()
            except:
                db.session.rollback()
                raise
        finally:
            del ec2
821141
def instance():
    
    # Record the starting time and print a starting message
    start_time = time.time()
    print(_green("Started..."))

    # Use boto to create an EC2 instance
    env.host_string = _create_ec2_instance()
    print(_green("Waiting 30 seconds for server to boot..."))
    time.sleep(30)
    
    # Configure the instance that was just created
    for item in tasks.configure_instance:
        try:
            print(_yellow(item['message']))
        except KeyError:
            pass
        globals()["_" + item['action']](item['params'])
    
    # Print out the final runtime and the public dns of the new instance
    end_time = time.time()
    print(_green("Runtime: %f minutes" % ((end_time - start_time) / 60)))
    print(_green("\nPLEASE ADD ADDRESS THIS TO YOUR ")),
    print(_yellow("project_conf.py")),
    print(_green(" FILE UNDER ")),
    print(_yellow("fabconf['EC2_INSTANCES'] : ")),
    print(_green(env.host_string))
238729
def list_instance_profiles(path_prefix='/', region=None, key=None,
                           keyid=None, profile=None):
    '''
    
    '''
    p = get_all_instance_profiles(path_prefix, region, key, keyid, profile)
    return [i['instance_profile_name'] for i in p]
455371
def is_instance_running(self, instance_id):
        
        self._init_az_api()
        # Here, it's always better if we update the instance.
        vm = self._get_vm(instance_id, force_reload=True)
        # FIXME: should we rather check `vm.instance_view.statuses`
        # and search for `.code == "PowerState/running"`? or
        # `vm.instance_view.vm_agent.statuses` and search for `.code
        # == 'ProvisioningState/suceeded'`?
        return vm.provisioning_state == u'Succeeded'
1110268
def _tag_ec2(self, conn, role):
        
        tags = {'Role': role}
        conn.create_tags([self.instance_id], tags)
1270609
def run(self, *args, **kwargs):
        
        accounts = list(AWSAccount.get_all(include_disabled=False).values())

        # S3 Bucket config
        s3_acl = get_template('cloudtrail_s3_bucket_policy.json')
        s3_bucket_name = self.dbconfig.get('bucket_name', self.ns)
        s3_bucket_region = self.dbconfig.get('bucket_region', self.ns, 'us-west-2')
        s3_bucket_account = AWSAccount.get(self.dbconfig.get('bucket_account', self.ns))
        CloudTrail.create_s3_bucket(s3_bucket_name, s3_bucket_region, s3_bucket_account, s3_acl)

        self.validate_sqs_policy(accounts)

        for account in accounts:
            ct = CloudTrail(account, s3_bucket_name, s3_bucket_region, self.log)
            ct.run()
1024817
def show_instance(name, conn=None, call=None):
    '''
    

    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )
    if conn is None:
        conn = get_conn()

    node = conn.get_server(name, bare=True)
    ret = dict(node)
    ret['id'] = node.id
    ret['name'] = node.name
    ret['size'] = conn.get_flavor(node.flavor.id).name
    ret['state'] = node.status
    ret['private_ips'] = _get_ips(node, 'private')
    ret['public_ips'] = _get_ips(node, 'public')
    ret['floating_ips'] = _get_ips(node, 'floating')
    ret['fixed_ips'] = _get_ips(node, 'fixed')
    if isinstance(node.image, six.string_types):
        ret['image'] = node.image
    else:
        ret['image'] = conn.get_image(node.image.id).name
    return ret
979988
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )

    items = query(action='ve', command=name)

    ret = {}
    for item in items:
        if 'text' in item.__dict__:
            ret[item.tag] = item.text
        else:
            ret[item.tag] = item.attrib

        if item._children:
            ret[item.tag] = {}
            children = item._children
            for child in children:
                ret[item.tag][child.tag] = child.attrib

    __utils__['cloud.cache_node'](ret, __active_provider_name__, __opts__)
    return ret
1130656
def start_instance(self, instance):
        
        params = {'state': 'running'}
        url = '/instances/{}'.format(instance)
        self.patch_proto(url, params=params)
87787
public void create() {
        RunInstancesRequest runInstancesRequest =
                        new RunInstancesRequest().withImageId(amiId).withInstanceType(size).withKeyName(keyPair)
                                        .withMinCount(1).withSecurityGroupIds(securityGroupId).withMaxCount(numBoxes);
        AmazonEC2 ec2 = getEc2();
        ec2.setRegion(com.amazonaws.regions.Region.getRegion(regions));
        List<Instance> boxes = ec2.runInstances(runInstancesRequest).getReservation().getInstances();
        if (boxesCreated == null) {
            boxesCreated = new ArrayList<>();
            for (Instance i : boxes)
                boxesCreated.add(i.getInstanceId());



            log.info("Boxes created " + boxesCreated);
        } else {
            blowupBoxes();
            boxesCreated.clear();
            for (Instance i : boxes)
                boxesCreated.add(i.getInstanceId());

        }
    }
1073185
def run(self, *args, **kwargs):
        
        try:
            zones = list(DNSZone.get_all().values())
            buckets = {k.lower(): v for k, v in S3Bucket.get_all().items()}
            dists = list(CloudFrontDist.get_all().values())
            ec2_public_ips = [x.public_ip for x in EC2Instance.get_all().values() if x.public_ip]
            beanstalks = {x.cname.lower(): x for x in BeanStalk.get_all().values()}

            existing_issues = DomainHijackIssue.get_all()
            issues = []

            # List of different types of domain audits
            auditors = [
                ElasticBeanstalkAudit(beanstalks),
                S3Audit(buckets),
                S3WithoutEndpointAudit(buckets),
                EC2PublicDns(ec2_public_ips),
            ]

            # region Build list of active issues
            for zone in zones:
                for record in zone.records:
                    for auditor in auditors:
                        if auditor.match(record):
                            issues.extend(auditor.audit(record, zone))

            for dist in dists:
                for org in dist.origins:
                    if org['type'] == 's3':
                        bucket = self.return_resource_name(org['source'], 's3')

                        if bucket not in buckets:
                            key = '{} ({})'.format(bucket, dist.type)
                            issues.append({
                                'key': key,
                                'value': 'S3Bucket {} doesnt exist on any known account. Referenced by {} on {}'.format(
                                    bucket,
                                    dist.domain_name,
                                    dist.account,
                                )
                            })
            # endregion

            # region Process new, old, fixed issue lists
            old_issues = {}
            new_issues = {}
            fixed_issues = []

            for data in issues:
                issue_id = get_resource_id('dhi', ['{}={}'.format(k, v) for k, v in data.items()])

                if issue_id in existing_issues:
                    issue = existing_issues[issue_id]

                    if issue.update({'state': 'EXISTING', 'end': None}):
                        db.session.add(issue.issue)

                    old_issues[issue_id] = issue

                else:
                    properties = {
                        'issue_hash': issue_id,
                        'state': 'NEW',
                        'start': datetime.now(),
                        'end': None,
                        'source': data['key'],
                        'description': data['value']
                    }
                    new_issues[issue_id] = DomainHijackIssue.create(issue_id, properties=properties)
            db.session.commit()

            for issue in list(existing_issues.values()):
                if issue.id not in new_issues and issue.id not in old_issues:
                    fixed_issues.append(issue.to_json())
                    db.session.delete(issue.issue)
            # endregion

            # Only alert if its been more than a day since the last alert
            alert_cutoff = datetime.now() - timedelta(hours=self.alert_frequency)
            old_alerts = []
            for issue_id, issue in old_issues.items():
                if issue.last_alert and issue.last_alert < alert_cutoff:
                    if issue.update({'last_alert': datetime.now()}):
                        db.session.add(issue.issue)

                    old_alerts.append(issue)

            db.session.commit()

            self.notify(
                [x.to_json() for x in new_issues.values()],
                [x.to_json() for x in old_alerts],
                fixed_issues
            )
        finally:
            db.session.rollback()
1267478
def wait_for_instance(instance):
    

    status = None
    print("getting status for instance {} ...".format(instance.id))
    while status is None:
        try:
            status = instance.update()
            if status is None:
                time.sleep(2)
        except EC2ResponseError:
            time.sleep(2)

    print("waiting for instance {} ...".format(instance.id))

    while status == "pending":
        time.sleep(2)
        status = instance.update()

    if status != "running":
        print("Invalid status when starting instance {}: {}".format(instance.id, status))
        return False

    print("New instance {} started: {}".format(instance.id, instance.ip_address))
    return True
468592
def show_instance(instance_id, call=None, kwargs=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )

    params = {
        'action': 'DescribeInstances',
        'instances.1': instance_id,
        'zone': _get_specified_zone(kwargs=None, provider=get_configured_provider()),
    }
    items = query(params=params)

    if items['total_count'] == 0:
        raise SaltCloudNotFound(
            'The specified instance, \'{0}\', could not be found.'.format(instance_id)
        )

    full_node = items['instance_set'][0]
    normalized_node = _show_normalized_node(full_node)
    full_node.update(normalized_node)

    result = full_node

    return result
433407
def reboot_instances(self, instance_ids=None):
        
        params = {}
        if instance_ids:
            self.build_list_params(params, instance_ids, 'InstanceId')
        return self.get_status('RebootInstances', params)