1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
//! Get your fresh, farm-to-table, single-origin ec2 Ubuntu AMIs.
//!
//! # Example
//! ```rust
//! use ubuntu_ami::*;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), StdError> {
//!     let res = get_latest(
//!         "us-east-1",
//!         Some("bionic"),
//!         None,
//!         Some("hvm:ebs-ssd"),
//!         Some("amd64"),
//!     )
//!     .await?;
//!     println!("us-east-1 ubuntu:bionic: {}", res);
//!     Ok(())
//! }
//! ```

static URL: &str = "https://cloud-images.ubuntu.com/locator/ec2/releasesTable?_=1588199609256";

pub type StdError = Box<dyn std::error::Error + Send + Sync + 'static>;

#[derive(Debug, Clone)]
struct Entry {
    region: String,
    release_name: String,
    release_number: String,
    architecture: String,
    instance_type: String,
    date: String,
    ami: String,
    hvm: String,
}

/// Get the most recent Ubuntu AMI that matches the given criteria.
pub async fn get_latest(
    region: &str,
    release_name: Option<&str>,
    release_number: Option<&str>,
    instance_type: Option<&str>,
    architecture: Option<&str>,
) -> Result<String, StdError> {
    let mut r = reqwest::get(URL).await?.text().await?;

    // get rid of the trailing comma
    let len = r.len();
    let (first, last) = r.split_at_mut(len - 10);
    let mut r = first.to_string();
    r.extend(last.replace(',', " ").chars());

    // parse to json
    let j: serde_json::Value = serde_json::from_str(&r)?;
    let amis = j
        .as_object()
        .ok_or_else(|| String::from("Value not a JSON object"))?
        .values()
        .next()
        .unwrap();

    let mut amis: Vec<Entry> = amis
        .as_array()
        .ok_or_else(|| String::from("Value not a JSON array"))?
        .into_iter()
        .map(|v| {
            let fs: Vec<&str> = v
                .as_array()
                .unwrap()
                .into_iter()
                .map(|s| s.as_str().unwrap())
                .collect();
            Entry {
                region: fs[0].to_string(),
                release_name: fs[1].to_string(),
                release_number: fs[2].to_string(),
                architecture: fs[3].to_string(),
                instance_type: fs[4].to_string(),
                date: fs[5].to_string(),
                ami: fs[6].to_string(),
                hvm: fs[7].to_string(),
            }
        })
        .filter(|e| e.region == region)
        .filter(|e| {
            if let Some(release_name) = release_name {
                e.release_name == release_name
            } else {
                true
            }
        })
        .filter(|e| {
            if let Some(release_number) = release_number {
                e.release_number == release_number
            } else {
                true
            }
        })
        .filter(|e| {
            if let Some(instance_type) = instance_type {
                e.instance_type == instance_type
            } else {
                true
            }
        })
        .filter(|e| {
            if let Some(architecture) = architecture {
                e.architecture == architecture
            } else {
                true
            }
        })
        .collect();
    amis.sort_by_key(|e| e.date.clone());
    let entry = amis
        .pop()
        .ok_or_else(|| anyhow::anyhow!("Could not find ami for criteria"))?;

    Ok(parse_ami(&entry.ami)
        .ok_or_else(|| anyhow::anyhow!("Failure parsing ami"))?
        .to_string())
}

fn parse_ami(a_tag: &str) -> Option<&str> {
    // example:
    // "<a href=\"https://console.aws.amazon.com/ec2/home?region=us-east-1#launchAmi=ami-085925f297f89fce1\">ami-085925f297f89fce1</a>"
    let start_idx = a_tag.find("ami-")?;
    let end_idx = a_tag[start_idx + 4..].find(|c: char| !c.is_alphanumeric())? + start_idx + 4;
    Some(&a_tag[start_idx..end_idx])
}

#[cfg(test)]
mod test {
    use super::parse_ami;

    #[test]
    fn test_ami_parse() {
        let html = "<a href=\"https://console.aws.amazon.com/ec2/home?region=us-east-1#launchAmi=ami-085925f297f89fce1\">ami-085925f297f89fce1</a>";
        let ami = parse_ami(html).unwrap();
        assert_eq!(ami, "ami-085925f297f89fce1");
    }
}