Debian Codegraph @

provider/azure/azure_discover.go

raw
1 // Package azure provides node discovery for Microsoft Azure.
2 package azure
3
4 import (
5 "context"
6 "fmt"
7 "io/ioutil"
8 "log"
9 "os"
10
11 "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2015-06-15/network"
12 "github.com/Azure/go-autorest/autorest"
13 "github.com/Azure/go-autorest/autorest/azure/auth"
14 )
15
16 type Provider struct {
17 userAgent string
18 }
19
20 func (p *Provider) SetUserAgent(s string) {
21 p.userAgent = s
22 }
23
24 func (p *Provider) Help() string {
25 return `Microsoft Azure:
26
27 provider: "azure"
28 tenant_id: The id of the tenant
29 client_id: The id of the client
30 subscription_id: The id of the subscription
31 secret_access_key: The authentication credential
32 **NOTE** The secret_access_key value often may have an equals sign in it's value,
33 especially if generated from the Azure Portal. So is important to wrap in single quotes
34 eg. secret_acccess_key='fpOfcHQJAQBczjAxiVpeyLmX1M0M0KPBST+GU2GvEN4='
35
36 Variables can also be provided by environmental variables:
37 export ARM_SUBSCRIPTION_ID for subscription
38 export ARM_TENANT_ID for tenant
39 export ARM_CLIENT_ID for client
40 export ARM_CLIENT_SECRET for secret access key
41
42 If none of those options are given, the Azure SDK is using the default environment based authentication outlined
43 here https://docs.microsoft.com/en-us/go/azure/azure-sdk-go-authorization#use-environment-based-authentication
44 This will fallback to MSI if nothing is explicitly specified.
45
46 Use these configuration parameters when using tags:
47
48 tag_name: The name of the tag to filter on
49 tag_value: The value of the tag to filter on
50
51 Use these configuration parameters when using Virtual Machine Scale Sets:
52
53 resource_group: The name of the resource group to filter on
54 vm_scale_set: The name of the virtual machine scale set to filter on
55
56 When using tags the only permission needed is Microsoft.Network/networkInterfaces/*
57
58 When using Virtual Machine Scale Sets the only role action needed is Microsoft.Compute/virtualMachineScaleSets/*/read.
59
60 It is recommended you make a dedicated key used only for auto-joining.
61 `
62 }
63
64 // argsOrEnv allows you to pick an environmental variable for a setting if the arg is not set
65 func argsOrEnv(args map[string]string, key, env string) string {
66 if value, ok := args[key]; ok {
67 return value
68 }
69 return os.Getenv(env)
70 }
71
72 func (p *Provider) Addrs(args map[string]string, l *log.Logger) ([]string, error) {
73 var authorizer autorest.Authorizer
74
75 if args["provider"] != "azure" {
76 return nil, fmt.Errorf("discover-azure: invalid provider " + args["provider"])
77 }
78
79 if l == nil {
80 l = log.New(ioutil.Discard, "", 0)
81 }
82
83 // check for environmental variables, and use if the argument hasn't been set in config
84 tenantID := argsOrEnv(args, "tenant_id", "ARM_TENANT_ID")
85 clientID := argsOrEnv(args, "client_id", "ARM_CLIENT_ID")
86 subscriptionID := argsOrEnv(args, "subscription_id", "ARM_SUBSCRIPTION_ID")
87 secretKey := argsOrEnv(args, "secret_access_key", "ARM_CLIENT_SECRET")
88
89 // Try to use the argument and environment provided arguments first, if this fails fall back to the Azure
90 // SDK provided methods
91 if tenantID != "" && clientID != "" && secretKey != "" {
92 var err error
93 authorizer, err = auth.NewClientCredentialsConfig(clientID, secretKey, tenantID).Authorizer()
94 if err != nil {
95 return nil, fmt.Errorf("discover-azure (ClientCredentials): %s", err)
96 }
97 } else {
98 var err error
99 authorizer, err = auth.NewAuthorizerFromEnvironment()
100 if err != nil {
101 return nil, fmt.Errorf("discover-azure (EnvironmentCredentials): %s", err)
102 }
103 }
104
105 // Use tags if using network interfaces
106 tagName := args["tag_name"]
107 tagValue := args["tag_value"]
108
109 // Use resourceGroup and vmScaleSet if using vm scale sets
110 resourceGroup := args["resource_group"]
111 vmScaleSet := args["vm_scale_set"]
112
113 // Setup the client using autorest; followed the structure from Terraform
114 vmnet := network.NewInterfacesClient(subscriptionID)
115 vmnet.Sender = autorest.CreateSender(autorest.WithLogging(l))
116 vmnet.Authorizer = authorizer
117
118 if p.userAgent != "" {
119 vmnet.Client.UserAgent = p.userAgent
120 }
121
122 if tagName != "" && tagValue != "" && resourceGroup == "" && vmScaleSet == "" {
123 l.Printf("[DEBUG] discover-azure: using tag method. tag_name: %s, tag_value: %s", tagName, tagValue)
124 return fetchAddrsWithTags(tagName, tagValue, vmnet, l)
125 } else if resourceGroup != "" && vmScaleSet != "" && tagName == "" && tagValue == "" {
126 l.Printf("[DEBUG] discover-azure: using vm scale set method. resource_group: %s, vm_scale_set: %s", resourceGroup, vmScaleSet)
127 return fetchAddrsWithVmScaleSet(resourceGroup, vmScaleSet, vmnet, l)
128 } else {
129 l.Printf("[ERROR] discover-azure: tag_name: %s, tag_value: %s", tagName, tagValue)
130 l.Printf("[ERROR] discover-azure: resource_group %s, vm_scale_set %s", resourceGroup, vmScaleSet)
131 return nil, fmt.Errorf("discover-azure: unclear configuration. use (tag name and value) or (resouce_group and vm_scale_set)")
132 }
133
134 }
135
136 func fetchAddrsWithTags(tagName string, tagValue string, vmnet network.InterfacesClient, l *log.Logger) ([]string, error) {
137 // Get all network interfaces across resource groups
138 // unless there is a compelling reason to restrict
139
140 ctx := context.Background()
141 netres, err := vmnet.ListAll(ctx)
142
143 if err != nil {
144 return nil, fmt.Errorf("discover-azure: %s", err)
145 }
146
147 if len(netres.Values()) == 0 {
148 return nil, fmt.Errorf("discover-azure: no interfaces")
149 }
150
151 // Choose any PrivateIPAddress with the matching tag
152 var addrs []string
153 for _, v := range netres.Values() {
154 var id string
155 if v.ID != nil {
156 id = *v.ID
157 } else {
158 id = "ip address id not found"
159 }
160 if v.Tags == nil {
161 l.Printf("[DEBUG] discover-azure: Interface %s has no tags", id)
162 continue
163 }
164 tv := v.Tags[tagName] // *string
165 if tv == nil {
166 l.Printf("[DEBUG] discover-azure: Interface %s did not have tag: %s", id, tagName)
167 continue
168 }
169 if *tv != tagValue {
170 l.Printf("[DEBUG] discover-azure: Interface %s tag value was: %s which did not match: %s", id, *tv, tagValue)
171 continue
172 }
173 if v.IPConfigurations == nil {
174 l.Printf("[DEBUG] discover-azure: Interface %s had no ip configuration", id)
175 continue
176 }
177 for _, x := range *v.IPConfigurations {
178 if x.PrivateIPAddress == nil {
179 l.Printf("[DEBUG] discover-azure: Interface %s had no private ip", id)
180 continue
181 }
182 iAddr := *x.PrivateIPAddress
183 l.Printf("[DEBUG] discover-azure: Interface %s has private ip: %s", id, iAddr)
184 addrs = append(addrs, iAddr)
185 }
186 }
187 l.Printf("[DEBUG] discover-azure: Found ip addresses: %v", addrs)
188 return addrs, nil
189 }
190
191 func fetchAddrsWithVmScaleSet(resourceGroup string, vmScaleSet string, vmnet network.InterfacesClient, l *log.Logger) ([]string, error) {
192 // Get all network interfaces for a specific virtual machine scale set
193 ctx := context.Background()
194 netres, err := vmnet.ListVirtualMachineScaleSetNetworkInterfaces(ctx, resourceGroup, vmScaleSet)
195 if err != nil {
196 return nil, fmt.Errorf("discover-azure: %s", err)
197 }
198
199 if len(netres.Values()) == 0 {
200 return nil, fmt.Errorf("discover-azure: no interfaces")
201 }
202
203 // Get all of PrivateIPAddresses we can.
204 var addrs []string
205 for _, v := range netres.Values() {
206 var id string
207 if v.ID != nil {
208 id = *v.ID
209 } else {
210 id = "ip address id not found"
211 }
212 if v.IPConfigurations == nil {
213 l.Printf("[DEBUG] discover-azure: Interface %s had no ip configuration", id)
214 continue
215 }
216 for _, x := range *v.IPConfigurations {
217 if x.PrivateIPAddress == nil {
218 l.Printf("[DEBUG] discover-azure: Interface %s had no private ip", id)
219 continue
220 }
221 iAddr := *x.PrivateIPAddress
222 l.Printf("[DEBUG] discover-azure: Interface %s has private ip: %s", id, iAddr)
223 addrs = append(addrs, iAddr)
224 }
225 }
226 l.Printf("[DEBUG] discover-azure: Found ip addresses: %v", addrs)
227 return addrs, nil
228 }