Add function to detect whether Packer is running on Azure

This commit is contained in:
Paul Meyer 2019-09-25 21:15:25 +00:00
parent f106adbd12
commit 113dc12346
3 changed files with 60 additions and 0 deletions

View File

@ -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
}

View File

@ -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
}

View File

@ -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")
}