-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmain.go
289 lines (257 loc) · 8.99 KB
/
main.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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/url"
"os"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/plugin"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
"google.golang.org/api/siteverification/v1"
)
//go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs
func main() {
if len(os.Args) > 1 && os.Args[1] == "install" {
install()
return
}
plugin.Serve(&plugin.ServeOpts{
ProviderFunc: Provider,
})
}
const tokenKey = "token"
const domainKey = "domain"
const recordTypeKey = "record_type"
const recordNameKey = "record_name"
const recordValueKey = "record_value"
const credentialsKey = "credentials"
const siteType = "INET_DOMAIN"
const verificationMethod = "DNS_TXT"
const tokenStillExists = "You cannot unverify your ownership of this site until your verification token (meta tag, HTML file, Google Analytics tracking code, Google Tag Manager container code, or DNS record) has been removed."
func Provider() terraform.ResourceProvider {
return &schema.Provider{
Schema: map[string]*schema.Schema{
credentialsKey: {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{
"GOOGLE_CREDENTIALS",
"GOOGLE_CLOUD_KEYFILE_JSON",
"GCLOUD_KEYFILE_JSON",
}, ""),
Description: "Either the path to or the contents of a [service account key file](https://cloud.google.com/iam/docs/creating-managing-service-account-keys) in JSON format. If not provided, the [application default credentials](https://cloud.google.com/sdk/gcloud/reference/auth/application-default) will be used.",
},
},
ConfigureFunc: configureProvider,
DataSourcesMap: map[string]*schema.Resource{
"googlesiteverification_dns_token": {
Schema: map[string]*schema.Schema{
domainKey: {
Type: schema.TypeString,
Required: true,
Description: "The domain you want to verify.",
},
recordTypeKey: {
Type: schema.TypeString,
Computed: true,
Description: "The type of DNS record you should create.",
},
recordNameKey: {
Type: schema.TypeString,
Computed: true,
Description: "The name of the record you should create.",
},
recordValueKey: {
Type: schema.TypeString,
Computed: true,
Description: "The value of the record you should create.",
},
},
Description: "https://developers.google.com/site-verification/v1/webResource/getToken",
Read: readDnsSiteVerificationToken,
},
},
ResourcesMap: map[string]*schema.Resource{
"googlesiteverification_dns": {
Schema: map[string]*schema.Schema{
domainKey: {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The domain you want to verify.",
},
tokenKey: {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The token you got from data.googlesiteverification_dns_token. This forces a new verification in case the token changes.",
},
},
Create: createDnsSiteVerification,
Read: readDnsSiteVerification,
Delete: deleteDnsSiteVerification,
Description: "https://developers.google.com/site-verification",
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
},
Importer: &schema.ResourceImporter{
State: importSiteVerification,
},
},
},
}
}
func importSiteVerification(resourceData *schema.ResourceData, provider interface{}) ([]*schema.ResourceData, error) {
service := provider.(configuredProvider).service
domain := strings.TrimPrefix(resourceData.Id(), "dns://")
if setErr := resourceData.Set(domainKey, domain); setErr != nil {
return nil, setErr
}
_, getErr := service.WebResource.Get(resourceData.Id()).Do()
if getErr != nil {
return nil, getErr
}
// fetch and set the token's value
tokenResource, getTokenErr := service.WebResource.GetToken(&siteverification.SiteVerificationWebResourceGettokenRequest{
Site: &siteverification.SiteVerificationWebResourceGettokenRequestSite{
Identifier: domain,
Type: siteType,
},
VerificationMethod: verificationMethod,
}).Do()
if getTokenErr != nil {
return nil, getTokenErr
}
if setErr := resourceData.Set(tokenKey, tokenResource.Token); setErr != nil {
return nil, setErr
}
return []*schema.ResourceData{resourceData}, nil
}
type configuredProvider struct {
service *siteverification.Service
}
func configureProvider(resourceData *schema.ResourceData) (interface{}, error) {
ctx := context.Background()
credentialsClientOption, crendentialsErr := findCredentials(resourceData, ctx)
if crendentialsErr != nil {
return nil, crendentialsErr
}
service, serviceErr := siteverification.NewService(ctx, credentialsClientOption)
if serviceErr != nil {
return nil, serviceErr
}
return configuredProvider{
service: service,
}, nil
}
func findCredentials(resourceData *schema.ResourceData, ctx context.Context) (option.ClientOption, error) {
// here we are trying to match the official GCP Provider's behavior https://www.terraform.io/docs/providers/google/guides/provider_reference.html#full-reference
var credentialsLiteral string
if credentialsFromConfig, ok := resourceData.GetOk(credentialsKey); ok {
credentialsLiteral = credentialsFromConfig.(string)
}
var credentialsClientOption option.ClientOption
if credentialsLiteral != "" {
if json.Valid([]byte(credentialsLiteral)) {
credentialsClientOption = option.WithCredentialsJSON([]byte(credentialsLiteral))
} else {
_, statErr := os.Stat(credentialsLiteral)
if statErr != nil {
return nil, statErr
}
credentialsClientOption = option.WithCredentialsFile(credentialsLiteral)
}
} else {
scopes := []string{
"https://www.googleapis.com/auth/siteverification",
}
credentials, defaultCredentialsErr := google.FindDefaultCredentials(ctx, scopes...)
if defaultCredentialsErr != nil {
return nil, defaultCredentialsErr
}
credentialsClientOption = option.WithCredentials(credentials)
}
return credentialsClientOption, nil
}
func readDnsSiteVerificationToken(resourceData *schema.ResourceData, provider interface{}) error {
service := provider.(configuredProvider).service
domain := resourceData.Get(domainKey).(string)
tokenResource, getTokenErr := service.WebResource.GetToken(&siteverification.SiteVerificationWebResourceGettokenRequest{
Site: &siteverification.SiteVerificationWebResourceGettokenRequestSite{
Identifier: domain,
Type: siteType,
},
VerificationMethod: verificationMethod,
}).Do()
if getTokenErr != nil {
return getTokenErr
}
if setErr := resourceData.Set(recordTypeKey, "TXT"); setErr != nil {
return setErr
}
if setErr := resourceData.Set(recordNameKey, domain); setErr != nil {
return setErr
}
if setErr := resourceData.Set(recordValueKey, tokenResource.Token); setErr != nil {
return setErr
}
resourceData.SetId(domain)
return nil
}
func deleteDnsSiteVerification(resourceData *schema.ResourceData, provider interface{}) error {
service := provider.(configuredProvider).service
id := resourceData.Id()
if !strings.HasPrefix(resourceData.Id(), "dns://") {
// the provider 0.3.1 and earlier stored the domain as
// the id, which is incorrect.
id = fmt.Sprintf("dns://%s", id)
}
return resource.Retry(resourceData.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
err := service.WebResource.Delete(id).Do()
if err != nil {
if strings.Contains(err.Error(), tokenStillExists) {
log.Printf("retry: %s", err)
return resource.RetryableError(err)
} else {
return resource.NonRetryableError(err)
}
}
return nil
})
}
func readDnsSiteVerification(resourceData *schema.ResourceData, provider interface{}) error {
service := provider.(configuredProvider).service
_, getErr := service.WebResource.Get(resourceData.Id()).Do()
return getErr
}
func createDnsSiteVerification(resourceData *schema.ResourceData, provider interface{}) error {
service := provider.(configuredProvider).service
domain := resourceData.Get(domainKey).(string)
return resource.Retry(resourceData.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
r, insertErr := service.WebResource.Insert(verificationMethod, &siteverification.SiteVerificationWebResourceResource{
Site: &siteverification.SiteVerificationWebResourceResourceSite{
Identifier: domain,
Type: siteType,
},
}).Do()
if insertErr != nil {
log.Printf("retrying failed site verification request, %s", insertErr)
return resource.RetryableError(insertErr)
}
id, err := url.QueryUnescape(r.Id)
if err != nil {
return resource.NonRetryableError(
fmt.Errorf(
"failed to urldecode id %s, %s", r.Id, err))
}
resourceData.SetId(id)
return resource.NonRetryableError(readDnsSiteVerification(resourceData, provider))
})
}