/
resource_google_service_account.go
221 lines (200 loc) · 6.99 KB
/
resource_google_service_account.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
package google
import (
"fmt"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"google.golang.org/api/iam/v1"
)
func resourceGoogleServiceAccount() *schema.Resource {
return &schema.Resource{
Create: resourceGoogleServiceAccountCreate,
Read: resourceGoogleServiceAccountRead,
Delete: resourceGoogleServiceAccountDelete,
Update: resourceGoogleServiceAccountUpdate,
Importer: &schema.ResourceImporter{
State: resourceGoogleServiceAccountImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"email": {
Type: schema.TypeString,
Computed: true,
Description: `The e-mail address of the service account. This value should be referenced from any google_iam_policy data sources that would grant the service account privileges.`,
},
"unique_id": {
Type: schema.TypeString,
Computed: true,
Description: `The unique id of the service account.`,
},
"name": {
Type: schema.TypeString,
Computed: true,
Description: `The fully-qualified name of the service account.`,
},
"account_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateRFC1035Name(6, 30),
Description: `The account id that is used to generate the service account email address and a stable unique id. It is unique within a project, must be 6-30 characters long, and match the regular expression [a-z]([-a-z0-9]*[a-z0-9]) to comply with RFC1035. Changing this forces a new service account to be created.`,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
Description: `The display name for the service account. Can be updated without creating a new resource.`,
},
"description": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringLenBetween(0, 256),
Description: `A text description of the service account. Must be less than or equal to 256 UTF-8 bytes.`,
},
"project": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
Description: `The ID of the project that the service account will be created in. Defaults to the provider project configuration.`,
},
},
UseJSONNumber: true,
}
}
func resourceGoogleServiceAccountCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
project, err := getProject(d, config)
if err != nil {
return err
}
aid := d.Get("account_id").(string)
displayName := d.Get("display_name").(string)
description := d.Get("description").(string)
sa := &iam.ServiceAccount{
DisplayName: displayName,
Description: description,
}
r := &iam.CreateServiceAccountRequest{
AccountId: aid,
ServiceAccount: sa,
}
sa, err = config.NewIamClient(userAgent).Projects.ServiceAccounts.Create("projects/"+project, r).Do()
if err != nil {
return fmt.Errorf("Error creating service account: %s", err)
}
d.SetId(sa.Name)
err = retryTimeDuration(func() (operr error) {
_, saerr := config.NewIamClient(userAgent).Projects.ServiceAccounts.Get(d.Id()).Do()
return saerr
}, d.Timeout(schema.TimeoutCreate), isNotFoundRetryableError("service account creation"))
if err != nil {
return fmt.Errorf("Error reading service account after creation: %s", err)
}
return resourceGoogleServiceAccountRead(d, meta)
}
func resourceGoogleServiceAccountRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
// Confirm the service account exists
sa, err := config.NewIamClient(userAgent).Projects.ServiceAccounts.Get(d.Id()).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Service Account %q", d.Id()))
}
if err := d.Set("email", sa.Email); err != nil {
return fmt.Errorf("Error setting email: %s", err)
}
if err := d.Set("unique_id", sa.UniqueId); err != nil {
return fmt.Errorf("Error setting unique_id: %s", err)
}
if err := d.Set("project", sa.ProjectId); err != nil {
return fmt.Errorf("Error setting project: %s", err)
}
if err := d.Set("account_id", strings.Split(sa.Email, "@")[0]); err != nil {
return fmt.Errorf("Error setting account_id: %s", err)
}
if err := d.Set("name", sa.Name); err != nil {
return fmt.Errorf("Error setting name: %s", err)
}
if err := d.Set("display_name", sa.DisplayName); err != nil {
return fmt.Errorf("Error setting display_name: %s", err)
}
if err := d.Set("description", sa.Description); err != nil {
return fmt.Errorf("Error setting description: %s", err)
}
return nil
}
func resourceGoogleServiceAccountDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
name := d.Id()
_, err = config.NewIamClient(userAgent).Projects.ServiceAccounts.Delete(name).Do()
if err != nil {
return err
}
d.SetId("")
return nil
}
func resourceGoogleServiceAccountUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
sa, err := config.NewIamClient(userAgent).Projects.ServiceAccounts.Get(d.Id()).Do()
if err != nil {
return fmt.Errorf("Error retrieving service account %q: %s", d.Id(), err)
}
updateMask := make([]string, 0)
if d.HasChange("description") {
updateMask = append(updateMask, "description")
}
if d.HasChange("display_name") {
updateMask = append(updateMask, "display_name")
}
_, err = config.NewIamClient(userAgent).Projects.ServiceAccounts.Patch(d.Id(),
&iam.PatchServiceAccountRequest{
UpdateMask: strings.Join(updateMask, ","),
ServiceAccount: &iam.ServiceAccount{
DisplayName: d.Get("display_name").(string),
Description: d.Get("description").(string),
Etag: sa.Etag,
},
}).Do()
if err != nil {
return err
}
// This API is meant to be synchronous, but in practice it shows the old value for
// a few milliseconds after the update goes through. 5 seconds is more than enough
// time to ensure following reads are correct.
time.Sleep(time.Second * 5)
return nil
}
func resourceGoogleServiceAccountImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
if err := parseImportId([]string{
"projects/(?P<project>[^/]+)/serviceAccounts/(?P<email>[^/]+)",
"(?P<project>[^/]+)/(?P<email>[^/]+)",
"(?P<email>[^/]+)"}, d, config); err != nil {
return nil, err
}
// Replace import id for the resource id
id, err := replaceVars(d, config, "projects/{{project}}/serviceAccounts/{{email}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}