-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbiganimal-csp-setup
executable file
·503 lines (466 loc) · 16.4 KB
/
biganimal-csp-setup
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#!/usr/bin/env bash
#
# Copyright 2021,2022 EnterpriseDB Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This script is used to create a SPN(Service Principal Name) with enough
# permissions in your Azure subscription for handling the BigAnimal managed
# service, or update SPN with MS Graph API permissions.
#
# What it does:
# - assume you have already login to your Azure AD(Active Directory) directory by Azure CLI
# - set your Azure CLI context to the given subscription
# - create a custom role with resource permissions documented in ./biganimal-poweruser-template.json
# - create a new client app or update client app in the Azure AD directory
# - grant the custom role to the client app
#
# it finally outputs the:
# - client app Id
# - client app secret
# - your Azure subscription Id
# These outputs will be used in the BigAnimal Signup submission form.
#
# For more details, please refer to
# https://www.enterprisedb.com/docs/edbcloud/latest/getting_started/02_connect_cloud_account
#
set -e
display_name=""
subscription=""
years=""
client_id=""
spn=""
spn_role=""
app_id=""
role_id=""
CURRENT_PATH=$(pwd)
TMPDIR=$(mktemp -d)
function cleanup {
rm -rf "${TMPDIR}"
}
trap cleanup EXIT
pushd "${TMPDIR}" >/dev/null || exit
show_help()
{
echo "Required permissions:"
echo " Microsoft.Authorization/roleAssignments/write"
echo "Required tools:"
echo " jq"
echo "Usage:"
echo " $0 -d NAME -s SUBSCRIPTION_ID [-i CLIENT_ID] [options]"
echo ""
echo "Options:"
echo " -d, --display-name: The name of Azure AD App."
echo " -s, --subscription: The Azure Subscription ID used by BigAnimal."
echo " -t, --tenant: [Optional] The Azure AD Tenant ID used by BigAnimal."
echo " -y, --years: [Optional] The Number of years for which the credentials will be valid. Only accept positive integer value. Default: 1 year."
echo " -i, --id: [Optional] The Application (client) ID of Service Principal will be updated."
echo " -h, --help: Show this help."
echo ""
}
check()
{
# jq is required
hash jq > /dev/null 2>&1 || { show_help; suggest "Error: please install jq on the system" alert; }
check_az_version
check_display_name
check_subscription
if [[ -n "${client_id}" && -z "${tenant}" ]]; then
suggest "When specifiying the Azure AD Service Principal application ${client_id} you need to specify also the Azure AD tenant with -t|--tenant!" alert
exit 1
fi
}
suggest()
{
local what=$1
local highlight=$2
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'
if [ "$highlight" = 'alert' ]; then
echo -e "${RED}${what}${NC}"
else
echo -e "${GREEN}${what}${NC}"
fi
}
# refer from
# https://stackoverflow.com/questions/4023830/how-to-compare-two-strings-in-dot-separated-version-format-in-bash
vercomp () {
if [[ $1 == $2 ]]
then
return 0
fi
local IFS=.
local i ver1=($1) ver2=($2)
# fill empty fields in ver1 with zeros
for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
do
ver1[i]=0
done
for ((i=0; i<${#ver1[@]}; i++))
do
if [[ -z ${ver2[i]} ]]
then
# fill empty fields in ver2 with zeros
ver2[i]=0
fi
if ((10#${ver1[i]} > 10#${ver2[i]}))
then
return 1
fi
if ((10#${ver1[i]} < 10#${ver2[i]}))
then
return 2
fi
done
return 0
}
#### Check Azure CLI version
function check_az_version {
set +e
version=$(az version --query \"azure-cli\" -o tsv)
if command -v clouddrive &> /dev/null; then
echo "Run Azure CSP setup with azure-cli ${version} in Azure Cloud shell"
else
# only support azure-cli >= 2.31.0
vercomp "${version}" 2.31.0
if [ $? -eq 2 ]; then
suggest "Error: this script only supports azure-cli >= 2.31.0" alert
exit 1
fi
echo "Run Azure CSP setup with azure-cli ${version}"
fi
# check if we are running azure-cli >= 2.37.0
msgraphapi=true
vercomp "${version}" 2.37.0
if [ $? -eq 2 ]; then
msgraphapi=false
fi
set -e
}
check_display_name()
{
if [[ "${display_name}" == "" ]]; then
show_help
suggest "Error: missing -d, --display-name to specify Azure AD App name" alert
exit 1
fi
}
check_subscription()
{
if [[ "${subscription}" == "" ]]; then
show_help
suggest "Error: missing -s, --subscription to specify Azure Subscription" alert
exit 1
fi
}
check_tenant()
{
if [[ "${tenant}" == "" ]]; then
show_help
suggest "Error: missing -t, --tenant to specify Azure Tenant" alert
exit 1
fi
}
check_years()
{
if [[ "${years}" == "" ]]; then
show_help
suggest "Error: -y, --years should have a value" alert
exit 1
fi
}
check_id()
{
if [[ -n "${client_id}" ]]; then
display_name=$(az ad app show --id "${client_id}" -o tsv --query displayName --only-show-errors)
fi
}
download_dependencies()
{
# a shell func to download all the dependencies of this script before starting to execute
# Download the latest biganimal role template or overwrite it
template_file=biganimal-poweruser-template.json
curl https://raw.githubusercontent.com/EnterpriseDB/cloud-utilities/main/azure/${template_file} -o "${CURRENT_PATH}"/${template_file}
if [[ -s "${CURRENT_PATH}/${template_file}" ]]; then
echo "Downloaded ${CURRENT_PATH}/${template_file}"
else
echo "Error: failed to download ${CURRENT_PATH}/${template_file}"
exit 1
fi
}
retry ()
{
local attempts=5
local count=0
until "$@"; do
# shellcheck disable=SC2004
wait=$((5 ** $count))
# shellcheck disable=SC2004
count=$(($count + 1))
if [ $count -lt $attempts ]; then
echo "Retrying in $wait seconds..."
sleep $wait
else
echo "Retried $count attempts with failure, the command/function that has failed is:"
echo "$@"
return 0
fi
done
return 0
}
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-h|--help)
show_help
exit 0
;;
-i|--id)
client_id="$2"
check_id
shift 2
;;
-d|--display-name)
display_name="$2"
check_display_name
shift 2
;;
-s|--subscription)
subscription="$2"
check_subscription
shift 2
;;
-t|--tenant)
tenant="$2"
check_tenant
shift 2
;;
-y|--years)
years="$2"
check_years
shift 2
;;
*)
shift
;;
esac
done
set_subscription()
{
echo "Change to use Azure Subscription ${subscription}..."
az account set --subscription "${subscription}"
}
show_account()
{
az account show
}
create_or_update_custom_role()
{
# get custom role id
echo "Create or update custom role"
role_name="biganimal-poweruser-${subscription}"
roleScope="/subscriptions/${subscription}"
role_id=$(az role definition list --only-show-errors --query "[?roleName=='${role_name}'].id" -o tsv)
jq --arg rolename "$role_name" --arg scope "$roleScope" '(.Name) |= $rolename | (.assignableScopes[]) |= $scope' \
"${CURRENT_PATH}"/biganimal-poweruser-template.json > "${CURRENT_PATH}"/biganimal-poweruser.json
if [[ -z "${role_id}" ]]; then
echo "Did not find the custom role, creating it..."
create_custom_role
else
echo "Fetched role is ${role_id}"
retry update_custom_role
fi
}
wait_for_custom_role()
{
role_name="biganimal-poweruser-${subscription}"
role_id=$(az role definition list --only-show-errors --query "[?roleName=='${role_name}'].id" -o tsv)
if [[ -z "${role_id}" ]]; then
echo "Did not find the custom role, checking again in a while..."
return 1
else
echo "Custom role exists with ID ${role_id}, proceeding..."
return 0
fi
}
check_custom_role()
{
# check for custom role existance
# sometimes Azure AD requires time to propagate it as staten here
# https://learn.microsoft.com/en-us/azure/role-based-access-control/troubleshooting?source=recommendations&tabs=bicep#symptom---assigning-a-role-to-a-new-principal-sometimes-fails
retry wait_for_custom_role
if [[ -z "${role_id}" ]]; then
suggest "The Azure AD Custom Role creation/replication has not completed successfully! Please retry in a few minutes..." alert
exit 1
fi
}
wait_for_spn()
{
spn_exist=$(az ad sp list --spn "${app_id}" | jq -r 'length')
if (( spn_exist > 0 )); then
echo "Updating Azure AD Service Principal application ${app_id} and configuring its access to Azure resources in subscription ${subscription}..."
spn_role=$(az role assignment create --assignee "${app_id}" --role "${role_name}" --scope /subscriptions/"${subscription}" --only-show-errors)
if [[ -z "${spn_role}" ]]; then
echo "Did not find the role, Azure may need some time to replicate the role, checking again in a while..."
return 1
fi
return 0
else
echo "Did not find the SPN, checking again in a while..."
return 1
fi
}
create_ad_sp()
{
echo "rolename: ${role_name}"
# create or update SPN using azure-cli
years="${years:-1}"
if [[ -z "${client_id}" ]]; then
echo "Creating Azure AD Service Principal in subscription ${subscription}..."
spn=$(az ad sp create-for-rbac -o json -n "${display_name}" --only-show-errors --years "${years}")
app_id=$(echo "${spn}" | jq -r .appId)
retry wait_for_spn
if [[ -z "${spn_role}" ]]; then
suggest "cannot find the role ${role_name}, Azure may need more minutes to replicate the role" alert
suggest "please wait for the role ${role_name} replication, clean up the SPN ${display_name} and retry later" alert
exit 1
fi
else
echo "Checking if Azure AD Service Principal application ${client_id} already exists in subscription ${subscription} and tenant ${tenant}..."
spn_exist=$(az ad sp list --spn "${client_id}" | jq -r 'length')
if (( spn_exist > 0 )); then
echo "Updating Azure AD Service Principal application ${client_id} in subscription ${subscription} and tenant ${tenant}..."
spn=$(az ad sp credential reset --id "${client_id}" --display-name "${display_name}" --append --years "${years}" --only-show-errors)
spn_role=$(az role assignment create --assignee "${client_id}" --role "${role_name}" --scope /subscriptions/"${subscription}" --only-show-errors)
else
suggest "Azure AD Service Principal application ${client_id} does NOT exists in subscription ${subscription} and tenant ${tenant}!" alert
exit 1
fi
fi
}
add_spn_owners()
{
# add current user and spn to the SPN owner list
if [[ -z "${client_id}" ]]; then
client_id=$(echo "${spn}" | jq -r .appId)
else
skip_addowners="true"
fi
# The following checks changes starting from Azure CLI 2.37 due to the usage of MS Graph APIs
# refers to https://github.com/Azure/azure-cli/issues/22580
if [ "$msgraphapi" = "false" ]; then
sp_object_id=$(az ad sp show --id "${client_id}" -o tsv --query objectId --only-show-errors)
user_object_id=$(az ad signed-in-user show -o tsv --query objectId --only-show-errors)
else
sp_object_id=$(az ad sp show --id "${client_id}" -o tsv --query id --only-show-errors)
user_object_id=$(az ad signed-in-user show -o tsv --query id --only-show-errors)
fi
echo "Add Azure AD Service Principal Owners..."
# To add owners to application
az ad app owner add --id "${client_id}" --owner-object-id "${sp_object_id}" --only-show-errors
az ad app owner add --id "${client_id}" --owner-object-id "${user_object_id}" --only-show-errors
# To add owners to service principal
# this doesn't need to be done while updating an existing SPN, and if done it fails with
# One or more added object references already exist for the following modified properties: 'owners'
if [[ -z "${skip_addowners}" ]]; then
retry az rest -m POST -u https://graph.microsoft.com/beta/servicePrincipals/"${sp_object_id}"/owners/\$ref \
--headers Content-Type=application/json --output none \
-b "{\"@odata.id\": \"https://graph.microsoft.com/beta/servicePrincipals/${sp_object_id}\"}"
fi
}
create_custom_role()
{
# create custom role for the SPN
echo "Creating custom role for Azure AD Service Principal..."
az role definition create --subscription "${subscription}" --role-definition "${CURRENT_PATH}"/biganimal-poweruser.json \
--only-show-errors
}
update_custom_role()
{
# update custom role for the SPN
echo "update custom role for Azure AD Service Principal..."
az role definition update --subscription "${subscription}" --role-definition "${CURRENT_PATH}"/biganimal-poweruser.json \
--only-show-errors
}
grant_api_permissions()
{
# Add graph API permissions to the SPN, and grant admin consent
if [ "$msgraphapi" = "false" ]; then
sp_object_id=$(az ad sp show --id "${client_id}" -o tsv --query objectId --only-show-errors)
else
sp_object_id=$(az ad sp show --id "${client_id}" -o tsv --query id --only-show-errors)
fi
# Microsoft Graph Application ID: 00000003-0000-0000-c000-000000000000
# retrieve Application.ReadWrite.OwnedBy appId: 18a4783c-866b-4cc7-a460-3d5e5662c884
# az ad sp show --id 00000003-0000-0000-c000-000000000000 \
# --query "appRoles[?value=='Application.ReadWrite.OwnedBy']"
# retrieve Directory.Read.All appId: 7ab1d382-f21e-4acd-a863-ba3e13f7da61
# az ad sp show --id 00000003-0000-0000-c000-000000000000 \
# --query "appRoles[?value=='Directory.Read.All']"
# To add API permissions
# Application.ReadWrite.OwnedBy
az ad app permission add --id "${client_id}" --only-show-errors \
--api 00000003-0000-0000-c000-000000000000 \
--api-permissions 18a4783c-866b-4cc7-a460-3d5e5662c884=Role
# Directory.Read.All
az ad app permission add --id "${client_id}" --only-show-errors \
--api 00000003-0000-0000-c000-000000000000 \
--api-permissions 7ab1d382-f21e-4acd-a863-ba3e13f7da61=Role
# To grant admin
if [ "$msgraphapi" = "false" ]; then
resourceId=$(az ad sp show --id 00000003-0000-0000-c000-000000000000 --query "objectId" --output tsv --only-show-errors)
else
resourceId=$(az ad sp show --id 00000003-0000-0000-c000-000000000000 --query "id" --output tsv --only-show-errors)
fi
az rest --method POST \
--uri https://graph.microsoft.com/v1.0/servicePrincipals/"${sp_object_id}"/appRoleAssignments \
--headers Content-Type=application/json --output none \
--body "{
\"principalId\": \"${sp_object_id}\",
\"resourceId\": \"${resourceId}\",
\"appRoleId\": \"18a4783c-866b-4cc7-a460-3d5e5662c884\"}" 2>${TMPDIR}/OUTPUT || true
az rest --method POST \
--uri https://graph.microsoft.com/v1.0/servicePrincipals/"${sp_object_id}"/appRoleAssignments \
--headers Content-Type=application/json --output none \
--body "{
\"principalId\": \"${sp_object_id}\",
\"resourceId\": \"${resourceId}\",
\"appRoleId\": \"7ab1d382-f21e-4acd-a863-ba3e13f7da61\"}" 2>>${TMPDIR}/OUTPUT || true
# catch Authorization_RequestDenied exception messages
[[ $(cat ${TMPDIR}/OUTPUT) == *"Authorization_RequestDenied"* ]] && echo -e "\033[0;31mError: Please request Azure AD Global Administrator or Privileged Role Administrator to grant admin consent permissions for Service Principal ${display_name}(${client_id})\033[0m" && exit 1
return 0
}
print_and_save_result()
{
local client_secret="N/A"
[[ -n "${spn}" ]] && client_secret=$(echo "${spn}" | jq -r .password)
tenant=$(az account show -s "${subscription}" -o json | jq -r .tenantId)
jq --null-input \
--arg client_id "${client_id}" \
--arg client_secret "REDACTED" \
--arg subscription "${subscription}" \
--arg tenant "${tenant}" \
'{"client_id":$client_id,"client_secret":$client_secret,"subscription_id":$subscription,"tenant_id":$tenant}'
# exporting JSON "ba-passport.json" that will be used by BigAnimal CLI
echo "{\"client_id\":\"${client_id}\",\"client_secret\":\"${client_secret}\",\"subscription_id\":\"${subscription}\",\"tenant_id\":\"${tenant}\"}" > "$CURRENT_PATH"/ba-passport.json
}
check
download_dependencies
set_subscription
show_account
create_or_update_custom_role
check_custom_role
create_ad_sp
add_spn_owners
grant_api_permissions
print_and_save_result