Photo by Dallas Reedy on Unsplash
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 http://169.254.169.254/latest/meta-data/placement/availability-zone > /dev/null; then
echo "aws_imdsv1"
elif TOKEN=`curl --fail -s -m 5 -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 600"` \
&& curl --fail -s -m 5 -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/placement/availability-zone > /dev/null; then
echo "aws_imdsv2"
elif curl --fail -s -m 5 -H "Metadata:true" "http://169.254.169.254/metadata/instance?api-version=2017-08-01" > /dev/null; then
echo "azure"
elif curl --fail -s -m 5 -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/project/ > /dev/null; then
echo "gcp"
elif curl --fail -s -m 5 -H "Authorization: Bearer Oracle" -L http://169.254.169.254/opc/v2/instance/ > /dev/null; then
echo "oci"
else
echo "unknown"
fi
}
A GitHub Gist is also available as well as an example usage of this script below
source get-cloud-provider.sh; 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.