Created
March 24, 2017 08:13
-
-
Save axw/8ebcfdd027710d8a204426a97859ab5d to your computer and use it in GitHub Desktop.
POC to list tenants and subscriptions, using device code auth with Juju Application ID
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"github.com/Azure/azure-sdk-for-go/arm/resources/subscriptions" | |
"github.com/Azure/go-autorest/autorest/azure" | |
"github.com/Azure/go-autorest/autorest/to" | |
) | |
func main() { | |
const clientId = "cbb548f1-5039-4836-af0b-727e8571f6a9" | |
const resourceManagerEndpoint = "https://management.azure.com" | |
const graphEndpoint = "https://graph.windows.net" | |
cloudEnv := azure.PublicCloud | |
oauthConfig, err := cloudEnv.OAuthConfigForTenant("common") | |
if err != nil { | |
log.Fatal(err) | |
} | |
client := subscriptions.Client{subscriptions.NewWithBaseURI(resourceManagerEndpoint)} | |
deviceCode, err := azure.InitiateDeviceAuth(&client.Client, *oauthConfig, clientId, resourceManagerEndpoint) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(to.String(deviceCode.Message)) | |
token, err := azure.WaitForUserCompletion(&client.Client, deviceCode) | |
if err != nil { | |
log.Fatal(err) | |
} | |
armSpt, err := azure.NewServicePrincipalTokenFromManualToken(*oauthConfig, clientId, "https://management.azure.com/", *token) | |
if err != nil { | |
log.Fatal(err) | |
} | |
if err := armSpt.Refresh(); err != nil { | |
log.Fatal(err) | |
} | |
client.Authorizer = armSpt | |
tenantsClient := subscriptions.NewTenantsClient() | |
tenantsClient.ManagementClient = client.ManagementClient | |
result, err := tenantsClient.List() | |
if err != nil { | |
log.Fatal(err) | |
} | |
for _, result := range *result.Value { | |
fmt.Println("querying subscriptions in tenant", to.String(result.TenantID)) | |
oauthConfig, err := cloudEnv.OAuthConfigForTenant(to.String(result.TenantID)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
armSpt, err := azure.NewServicePrincipalTokenFromManualToken( | |
*oauthConfig, clientId, "https://management.azure.com/", *token, | |
) | |
if err != nil { | |
log.Fatalf("creating token: %v", err) | |
} | |
if err := armSpt.Refresh(); err != nil { | |
log.Fatalf("refreshing token: %v", err) | |
} | |
client.Authorizer = armSpt | |
subscriptions, err := client.List() | |
if err != nil { | |
log.Fatal(err) | |
} | |
for _, result := range *subscriptions.Value { | |
fmt.Printf("%s: %s (%s)\n", | |
to.String(result.DisplayName), | |
to.String(result.SubscriptionID), | |
to.String(result.State), | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment