import requests
import yaml


def _lookup_image_by_region(region):
    """Retrieve Ubuntu AMI for the given region from official table.
    """
    url = "http://cloud-images.ubuntu.com/locator/ec2/releasesTable"
    r = requests.get(url)
    r_parsed = yaml.safe_load(r.text)
    available = []
    for (cur_region, _, version, _, instance_type, _, ami_id, _) in r_parsed["aaData"]:
        if cur_region == region and instance_type == "hvm:ebs-ssd" and "LTS" in version:
            ami_id = ami_id.split(">")[1].split("<")[0]
            available.append((version, ami_id))
    available.sort(reverse=True)
    return available[0][1]