Identifying your Cloud Provider within a Virtual Machine

Using Instance Metadata Services to identify the Cloud Provider

Below is a simple bash script that can be run to identify if the script exists within an AWS, Azure, Google Cloud, or Oracle Cloud Virtual Machine.

Bash Script

#!/usr/bin/env bash
set -e pipefail

function getCloudProvider() {
  if curl --fail -s -m 5 > /dev/null; then
    echo "aws_imdsv1"
  elif TOKEN=`curl --fail -s -m 5 -X PUT "" -H "X-aws-ec2-metadata-token-ttl-seconds: 600"` \
    && curl --fail -s -m 5 -H "X-aws-ec2-metadata-token: $TOKEN" > /dev/null; then
    echo "aws_imdsv2"
  elif curl --fail -s -m 5 -H "Metadata:true" "" > /dev/null; then
    echo "azure"
  elif curl --fail -s -m 5 -H "Metadata-Flavor: Google" > /dev/null; then
    echo "gcp"
  elif curl --fail -s -m 5 -H "Authorization: Bearer Oracle" -L > /dev/null; then
    echo "oci"
    echo "unknown"

A GitHub Gist is also available as well as an example usage of this script below

source; getCloudProvider

How and Why it Works

This simple script is useful due to its overall simplicity

  • Bash script to be easily run on any Unix system

  • Leverages curl, which is commonly available on most systems

  • Hits well-known endpoints within each Cloud Provider

Given that each Cloud Provider has a different IMDS implementation with different endpoints, this type of if-else approach has been verified to work via testing in all Cloud Providers. If multiple Cloud Providers had similar endpoints, there could be false positives during checking.

Cloud Provider References

Each cloud provider has an “Instance Metadata Service” of some kind*. Below is the reference documentation for each provider.

*for AWS there are multiple versions, with most systems moving towards IMDSv2, not all are there yet. Knowing the difference and testing for both may be very valuable when migrating or working with multiple regions still supporting IMDSv1.