Python get ami id

10 Python code examples are found related to " get ami id". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: autoscaling.py    From elastic with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_ami_id(self, accelerator):
        """
        Use EKS optimized AMI since it has everything we need pre-installed
        """

        eks_owner_id = "602401143452"
        eks_amis = {
            Accelerator.NONE: "amazon-eks-node-1.14-v20190927",
            Accelerator.GPU: "amazon-eks-gpu-node-1.14-v20190927",
        }

        res = self._ec2.describe_images(
            Filters=[
                {"Name": "owner-id", "Values": [eks_owner_id]},
                {
                    "Name": "name",
                    "Values": [eks_amis.get(accelerator, Accelerator.NONE)],
                },
            ]
        )
        images = res["Images"]
        assert (
            len(images) == 1
        ), f"Multiple EKS AMIs found for {self._session.aws_region()}"
        return images[0]["ImageId"] 
Example 2
Source File: aws_run_instances.py    From distributed_rl with MIT License 5 votes vote down vote up
def get_ami_id():
    ec2 = boto3.client('ec2')
    response = ec2.describe_images(Owners=["self"],
                                   Filters=[{'Name': 'name',
                                             'Values': ['distributed_rl']}])
    return response['Images'][0]['ImageId'] 
Example 3
Source File: aws.py    From -Deploying-Jenkins-to-the-Cloud-with-DevOps-Tools with MIT License 5 votes vote down vote up
def get_ami_image_id(name, region, **kwargs):
    """
    Args:
        name (str): The name of the of the image you are searching for.
        region (str): The AWS region.

    Basic Usage:
        >>> name = 'ubuntu/images/hvm/ubuntu-trusty-14.04-amd64-server-20150609'
        >>> aws_region = 'us-west-2'
        >>> get_ami_image_id(name, aws_region)
        u'ami-1234567'

    Returns:
        AMI Image Id
    """

    images = get_ami_images(name, region, **kwargs)

    if len(images) == 1:
        return images[0].id

    elif len(images) > 1:
        raise errors.AnsibleFilterError(
            "More than 1 instance was found with name {0} in region {1}"
            .format(name, region)
        )
    else:
        raise errors.AnsibleFilterError(
            "No instance was found with name {0} in region {1}"
            .format(name, region)
        ) 
Example 4
Source File: meta_lib.py    From incubator-dlab with Apache License 2.0 5 votes vote down vote up
def get_ami_id(ami_name):
    try:
        client = boto3.client('ec2')
        image_id = ''
        response = client.describe_images(
            Filters=[
                {
                    'Name': 'name',
                    'Values': [ami_name]
                },
                {
                    'Name': 'virtualization-type', 'Values': ['hvm']
                },
                {
                    'Name': 'state', 'Values': ['available']
                },
                {
                    'Name': 'root-device-name', 'Values': ['/dev/sda1']
                },
                {
                    'Name': 'root-device-type', 'Values': ['ebs']
                },
                {
                    'Name': 'architecture', 'Values': ['x86_64']
                }
            ])
        response = response.get('Images')
        for i in response:
            image_id = i.get('ImageId')
        if image_id == '':
            raise Exception("Unable to find image id with name: " + ami_name)
        return image_id
    except Exception as err:
        logging.error("Failed to find AMI: " + ami_name + " : " + str(err) + "\n Traceback: " + traceback.print_exc(file=sys.stdout))
        append_result(str({"error": "Unable to find AMI", "error_message": str(err) + "\n Traceback: " + traceback.print_exc(file=sys.stdout)}))
        traceback.print_exc(file=sys.stdout) 
Example 5
Source File: meta_lib.py    From incubator-dlab with Apache License 2.0 5 votes vote down vote up
def get_ami_id_by_instance_name(instance_name):
    ec2 = boto3.resource('ec2')
    try:
        for instance in ec2.instances.filter(Filters=[{'Name': 'tag:{}'.format('Name'), 'Values': [instance_name]}]):
            return instance.image_id
    except Exception as err:
        logging.error("Error with getting AMI ID by instance name: " + str(
            err) + "\n Traceback: " + traceback.print_exc(file=sys.stdout))
        append_result(str({"error": "Error with getting AMI ID by instance name",
                           "error_message": str(
                               err) + "\n Traceback: " + traceback.print_exc(
                               file=sys.stdout)}))
        traceback.print_exc(file=sys.stdout)
        return ''
    return '' 
Example 6
Source File: meta_lib.py    From incubator-dlab with Apache License 2.0 5 votes vote down vote up
def get_ami_id_by_name(ami_name, state="*"):
    ec2 = boto3.resource('ec2')
    try:
        for image in ec2.images.filter(Filters=[{'Name': 'name', 'Values': [ami_name]}, {'Name': 'state', 'Values': [state]}]):
            return image.id
    except Exception as err:
        logging.error("Error with getting AMI ID by name: " + str(err) + "\n Traceback: " + traceback.print_exc(file=sys.stdout))
        append_result(str({"error": "Error with getting AMI ID by name",
                   "error_message": str(err) + "\n Traceback: " + traceback.print_exc(file=sys.stdout)}))
        traceback.print_exc(file=sys.stdout)
        return ''
    return '' 
Example 7
Source File: malboxes.py    From malboxes with GNU General Public License v3.0 5 votes vote down vote up
def get_AMI_ID_by_template(config, template):
    """
    Gets the ID of an AMI by the template tag on it.
    """
    images = create_EC2_client(config).describe_images(Owners=['self'],
    Filters=[{'Name': 'tag:Template', 'Values': [template]}])
    return images['Images'][0]['ImageId'] 
Example 8
Source File: aws.py    From stacks with MIT License 5 votes vote down vote up
def get_ami_id(conn, name):
    """Return the first AMI ID given its name"""
    images = conn.get_all_images(filters={'name': name})
    conn.close()
    if len(images) != 0:
        return images[0].id
    else:
        raise RuntimeError('{} AMI not found'.format(name)) 
Example 9
Source File: server.py    From aws-extender with MIT License 5 votes vote down vote up
def get_ami_id(self, params):
        valid = False
        while not valid:
            ami = params.get('ami', None)
            if not ami:
                prop = StringProperty(name='ami', verbose_name='AMI')
                ami = propget.get(prop)
            try:
                rs = self.ec2.get_all_images([ami])
                if len(rs) == 1:
                    valid = True
                    params['ami'] = rs[0]
            except EC2ResponseError:
                pass