Skip to content

Commit

Permalink
providers/azure: fetch hostname from metadata
Browse files Browse the repository at this point in the history
This implements fetching the machine name from Azure metadata.

Ref: https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service
  • Loading branch information
lucab committed Apr 11, 2019
1 parent a633f64 commit 57e7023
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
24 changes: 24 additions & 0 deletions src/providers/azure/mock_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,27 @@ fn test_boot_checkin() {
m_health.assert();
r.unwrap();
}

#[test]
fn test_hostname() {
let m_version = mock_fab_version();
let m_goalstate = mock_goalstate();

let testname = "testname";
let endpoint = "/metadata/instance/compute/name?api-version=2017-08-01&format=text";
let m_hostname = mockito::mock("GET", endpoint)
.match_header("Metadata", "true")
.with_body(testname)
.with_status(200)
.create();

let provider = azure::Azure::try_new();
let r = provider.unwrap().hostname().unwrap();

m_version.assert();
m_goalstate.assert();

m_hostname.assert();
let hostname = r.unwrap();
assert_eq!(hostname, testname);
}
30 changes: 28 additions & 2 deletions src/providers/azure/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

//! azure metadata fetcher
//! Azure provider, metadata and wireserver fetcher.

mod crypto;

Expand Down Expand Up @@ -279,6 +279,17 @@ impl Azure {
}
}

#[cfg(test)]
fn metadata_endpoint() -> String {
mockito::server_url()
}

#[cfg(not(test))]
fn metadata_endpoint() -> String {
const URL: &str = "http://169.254.169.254";
URL.to_string()
}

fn get_certs_endpoint(&self) -> Result<String> {
// grab the certificates endpoint from the xml and return it
let cert_endpoint: &str = &self.goal_state.container.role_instance_list.role_instances[0]
Expand Down Expand Up @@ -392,6 +403,21 @@ impl Azure {
.ok_or_else(|| "empty RoleInstanceList".to_string())?
.instance_id)
}

fn fetch_hostname(&self) -> Result<Option<String>> {
const NAME_URL: &str = "metadata/instance/compute/name?api-version=2017-08-01&format=text";
let url = format!("{}/{}", Self::metadata_endpoint(), NAME_URL);

let name = retry::Client::try_new()?
.header(
HeaderName::from_static("metadata"),
HeaderValue::from_static("true"),
)
.get(retry::Raw, url)
.send()
.chain_err(|| "failed to get hostname")?;
Ok(name)
}
}

impl MetadataProvider for Azure {
Expand All @@ -411,7 +437,7 @@ impl MetadataProvider for Azure {
}

fn hostname(&self) -> Result<Option<String>> {
Ok(None)
self.fetch_hostname()
}

fn ssh_keys(&self) -> Result<Vec<PublicKey>> {
Expand Down

0 comments on commit 57e7023

Please sign in to comment.