2016-06-22 19:04:13 -04:00
|
|
|
package arm
|
|
|
|
|
2016-06-30 19:51:52 -04:00
|
|
|
// Method to resolve information about the user so that a client can be
|
|
|
|
// constructed to communicated with Azure.
|
|
|
|
//
|
|
|
|
// The following data are resolved.
|
|
|
|
//
|
|
|
|
// 1. TenantID
|
|
|
|
|
2016-06-22 19:04:13 -04:00
|
|
|
import (
|
2019-02-21 12:35:14 -05:00
|
|
|
"encoding/json"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
|
2016-06-22 19:04:13 -04:00
|
|
|
"github.com/Azure/go-autorest/autorest/azure"
|
2017-04-04 16:39:01 -04:00
|
|
|
"github.com/hashicorp/packer/builder/azure/common"
|
2016-06-22 19:04:13 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type configRetriever struct {
|
|
|
|
// test seams
|
|
|
|
findTenantID func(azure.Environment, string) (string, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
func newConfigRetriever() configRetriever {
|
2016-06-30 19:51:52 -04:00
|
|
|
return configRetriever{
|
|
|
|
common.FindTenantID,
|
|
|
|
}
|
2016-06-22 19:04:13 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cr configRetriever) FillParameters(c *Config) error {
|
2019-02-21 12:35:14 -05:00
|
|
|
if c.SubscriptionID == "" {
|
|
|
|
subscriptionID, err := cr.getSubscriptionFromIMDS()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.SubscriptionID = subscriptionID
|
|
|
|
}
|
|
|
|
|
2016-06-22 19:04:13 -04:00
|
|
|
if c.TenantID == "" {
|
|
|
|
tenantID, err := cr.findTenantID(*c.cloudEnvironment, c.SubscriptionID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.TenantID = tenantID
|
|
|
|
}
|
2016-06-30 19:51:52 -04:00
|
|
|
|
2016-06-22 19:04:13 -04:00
|
|
|
return nil
|
|
|
|
}
|
2019-02-21 12:35:14 -05:00
|
|
|
|
|
|
|
func (cr configRetriever) getSubscriptionFromIMDS() (string, error) {
|
|
|
|
client := &http.Client{}
|
|
|
|
|
|
|
|
req, _ := http.NewRequest("GET", "http://169.254.169.254/metadata/instance/compute", nil)
|
|
|
|
req.Header.Add("Metadata", "True")
|
|
|
|
|
|
|
|
q := req.URL.Query()
|
|
|
|
q.Add("format", "json")
|
|
|
|
q.Add("api-version", "2017-08-01")
|
|
|
|
|
|
|
|
req.URL.RawQuery = q.Encode()
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
resp_body, _ := ioutil.ReadAll(resp.Body)
|
|
|
|
result := map[string]string{}
|
|
|
|
err = json.Unmarshal(resp_body, &result)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return result["subscriptionId"], nil
|
|
|
|
}
|