forked from aliyun/terraform-provider-alicloud
/
config.go
389 lines (364 loc) · 13 KB
/
config.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package connectivity
import (
"fmt"
"log"
"sync"
roa "github.com/alibabacloud-go/tea-roa/client"
"encoding/json"
"net/http"
"strings"
rpc "github.com/alibabacloud-go/tea-rpc/client"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
credential "github.com/aliyun/credentials-go/credentials"
"github.com/jmespath/go-jmespath"
)
var securityCredURL = "http://100.100.100.200/latest/meta-data/ram/security-credentials/"
// Config of aliyun
type Config struct {
AccessKey string
SecretKey string
EcsRoleName string
Region Region
RegionId string
SecurityToken string
OtsInstanceName string
AccountId string
Protocol string
ClientReadTimeout int
ClientConnectTimeout int
SourceIp string
SecureTransport string
MaxRetryTimeout int
RamRoleArn string
RamRoleSessionName string
RamRolePolicy string
RamRoleExternalId string
RamRoleSessionExpiration int
Endpoints *sync.Map
SignVersion *sync.Map
RKvstoreEndpoint string
EcsEndpoint string
RdsEndpoint string
SlbEndpoint string
VpcEndpoint string
CenEndpoint string
EssEndpoint string
OssEndpoint string
OnsEndpoint string
AlikafkaEndpoint string
DnsEndpoint string
RamEndpoint string
CsEndpoint string
CrEndpoint string
CdnEndpoint string
KmsEndpoint string
OtsEndpoint string
CmsEndpoint string
PvtzEndpoint string
StsEndpoint string
LogEndpoint string
DrdsEndpoint string
DdsEndpoint string
GpdbEnpoint string
KVStoreEndpoint string
PolarDBEndpoint string
FcEndpoint string
ApigatewayEndpoint string
DatahubEndpoint string
MnsEndpoint string
LocationEndpoint string
ElasticsearchEndpoint string
NasEndpoint string
BssOpenApiEndpoint string
DdoscooEndpoint string
DdosbgpEndpoint string
SagEndpoint string
EmrEndpoint string
CasEndpoint string
MarketEndpoint string
HBaseEndpoint string
AdbEndpoint string
MaxComputeEndpoint string
edasEndpoint string
SkipRegionValidation bool
ConfigurationSource string
TerraformTraceId string
TerraformVersion string
CbnEndpoint string
DmsEnterpriseEndpoint string
WafOpenapiEndpoint string
ResourcemanagerEndpoint string
BssopenapiEndpoint string
AlidnsEndpoint string
CassandraEndpoint string
EciEndpoint string
OosEndpoint string
DcdnEndpoint string
MseEndpoint string
ActiontrailEndpoint string
ConfigEndpoint string
FnfEndpoint string
RosEndpoint string
PrivatelinkEndpoint string
MaxcomputeEndpoint string
ResourcesharingEndpoint string
GaEndpoint string
HitsdbEndpoint string
BrainIndustrialEndpoint string
EipanycastEndpoint string
ImsEndpoint string
QuotasEndpoint string
SgwEndpoint string
ScdnEndpoint string
DmEndpoint string
EventbridgeEndpoint string
OnsproxyEndpoint string
CdsEndpoint string
HbrEndpoint string
ArmsEndpoint string
CloudfwEndpoint string
ServerlessEndpoint string
AlbEndpoint string
RedisaEndpoint string
GwsecdEndpoint string
CloudphoneEndpoint string
DataworkspublicEndpoint string
HcsSgwEndpoint string
CddcEndpoint string
MscopensubscriptionEndpoint string
SddpEndpoint string
BastionhostEndpoint string
SasEndpoint string
AlidfsEndpoint string
EhpcEndpoint string
EnsEndpoint string
IotEndpoint string
ImmEndpoint string
ClickhouseEndpoint string
DtsEndpoint string
DgEndpoint string
CloudssoEndpoint string
WafEndpoint string
SwasEndpoint string
VsEndpoint string
QuickbiEndpoint string
VodEndpoint string
OpensearchEndpoint string
GdsEndpoint string
DbfsEndpoint string
DevopsrdcEndpoint string
EaisEndpoint string
CloudauthEndpoint string
ImpEndpoint string
MhubEndpoint string
ServicemeshEndpoint string
AcrEndpoint string
EdsuserEndpoint string
GpdbEndpoint string
GaplusEndpoint string
DdosbasicEndpoint string
SmartagEndpoint string
TagEndpoint string
EdasEndpoint string
EdasschedulerxEndpoint string
EhsEndpoint string
DysmsEndpoint string
CbsEndpoint string
NlbEndpoint string
VpcpeerEndpoint string
EbsEndpoint string
DmsenterpriseEndpoint string
BpStudioEndpoint string
DasEndpoint string
CloudfirewallEndpoint string
SrvcatalogEndpoint string
VpcPeerEndpoint string
EfloEndpoint string
OceanbaseEndpoint string
BeebotEndpoint string
ComputeNestEndpoint string
}
func (c *Config) loadAndValidate() error {
err := c.validateRegion()
if err != nil {
return err
}
return nil
}
func (c *Config) validateRegion() error {
for _, valid := range ValidRegions {
if c.Region == valid {
return nil
}
}
return fmt.Errorf("Invalid Alibaba Cloud region: %s. "+
"You can skip checking this region by setting provider parameter 'skip_region_validation'.", c.RegionId)
}
func (c *Config) getAuthCredential(stsSupported bool) auth.Credential {
if c.AccessKey != "" && c.SecretKey != "" {
if stsSupported && c.SecurityToken != "" {
return credentials.NewStsTokenCredential(c.AccessKey, c.SecretKey, c.SecurityToken)
}
if c.RamRoleArn != "" {
log.Printf("[INFO] Assume RAM Role specified in provider block assume_role { ... }")
if c.RamRoleExternalId != "" {
return credentials.NewRamRoleArnWithPolicyAndExternalIdCredential(
c.AccessKey, c.SecretKey, c.RamRoleArn,
c.RamRoleSessionName, c.RamRolePolicy, c.RamRoleExternalId, c.RamRoleSessionExpiration)
}
return credentials.NewRamRoleArnWithPolicyCredential(
c.AccessKey, c.SecretKey, c.RamRoleArn,
c.RamRoleSessionName, c.RamRolePolicy, c.RamRoleSessionExpiration)
}
return credentials.NewAccessKeyCredential(c.AccessKey, c.SecretKey)
}
if c.EcsRoleName != "" {
return credentials.NewEcsRamRoleCredential(c.EcsRoleName)
}
return credentials.NewAccessKeyCredential(c.AccessKey, c.SecretKey)
}
// getAuthCredentialByEcsRoleName aims to access meta to get sts credential
// Actually, the job should be done by sdk, but currently not all resources and products support alibaba-cloud-sdk-go,
// and their go sdk does support ecs role name.
// This method is a temporary solution and it should be removed after all go sdk support ecs role name
// The related PR: https://github.com/gunnerliu/terraform-provider-alicloud/pull/731
func (c *Config) getAuthCredentialByEcsRoleName() (accessKey, secretKey, token string, err error) {
if c.AccessKey != "" {
return c.AccessKey, c.SecretKey, c.SecurityToken, nil
}
if c.EcsRoleName == "" {
return
}
requestUrl := securityCredURL + c.EcsRoleName
httpRequest, err := http.NewRequest(requests.GET, requestUrl, strings.NewReader(""))
if err != nil {
err = fmt.Errorf("build sts requests err: %s", err.Error())
return
}
httpClient := &http.Client{}
httpResponse, err := httpClient.Do(httpRequest)
if err != nil {
err = fmt.Errorf("get Ecs sts token err : %s", err.Error())
return
}
response := responses.NewCommonResponse()
err = responses.Unmarshal(response, httpResponse, "")
if err != nil {
err = fmt.Errorf("Unmarshal Ecs sts token response err : %s", err.Error())
return
}
if response.GetHttpStatus() != http.StatusOK {
err = fmt.Errorf("get Ecs sts token err, httpStatus: %d, message = %s", response.GetHttpStatus(), response.GetHttpContentString())
return
}
var data interface{}
err = json.Unmarshal(response.GetHttpContentBytes(), &data)
if err != nil {
err = fmt.Errorf("refresh Ecs sts token err, json.Unmarshal fail: %s", err.Error())
return
}
code, err := jmespath.Search("Code", data)
if err != nil {
err = fmt.Errorf("refresh Ecs sts token err, fail to get Code: %s", err.Error())
return
}
if code.(string) != "Success" {
err = fmt.Errorf("refresh Ecs sts token err, Code is not Success")
return
}
accessKeyId, err := jmespath.Search("AccessKeyId", data)
if err != nil {
err = fmt.Errorf("refresh Ecs sts token err, fail to get AccessKeyId: %s", err.Error())
return
}
accessKeySecret, err := jmespath.Search("AccessKeySecret", data)
if err != nil {
err = fmt.Errorf("refresh Ecs sts token err, fail to get AccessKeySecret: %s", err.Error())
return
}
securityToken, err := jmespath.Search("SecurityToken", data)
if err != nil {
err = fmt.Errorf("refresh Ecs sts token err, fail to get SecurityToken: %s", err.Error())
return
}
if accessKeyId == nil || accessKeySecret == nil || securityToken == nil {
err = fmt.Errorf("there is no any available accesskey, secret and security token for Ecs role %s", c.EcsRoleName)
return
}
return accessKeyId.(string), accessKeySecret.(string), securityToken.(string), nil
}
func (c *Config) MakeConfigByEcsRoleName() error {
accessKey, secretKey, token, err := c.getAuthCredentialByEcsRoleName()
if err != nil {
return err
}
c.AccessKey, c.SecretKey, c.SecurityToken = accessKey, secretKey, token
return nil
}
func (c *Config) getTeaDslSdkConfig(stsSupported bool) (config rpc.Config, err error) {
config.SetRegionId(c.RegionId)
config.SetUserAgent(fmt.Sprintf("%s/%s %s/%s %s/%s %s/%s", Terraform, c.TerraformVersion, Provider, providerVersion, Module, c.ConfigurationSource, TerraformTraceId, c.TerraformTraceId))
credential, err := credential.NewCredential(c.getCredentialConfig(stsSupported))
config.SetCredential(credential).
SetRegionId(c.RegionId).
SetProtocol(c.Protocol).
SetReadTimeout(c.ClientReadTimeout).
SetConnectTimeout(c.ClientConnectTimeout).
SetMaxIdleConns(500)
if c.SourceIp != "" {
config.SetSourceIp(c.SourceIp)
}
if c.SecureTransport != "" {
config.SetSecureTransport(c.SecureTransport)
}
return
}
func (c *Config) getTeaRoaDslSdkConfig(stsSupported bool) (config roa.Config, err error) {
config.SetRegionId(c.RegionId)
config.SetUserAgent(fmt.Sprintf("%s/%s %s/%s %s/%s %s/%s", Terraform, c.TerraformVersion, Provider, providerVersion, Module, c.ConfigurationSource, TerraformTraceId, c.TerraformTraceId))
credential, err := credential.NewCredential(c.getCredentialConfig(stsSupported))
config.SetCredential(credential).
SetRegionId(c.RegionId).
SetProtocol(c.Protocol).
SetReadTimeout(c.ClientReadTimeout).
SetConnectTimeout(c.ClientConnectTimeout).
SetMaxIdleConns(500)
if c.SourceIp != "" {
config.SetSourceIp(c.SourceIp)
}
if c.SecureTransport != "" {
config.SetSecureTransport(c.SecureTransport)
}
return
}
func (c *Config) getCredentialConfig(stsSupported bool) *credential.Config {
credentialType := ""
credentialConfig := &credential.Config{}
if c.AccessKey != "" && c.SecretKey != "" {
credentialType = "access_key"
credentialConfig.AccessKeyId = &c.AccessKey // AccessKeyId
credentialConfig.AccessKeySecret = &c.SecretKey // AccessKeySecret
if stsSupported && c.SecurityToken != "" {
credentialType = "sts"
credentialConfig.SecurityToken = &c.SecurityToken // STS Token
} else if c.RamRoleArn != "" {
log.Printf("[INFO] Assume RAM Role specified in provider block assume_role { ... }")
credentialType = "ram_role_arn"
credentialConfig.RoleArn = &c.RamRoleArn
credentialConfig.RoleSessionName = &c.RamRoleSessionName
credentialConfig.RoleSessionExpiration = &c.RamRoleSessionExpiration
credentialConfig.Policy = &c.RamRolePolicy
if c.RamRoleExternalId != "" {
credentialConfig.ExternalId = &c.RamRoleExternalId
}
}
} else if c.EcsRoleName != "" {
credentialType = "ecs_ram_role"
credentialConfig.RoleName = &c.EcsRoleName
}
credentialConfig.Type = &credentialType
return credentialConfig
}