Detect Your VM's Cloud Provider and Region | Bash Script
Managing a global fleet of virtual machines (VMs) across various cloud service providers (CSPs) can be a challenging task. Depending on the naming convention applied to your hostnames, quickly identifying the CSP and region for a VM could be a challenge. To simplify this process, I've developed a bash script that takes advantage of each supported CSPs' available Instance Metadata Service (IMDS) to effectively identify the CSP and region, making troubleshooting more efficient.
At Kentik, we manage hundreds of global agents hosted across more than a dozen different CSPs for our Synthetics product. The hostnames assigned to these VMs follow a naming convention that identifies the CSP using an assigned numerical value and region using an IATA code. While the intent for this was to provide standardization across all environments, it's difficult to speedily identify what CSP and/or region you might be dealing with upon receiving an alert for a specific host. There are methods for identifying this information such as searching Kibana logs or matching up the CSP numerical identifier and IATA code for the region which has been my use case. To streamline this identification process, I've developed this simple tool supporting 9 different CSPs, including Azure, GCP, AWS, Alibaba Cloud, Vultr/Choopa, DigitalOcean, Tencent Cloud, Exoscale, and IBM Cloud.
This script utilizes a simple yet effective combination of Linux tools including
grep. By extracting the CSP and region details, the script enables faster navigation within the CSPs' portal and any other internal applications or tools you might use allowing you to pinpoint the affected VM within the appropriate region. For example, when troubleshooting an issue on an AWS host you need to know the region where it's hosted so you can navigate to the appropriate region's page within the AWS portal.
Using the script is straightforward and is intended to be run by the root user after being loaded into the
/usr/local/sbin directory on all cloud hosts across an infrastructure. Once executed, it cycles through a list of if/else statements until it matches the conditional for the CSPs' metadata the VM is running on. Next, it identifies the region based on the matching CSP statement.
Below are some sample test results from running the script across the 9 different supported CSPs in my environment. You can see how these example hostnames make it difficult to identify the CSP/region:
Region: ATL US
Managing VMs across various CSPs and regions is now much more efficient using this script. By combining
grep Linux tools, this solution leads to faster troubleshooting. The ability to quickly identify the CSP and region of a VM, right from within the host, showcases the potential of leveraging simple tools like this for enhanced operational efficiency.