-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
resource_arm_role_assignment.go
217 lines (179 loc) · 5.84 KB
/
resource_arm_role_assignment.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
package azurerm
import (
"fmt"
"log"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/preview/authorization/mgmt/2018-01-01-preview/authorization"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)
func resourceArmRoleAssignment() *schema.Resource {
return &schema.Resource{
Create: resourceArmRoleAssignmentCreate,
Read: resourceArmRoleAssignmentRead,
Delete: resourceArmRoleAssignmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"scope": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"role_definition_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"role_definition_name"},
DiffSuppressFunc: ignoreCaseDiffSuppressFunc,
},
"role_definition_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"role_definition_id"},
ValidateFunc: validateRoleDefinitionName,
},
"principal_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
}
}
func resourceArmRoleAssignmentCreate(d *schema.ResourceData, meta interface{}) error {
roleAssignmentsClient := meta.(*ArmClient).roleAssignmentsClient
roleDefinitionsClient := meta.(*ArmClient).roleDefinitionsClient
ctx := meta.(*ArmClient).StopContext
name := d.Get("name").(string)
scope := d.Get("scope").(string)
var roleDefinitionId string
if v, ok := d.GetOk("role_definition_id"); ok {
roleDefinitionId = v.(string)
} else if v, ok := d.GetOk("role_definition_name"); ok {
value := v.(string)
filter := fmt.Sprintf("roleName eq '%s'", value)
roleDefinitions, err := roleDefinitionsClient.List(ctx, "", filter)
if err != nil {
return fmt.Errorf("Error loading Role Definition List: %+v", err)
}
if len(roleDefinitions.Values()) != 1 {
return fmt.Errorf("Error loading Role Definition List: could not find role '%s'", value)
}
roleDefinitionId = *roleDefinitions.Values()[0].ID
} else {
return fmt.Errorf("Error: either role_definition_id or role_definition_name needs to be set")
}
d.Set("role_definition_id", roleDefinitionId)
principalId := d.Get("principal_id").(string)
if name == "" {
uuid, err := uuid.GenerateUUID()
if err != nil {
return fmt.Errorf("Error generating UUID for Role Assignment: %+v", err)
}
name = uuid
}
properties := authorization.RoleAssignmentCreateParameters{
RoleAssignmentProperties: &authorization.RoleAssignmentProperties{
RoleDefinitionID: utils.String(roleDefinitionId),
PrincipalID: utils.String(principalId),
},
}
err := resource.Retry(300*time.Second, retryRoleAssignmentsClient(scope, name, properties, meta))
if err != nil {
return err
}
read, err := roleAssignmentsClient.Get(ctx, scope, name)
if err != nil {
return err
}
if read.ID == nil {
return fmt.Errorf("Cannot read Role Assignment ID for %q (Scope %q)", name, scope)
}
d.SetId(*read.ID)
return resourceArmRoleAssignmentRead(d, meta)
}
func resourceArmRoleAssignmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).roleAssignmentsClient
ctx := meta.(*ArmClient).StopContext
resp, err := client.GetByID(ctx, d.Id())
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Role Assignment ID %q was not found - removing from state", d.Id())
d.SetId("")
return nil
}
return fmt.Errorf("Error loading Role Assignment %q: %+v", d.Id(), err)
}
d.Set("name", resp.Name)
if props := resp.RoleAssignmentPropertiesWithScope; props != nil {
d.Set("scope", props.Scope)
d.Set("role_definition_id", props.RoleDefinitionID)
d.Set("principal_id", props.PrincipalID)
}
return nil
}
func resourceArmRoleAssignmentDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).roleAssignmentsClient
ctx := meta.(*ArmClient).StopContext
id, err := parseRoleAssignmentId(d.Id())
if err != nil {
return err
}
resp, err := client.Delete(ctx, id.scope, id.name)
if err != nil {
if !utils.ResponseWasNotFound(resp.Response) {
return err
}
}
return nil
}
func validateRoleDefinitionName(i interface{}, k string) ([]string, []error) {
v, ok := i.(string)
if !ok {
return nil, []error{fmt.Errorf("expected type of %s to be string", k)}
}
if ok := strings.Contains(v, "(Preview)"); ok {
return nil, []error{fmt.Errorf("Preview roles are not supported")}
}
return nil, nil
}
func retryRoleAssignmentsClient(scope string, name string, properties authorization.RoleAssignmentCreateParameters, meta interface{}) func() *resource.RetryError {
return func() *resource.RetryError {
roleAssignmentsClient := meta.(*ArmClient).roleAssignmentsClient
ctx := meta.(*ArmClient).StopContext
_, err := roleAssignmentsClient.Create(ctx, scope, name, properties)
if err != nil {
return resource.RetryableError(err)
}
return nil
}
}
type roleAssignmentId struct {
scope string
name string
}
func parseRoleAssignmentId(input string) (*roleAssignmentId, error) {
segments := strings.Split(input, "/providers/Microsoft.Authorization/roleAssignments/")
if len(segments) != 2 {
return nil, fmt.Errorf("Expected Role Assignment ID to be in the format `{scope}/providers/Microsoft.Authorization/roleAssignments/{name}` but got %q", input)
}
// /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}
id := roleAssignmentId{
scope: strings.TrimPrefix(segments[0], "/"),
name: segments[1],
}
return &id, nil
}