-
Notifications
You must be signed in to change notification settings - Fork 0
/
az-login-sp.go
executable file
·92 lines (73 loc) · 1.89 KB
/
az-login-sp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//usr/bin/env go run $0 $@ ; exit
//
// dep ensure
// az ad sp create-for-rbac --sdk-auth > my.auth
// export AZURE_AUTH_LOCATION=my.auth
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/azure/auth"
"github.com/davecgh/go-spew/spew"
"github.com/pkg/errors"
)
// AzureSession is an object representing session our connection
// it takes an <Authorizer> and a <SubscriptionID>
type AzureSession struct {
SubscriptionID string
Authorizer autorest.Authorizer
}
// Accepts a string path, returns json data
func readJSON(path string) (*map[string]interface{}, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, errors.Wrap(err, "Can't open the file")
}
contents := make(map[string]interface{})
err = json.Unmarshal(data, &contents)
if err != nil {
err = errors.Wrap(err, "Can't unmarshal file")
}
return &contents, err
}
//creates a new <session> from file
func newSessionFromFile(quiet bool) (*AzureSession, error) {
authorizer, err := auth.NewAuthorizerFromFile(azure.PublicCloud.ResourceManagerEndpoint)
if err != nil {
return nil, errors.Wrap(err, "Can't initialize authorizer")
} else {
if quiet != true {
spew.Dump(authorizer)
}
}
authInfo, err := readJSON(os.Getenv("AZURE_AUTH_LOCATION"))
if err != nil {
return nil, errors.Wrap(err, "Can't get authinfo")
} else {
if quiet != true {
spew.Dump(authorizer)
}
}
sess := AzureSession{
SubscriptionID: (*authInfo)["subscriptionId"].(string),
Authorizer: authorizer,
}
if quiet != true {
spew.Dump(authorizer)
}
return &sess, nil
}
func main() {
// create a new session using an auth file
sess, err := newSessionFromFile(false)
if err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
} else {
fmt.Printf("%v\n", sess.SubscriptionID)
}
}