From 113dc1234617d748152fe039c24511de3cf3e2fc Mon Sep 17 00:00:00 2001 From: Paul Meyer Date: Wed, 25 Sep 2019 21:15:25 +0000 Subject: [PATCH] Add function to detect whether Packer is running on Azure --- builder/azure/common/detect_azure.go | 8 +++++ builder/azure/common/detect_azure_linux.go | 23 +++++++++++++++ .../azure/common/detect_azure_linux_test.go | 29 +++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 builder/azure/common/detect_azure.go create mode 100644 builder/azure/common/detect_azure_linux.go create mode 100644 builder/azure/common/detect_azure_linux_test.go diff --git a/builder/azure/common/detect_azure.go b/builder/azure/common/detect_azure.go new file mode 100644 index 000000000..001ca1b4f --- /dev/null +++ b/builder/azure/common/detect_azure.go @@ -0,0 +1,8 @@ +// +build !linux + +package common + +// IsAzure returns true if Packer is running on Azure (currently only works on Linux) +func IsAzure() bool { + return false +} diff --git a/builder/azure/common/detect_azure_linux.go b/builder/azure/common/detect_azure_linux.go new file mode 100644 index 000000000..f57eb42b9 --- /dev/null +++ b/builder/azure/common/detect_azure_linux.go @@ -0,0 +1,23 @@ +package common + +import ( + "bytes" + "io/ioutil" +) + +var ( + smbiosAssetTagFile = "/sys/class/dmi/id/chassis_asset_tag" + azureAssetTag = []byte("7783-7084-3265-9085-8269-3286-77\n") +) + +// IsAzure returns true if Packer is running on Azure +func IsAzure() bool { + return isAzureAssetTag(smbiosAssetTagFile) +} + +func isAzureAssetTag(filename string) bool { + if d, err := ioutil.ReadFile(filename); err == nil { + return bytes.Compare(d, azureAssetTag) == 0 + } + return false +} diff --git a/builder/azure/common/detect_azure_linux_test.go b/builder/azure/common/detect_azure_linux_test.go new file mode 100644 index 000000000..9d755cfd9 --- /dev/null +++ b/builder/azure/common/detect_azure_linux_test.go @@ -0,0 +1,29 @@ +package common + +import ( + "io/ioutil" + "os" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIsAzure(t *testing.T) { + f, err := ioutil.TempFile("", "TestIsAzure*") + if err != nil { + t.Fatal(err) + } + defer os.Remove(f.Name()) + + f.Seek(0, 0) + f.Truncate(0) + f.Write([]byte("not the azure assettag")) + + assert.False(t, isAzureAssetTag(f.Name()), "asset tag is not Azure's") + + f.Seek(0, 0) + f.Truncate(0) + f.Write(azureAssetTag) + + assert.True(t, isAzureAssetTag(f.Name()), "asset tag is Azure's") +}