Baber
Baber

Reputation: 321

How to create Virtual Network in Azure using GoLang API?

Currently I am trying to create Virtual Network using the GoLang code:

client := network.NewVirtualNetworksClient(subscriptionID)
var parameters network.VirtualNetwork
c := make(<-chan struct{})

c1, err := client.CreateOrUpdate(resourceGroupName, virtualNetworkName, parameters, c)

utils.Info.Println(err.Error())
utils.Info.Println(c1)

But the code isn't working fine. It throws the following exception:

Failure sending request: StatusCode=401 -- Original Error: Long running operation terminated with status 'Failed': Code="AuthenticationFailed" Message="Authentication failed. The 'Authorization' header is missing."

Your help will be highly appreciated.

Upvotes: 0

Views: 1352

Answers (2)

MarStr
MarStr

Reputation: 455

There is some good documentation in general for using Azure authentication that you can find here: azure-sdk-for-node/Documentation/Authentication

While there isn't an example for Virtual Networks specifically yet, you can find Azure SDK for Go samples here.

For Go in particular, you can update a Client to use an authentication token, so your code would look something like this:

c := make(chan struct{})
authConfig, err0 := azure.PublicCloud.OAuthConfigForTenant(<yourTenantID>)
token, err1 := azure.NewServicePrincipalToken(
                  *authConfig,
                  <yourClientID>,
                  <yourClientSecret>,
                  azure.PublicCloud.ResourceManagerEndpoint) 

client := network.NewVirtualNetworkClient(subscriptionID)
client.Authorizer = token

var parameters network.VirtualNetwork
c1, err2 := client.CreateOrUpdate(resourceGroupName, virtualNetworkName, parameters, c)

Upvotes: 2

Alex Belotserkovskiy
Alex Belotserkovskiy

Reputation: 4062

I assume you use GoLang SDK for Azure ? The reason of the error is that when you make a request, it does not have the Authorization header. Authorization header is the JSON Web Token that you can obtain from Azure Active Directory

1) Take a look at the request in the Fiddler and see if your request is aligned with the rules.

2) Go with the tutorials about how to get the token (1 and 2).

Upvotes: 1

Related Questions