forked from hashicorp/terraform-provider-google
/
resource_iam_audit_config.go
221 lines (200 loc) · 8.3 KB
/
resource_iam_audit_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
package google
import (
"errors"
"fmt"
"log"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"google.golang.org/api/cloudresourcemanager/v1"
)
var iamAuditConfigSchema = map[string]*schema.Schema{
"service": {
Type: schema.TypeString,
Required: true,
Description: `Service which will be enabled for audit logging. The special value allServices covers all services.`,
},
"audit_log_config": {
Type: schema.TypeSet,
Required: true,
Description: `The configuration for logging of each type of permission. This can be specified multiple times.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"log_type": {
Type: schema.TypeString,
Required: true,
Description: `Permission type for which logging is to be configured. Must be one of DATA_READ, DATA_WRITE, or ADMIN_READ.`,
},
"exempted_members": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Optional: true,
Description: `Identities that do not cause logging for this type of permission. Each entry can have one of the following values:user:{emailid}: An email address that represents a specific Google account. For example, alice@gmail.com or joe@example.com. serviceAccount:{emailid}: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com. group:{emailid}: An email address that represents a Google group. For example, admins@example.com. domain:{domain}: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com.`,
},
},
},
},
"etag": {
Type: schema.TypeString,
Computed: true,
Description: `The etag of iam policy`,
},
}
func ResourceIamAuditConfig(parentSpecificSchema map[string]*schema.Schema, newUpdaterFunc newResourceIamUpdaterFunc, resourceIdParser resourceIdParserFunc) *schema.Resource {
return ResourceIamAuditConfigWithBatching(parentSpecificSchema, newUpdaterFunc, resourceIdParser, IamBatchingDisabled)
}
func ResourceIamAuditConfigWithBatching(parentSpecificSchema map[string]*schema.Schema, newUpdaterFunc newResourceIamUpdaterFunc, resourceIdParser resourceIdParserFunc, enableBatching bool) *schema.Resource {
return &schema.Resource{
Create: resourceIamAuditConfigCreateUpdate(newUpdaterFunc, enableBatching),
Read: resourceIamAuditConfigRead(newUpdaterFunc),
Update: resourceIamAuditConfigCreateUpdate(newUpdaterFunc, enableBatching),
Delete: resourceIamAuditConfigDelete(newUpdaterFunc, enableBatching),
Schema: mergeSchemas(iamAuditConfigSchema, parentSpecificSchema),
Importer: &schema.ResourceImporter{
State: iamAuditConfigImport(resourceIdParser),
},
UseJSONNumber: true,
}
}
func resourceIamAuditConfigRead(newUpdaterFunc newResourceIamUpdaterFunc) schema.ReadFunc {
return func(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
updater, err := newUpdaterFunc(d, config)
if err != nil {
return err
}
eAuditConfig := getResourceIamAuditConfig(d)
p, err := iamPolicyReadWithRetry(updater)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("AuditConfig for %s on %q", eAuditConfig.Service, updater.DescribeResource()))
}
log.Printf("[DEBUG]: Retrieved policy for %s: %+v", updater.DescribeResource(), p)
var ac *cloudresourcemanager.AuditConfig
for _, b := range p.AuditConfigs {
if b.Service != eAuditConfig.Service {
continue
}
ac = b
break
}
if ac == nil {
log.Printf("[DEBUG]: AuditConfig for service %q not found in policy for %s, removing from state file.", eAuditConfig.Service, updater.DescribeResource())
d.SetId("")
return nil
}
if err := d.Set("etag", p.Etag); err != nil {
return fmt.Errorf("Error setting etag: %s", err)
}
err = d.Set("audit_log_config", flattenAuditLogConfigs(ac.AuditLogConfigs))
if err != nil {
return fmt.Errorf("Error flattening audit log config: %s", err)
}
if err := d.Set("service", ac.Service); err != nil {
return fmt.Errorf("Error setting service: %s", err)
}
return nil
}
}
func iamAuditConfigImport(resourceIdParser resourceIdParserFunc) schema.StateFunc {
return func(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) {
if resourceIdParser == nil {
return nil, errors.New("Import not supported for this IAM resource.")
}
config := m.(*Config)
s := strings.Fields(d.Id())
if len(s) != 2 {
d.SetId("")
return nil, fmt.Errorf("Wrong number of parts to AuditConfig id %s; expected 'resource_name service'.", s)
}
id, service := s[0], s[1]
// Set the ID only to the first part so all IAM types can share the same resourceIdParserFunc.
d.SetId(id)
if err := d.Set("service", service); err != nil {
return nil, fmt.Errorf("Error setting service: %s", err)
}
err := resourceIdParser(d, config)
if err != nil {
return nil, err
}
// Set the ID again so that the ID matches the ID it would have if it had been created via TF.
// Use the current ID in case it changed in the resourceIdParserFunc.
d.SetId(d.Id() + "/audit_config/" + service)
return []*schema.ResourceData{d}, nil
}
}
func resourceIamAuditConfigCreateUpdate(newUpdaterFunc newResourceIamUpdaterFunc, enableBatching bool) func(*schema.ResourceData, interface{}) error {
return func(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
updater, err := newUpdaterFunc(d, config)
if err != nil {
return err
}
ac := getResourceIamAuditConfig(d)
modifyF := func(ep *cloudresourcemanager.Policy) error {
cleaned := removeAllAuditConfigsWithService(ep.AuditConfigs, ac.Service)
ep.AuditConfigs = append(cleaned, ac)
return nil
}
if enableBatching {
err = BatchRequestModifyIamPolicy(updater, modifyF, config, fmt.Sprintf(
"Overwrite audit config for service %s on resource %q", ac.Service, updater.DescribeResource()))
} else {
err = iamPolicyReadModifyWrite(updater, modifyF)
}
if err != nil {
return err
}
d.SetId(updater.GetResourceId() + "/audit_config/" + ac.Service)
return resourceIamAuditConfigRead(newUpdaterFunc)(d, meta)
}
}
func resourceIamAuditConfigDelete(newUpdaterFunc newResourceIamUpdaterFunc, enableBatching bool) schema.DeleteFunc {
return func(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
updater, err := newUpdaterFunc(d, config)
if err != nil {
return err
}
ac := getResourceIamAuditConfig(d)
modifyF := func(ep *cloudresourcemanager.Policy) error {
ep.AuditConfigs = removeAllAuditConfigsWithService(ep.AuditConfigs, ac.Service)
return nil
}
if enableBatching {
err = BatchRequestModifyIamPolicy(updater, modifyF, config, fmt.Sprintf(
"Delete audit config for service %s on resource %q", ac.Service, updater.DescribeResource()))
} else {
err = iamPolicyReadModifyWrite(updater, modifyF)
}
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Resource %s with IAM audit config %q", updater.DescribeResource(), d.Id()))
}
return resourceIamAuditConfigRead(newUpdaterFunc)(d, meta)
}
}
func getResourceIamAuditConfig(d *schema.ResourceData) *cloudresourcemanager.AuditConfig {
auditLogConfigSet := d.Get("audit_log_config").(*schema.Set)
auditLogConfigs := make([]*cloudresourcemanager.AuditLogConfig, auditLogConfigSet.Len())
for x, y := range auditLogConfigSet.List() {
logConfig := y.(map[string]interface{})
auditLogConfigs[x] = &cloudresourcemanager.AuditLogConfig{
LogType: logConfig["log_type"].(string),
ExemptedMembers: convertStringArr(logConfig["exempted_members"].(*schema.Set).List()),
}
}
return &cloudresourcemanager.AuditConfig{
AuditLogConfigs: auditLogConfigs,
Service: d.Get("service").(string),
}
}
func flattenAuditLogConfigs(configs []*cloudresourcemanager.AuditLogConfig) *schema.Set {
auditLogConfigSchema := iamAuditConfigSchema["audit_log_config"].Elem.(*schema.Resource)
exemptedMemberSchema := auditLogConfigSchema.Schema["exempted_members"].Elem.(*schema.Schema)
res := schema.NewSet(schema.HashResource(auditLogConfigSchema), []interface{}{})
for _, conf := range configs {
res.Add(map[string]interface{}{
"log_type": conf.LogType,
"exempted_members": schema.NewSet(schema.HashSchema(exemptedMemberSchema), convertStringArrToInterface(conf.ExemptedMembers)),
})
}
return res
}