-
Notifications
You must be signed in to change notification settings - Fork 2
/
biganimal-csp-setup
executable file
·503 lines (471 loc) · 32.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 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 an IAM role and and IAM policy with enough
# permissions in your AWS account for handling the BigAnimal managed
# service, and returing its ARN in a "ba-passport.json".
#
# What it does:
# - assume you have an AWS profile configured to work with the AWS CLI
# - configured your AWS profile to work with the selected account
# - create an IAM policy following the PoLP (Principle of Least Privilege)
# - create an IAM role attaching the previously created IAM policy
# - write the IAM role ARN into a local file named "ba-passport.json"
# - request for needed service quota increases if asked to
#
# it finally outputs the:
# - IAM policy ARN
# - IAM role ARN
# - AWS account ID where those resources have been created
# - The new Service Quota that have been requested
# The "ba-passport.json" file content will be used later on with the BigAnimal CLI
# to connect your AWS account to your BigAnimal cloud account.
#
# For more details, please refer to
# https://www.enterprisedb.com/docs/edbcloud/latest/getting_started/02_connect_cloud_account
#
set -e
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'
[ "${BASH_VERSINFO:-0}" -lt 4 ] && echo -e "${RED}This script does not support Bash version 3 and below!${NC}" && show_help && exit 1
CURRENT_PATH=$(pwd)
# Default values for resources naming
suffix_policy_name="policy"
suffix_role_name="role"
account=""
biganimal_account_id=""
external_id=""
region=""
increase_quota=false
declare -A quota_increases
aws_used_service_quota_codes=("ec2" "vpc" "elasticloadbalancing")
declare -A quota_names
policy_arn=""
base_policy_arn=""
addon_policy_arn=""
role_arn=""
TMPDIR=$(mktemp -d)
function cleanup {
rm -rf "${TMPDIR}"
}
trap cleanup EXIT
pushd "${TMPDIR}" >/dev/null || exit
show_help()
{
echo "Required permissions:"
echo " arn:aws:iam::aws:policy/IAMFullAccess"
echo " arn:aws:iam::aws:policy/ServiceQuotasFullAccess"
echo " or equivalents like"
echo " arn:aws:iam::aws:policy/AdministratorAccess"
echo "Required tools:"
echo " jq"
echo "Usage:"
echo -e " ${GREEN}$0 -a ACCOUNT_ID -b BIGANIMAL_ACCOUNT_ID -e EXTERNAL_ID [options]${NC}"
echo ""
echo "Options:"
echo " -a, --account: Your AWS account ID that will be used by BigAnimal."
echo " -b, --biganimal-account: The AWS account ID provided by BigAnimal (should be a 12 chars numeric string)."
echo " -e, --external-id: The AWS external ID provided by BigAnimal (should be a 16 chars alphanumeric string)."
echo " -p, --policy-name-suffix: The suffix part in the name of the IAM policies (defaults policies name are 'biganimal-base' and 'biganimal-addon')."
echo " -r, --role-name-suffix: The suffix part in the name of the IAM role (defaults role name is 'biganimal-role')."
echo " -q, --increase-quotas: Create tickets to request Service Quota increases if needed (defaults to false)."
echo " -g, --region: The name of the AWS region in which ask for service quota increases (defaults to your AWS CLI profile)"
echo " -h, --help: Show this help."
echo ""
echo "Examples:"
echo " $0 -a 123456789012 -b 987654321098 -e aA1bB2cC3dD4eE5f"
echo " $0 -a 123456789012 -b 987654321098 -e aA1bB2cC3dD4eE5f -p \"my_policy_suffix\" -r \"my_role_suffix\" -q"
echo " this will create two policies named 'biganimal-base-my_policy_suffix'+'biganimal-addon-my_policy_suffix' and a role named 'biganimal-role-my_role_suffix'"
echo ""
}
check()
{
#### Check AWS CLI version
check_aws_version
# jq is required.
hash jq > /dev/null 2>&1 || { show_help; echo -e "${RED}Error: please install jq on the system${NC}"; }
check_account
check_biganimal_account_id
check_external_id
check_increase_quotas
}
version() { echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }'; }
check_aws_version()
{
fullcliversion=$(aws --version)
cliversionstripped=${fullcliversion% Python*}
cliversion=${cliversionstripped#*/}
if [[ "$AWS_EXECUTION_ENV" == "CloudShell" ]]; then
echo -e "${GREEN}Run AWS CSP setup with aws-cli ${cliversion} in AWS CloudShell${NC}"
else
[ "$(version "$cliversion")" -lt "$(version "2.3.0")" ] && echo -e "${RED}Error: upgrade aws-cli to 2.3.0 or later${NC}" && exit 1
echo -e "${GREEN}Run AWS CSP setup with aws-cli ${cliversion}${NC}"
fi
}
check_account()
{
if [[ "${account}" == "" ]]; then
echo -e "${RED}Error: missing -a, --account to specify the AWS account ID${NC}"
show_help
exit 1
fi
# check that the aws cli is configured to work with the given account and we have access to
set +e
current_account=$(aws sts get-caller-identity --no-cli-pager --query 'Account' --output text)
if [ $? -ne 0 ]; then
echo -e "${RED}Error while checking AWS credentials/profile configuration, please login/configure your AWS CLI session/profile${NC}"
show_help
exit 1
fi
set -e
if [[ ! "${current_account}" == "$account" ]]; then
echo -e "${RED}Error: AWS CLI not configured to work with the requested account $account!${NC}"
echo -e "${RED}The configured account ID is ${current_account}!${NC}"
show_help
exit 1
fi
}
check_biganimal_account_id()
{
if [[ "${biganimal_account_id}" == "" ]]; then
echo -e "${RED}Error: missing -b, --biganimal-account to specify the AWS account ID provided by BigAnimal${NC}"
show_help
exit 1
fi
if [[ ! "$biganimal_account_id" =~ ^[0-9]{12}$ ]]; then
echo -e "${RED}Error: the specified biganimal-account is wrong, it should be a 12 chars numeric string!${NC}"
show_help
exit 1
fi
}
check_external_id()
{
if [[ "${external_id}" == "" ]]; then
echo -e "${RED}Error: missing -e, --external-id to specify the AWS external ID provided by BigAnimal${NC}"
show_help
exit 1
fi
if [[ ! "$external_id" =~ ^[a-zA-Z0-9]{16}$ ]]; then
echo -e "${RED}Error: the specified external-id is wrong, it should be a 16 chars alphanumeric string!${NC}"
show_help
exit 1
fi
}
check_increase_quotas()
{
if [[ "$increase_quota" == "true" ]]; then
if [ -s "${CURRENT_PATH}/ba-preflight.json" ]; then
set +e
jq empty "${CURRENT_PATH}"/ba-preflight.json
[ $? -ne 0 ] && echo -e "${RED}Error while checking ${CURRENT_PATH}/ba-preflight.json, it doesn't have a valid JSON content${NC}" \
&& show_help && exit 1
set -e
for key in $(jq -r 'keys[]' "${CURRENT_PATH}"/ba-preflight.json); do
quota_increases[${key}]=$(jq -r ".\"$key\"" "${CURRENT_PATH}"/ba-preflight.json)
done
else
echo -e "${RED}Error: can't find ba-preflight.json in ${CURRENT_PATH}!${NC}"
show_help
exit 1
fi
fi
}
while [[ $# -gt 0 ]]; do
key="$1"
case $key in
-h|--help)
show_help
exit 0
;;
-a|--account)
account="$2"
shift 2
;;
-b|--biganimal-account)
biganimal_account_id="$2"
shift 2
;;
-e|--external-id)
external_id="$2"
shift 2
;;
-p|--policy-name-suffix)
suffix_policy_name="$2"
shift 2
;;
-r|--role-name-suffix)
suffix_role_name="$2"
shift 2
;;
-q|--increase-quotas)
increase_quota=true
shift
;;
-g|--region)
region="$2"
shift 2
;;
*)
shift
;;
esac
done
do_create_iam_policy()
{
local name=$1
local content=$2
echo "$content" > "${TMPDIR}"/"${name}".json
# verify if an IAM policy with the same name is already existing
policy_exists=$(aws iam list-policies --scope Local \
--query "length(Policies[*]|[?starts_with(PolicyName, \`${name}\`) == \`true\`]|[*].Arn)" \
--output json)
if [ "$policy_exists" -gt 0 ]; then
# an IAM policy with the same name already exists
# checking if it has more than 5 policy versions (that is the max allowed)
# https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreatePolicyVersion.html
policy_arn=$(aws iam list-policies --scope Local \
--query "Policies[*]|[?starts_with(PolicyName, \`${name}\`) == \`true\`]|[*].Arn" \
--output text)
echo -e "Updating AWS IAM policy ${GREEN}${name}${NC} within AWS account ${GREEN}${account}${NC}..."
policy_versions=$(aws iam list-policy-versions --policy-arn "$policy_arn" --output json --no-cli-pager \
--query "length(Versions[*].VersionId)")
if [ "$policy_versions" -eq 5 ]; then
# there are already 5 Policy Versions of this policy, going to delete the oldest one
policy_get_older_version=$(aws iam list-policy-versions --policy-arn "$policy_arn" --output text \
--no-cli-pager --query "Versions[-1].VersionId")
aws iam delete-policy-version --policy-arn "$policy_arn" --version-id "$policy_get_older_version" \
--output json > "${TMPDIR}"/biganimal_deletepolicyversion_output.json
fi
# create a new Policy Version and set it as default
aws iam create-policy-version --policy-arn "$policy_arn" --policy-document file://"${TMPDIR}"/"${name}".json \
--set-as-default --output json > "${TMPDIR}"/biganimal_createpolicyversion_output.json
else
# create IAM policy using aws-cli
echo -e "Creating AWS IAM policy ${GREEN}${name}${NC} within AWS account ${GREEN}${account}${NC}..."
aws iam create-policy --policy-name "${name}" --policy-document file://"${TMPDIR}"/"${name}".json \
--output json > "${TMPDIR}"/biganimal_createpolicy_output.json
policy_arn=$(jq -r '.Policy.Arn' "${TMPDIR}"/biganimal_createpolicy_output.json)
fi
# add the tag to the policy
aws iam tag-policy --policy-arn "${policy_arn}" --tags Key=ManagedBy,Value=BigAnimal
}
create_iam_role()
{
# IAM Policy
biganimal_base_policy=$(cat <<EOF
{"Version":"2012-10-17","Statement":[{"Action":["autoscaling:CreateOrUpdateTags","autoscaling:DeleteTags","autoscaling:DescribeAccountLimits","autoscaling:DescribeTags","cloudwatch:GetMetricData","cloudwatch:ListMetrics","ec2:AllocateAddress","ec2:AssociateRouteTable","ec2:AttachInternetGateway","ec2:CreateEgressOnlyInternetGateway","ec2:CreateInternetGateway","ec2:CreateNatGateway","ec2:CreateNetworkAcl","ec2:CreateNetworkAclEntry","ec2:DeleteNetworkAclEntry","ec2:CreateRoute","ec2:CreateRouteTable","ec2:CreateSecurityGroup","ec2:CreateSubnet","ec2:CreateTags","ec2:CreateVpc","ec2:CreateVpcEndpoint","ec2:Describe*","ec2:Get*","ec2:ListSnapshotsInRecycleBin","ecs:CreateCluster","ecs:RegisterTaskDefinition","eks:CreateAddon","eks:CreateCluster","eks:CreateNodegroup","eks:Describe*","eks:List*","elasticloadbalancing:DescribeLoadBalancers","iam:GetAccountSummary","iam:GetPolicy","iam:GetPolicyVersion","iam:GetRole","iam:GetRolePolicy","iam:ListAccessKeys","iam:ListAttachedRolePolicies","iam:ListEntitiesForPolicy","iam:ListInstanceProfileTags","iam:ListInstanceProfilesForRole","iam:ListMFADeviceTags","iam:ListMFADevices","iam:ListOpenIDConnectProviderTags","iam:ListOpenIDConnectProviders","iam:ListPolicies","iam:ListPoliciesGrantingServiceAccess","iam:ListPolicyTags","iam:ListPolicyVersions","iam:ListRolePolicies","iam:ListRoleTags","iam:ListRoles","iam:ListSAMLProviderTags","iam:ListSAMLProviders","iam:ListSSHPublicKeys","iam:ListServerCertificateTags","iam:ListServerCertificates","iam:ListServiceSpecificCredentials","iam:ListSigningCertificates","iam:ListVirtualMFADevices","kms:CreateAlias","kms:CreateKey","kms:ListAliases","kms:ListKeys","logs:DescribeLogGroups","logs:ListTagsLogGroup","s3:ListAllMyBuckets","servicequotas:ListAWSDefaultServiceQuotas","servicequotas:ListServiceQuotas","sts:DecodeAuthorizationMessage","ec2:AssociateVpcCidrBlock","ec2:CreateLaunchTemplate","ec2:CreateLaunchTemplateVersion","ec2:RunInstances","ec2:DeleteNetworkInterface"],"Effect":"Allow","Resource":"*"},{"Action":["cloudwatch:DeleteDashboards","cloudwatch:GetDashboard","cloudwatch:PutDashboard"],"Effect":"Allow","Resource":"arn:aws:cloudwatch::*:dashboard/Customer*"},{"Action":["ec2:CreateTags","ec2:DescribeTags","ec2:DeleteTags"],"Effect":"Allow","Resource":"*"},{"Action":["dynamodb:CreateTable","dynamodb:DeleteItem","dynamodb:DeleteTable","dynamodb:DescribeContinuousBackups","dynamodb:DescribeTable","dynamodb:GetItem","dynamodb:ListTables","dynamodb:ListTagsOfResource","dynamodb:PutItem","dynamodb:TagResource","dynamodb:UntagResource"],"Effect":"Allow","Resource":"arn:aws:dynamodb:*:*:table/tf-state-dynamodb-table*"},{"Effect":"Allow","Action":["ec2:AuthorizeSecurityGroupEgress","ec2:AuthorizeSecurityGroupIngress","ec2:Delete*","ec2:Detach*","ec2:Disassociate*","ec2:Modify*","ec2:Replace*","ec2:SearchLocalGatewayRoutes","ec2:SearchTransitGatewayRoutes","ec2:ReleaseAddress","ec2:RevokeSecurityGroupEgress","ec2:RevokeSecurityGroupIngress","ec2:TerminateInstances","ec2:UpdateSecurityGroupRuleDescriptionsIngress","ec2:UpdateSecurityGroupRuleDescriptionsEgress"],"Resource":"*","Condition":{"StringEquals":{"ec2:ResourceTag/ManagedBy":"BigAnimal"}}},{"Action":["s3:CreateBucket","s3:DeleteObject","s3:DeleteObjectVersion","s3:DeleteBucket","s3:DeleteBucketPolicy","s3:DescribeJob","s3:Get*","s3:List*","s3:PutBucketAcl","s3:PutBucketOwnershipControls","s3:PutBucketPolicy","s3:PutBucketPublicAccessBlock","s3:PutBucketTagging","s3:PutBucketVersioning","s3:PutLifecycleConfiguration","s3:PutEncryptionConfiguration","s3:PutObject"],"Effect":"Allow","Resource":["arn:aws:s3:::pg-*","arn:aws:s3:::pg-*/*","arn:aws:s3:::tf-state-*","arn:aws:s3:::tf-state-*/*","arn:aws:s3:::logs-bucket-*","arn:aws:s3:::logs-bucket-*/*","arn:aws:s3:::metrics-bucket-*","arn:aws:s3:::metrics-bucket-*/*"]}]}
EOF
)
do_create_iam_policy "biganimal-base-${suffix_policy_name}" "${biganimal_base_policy}"
base_policy_arn=${policy_arn}
biganimal_addon_policy=$(cat <<EOF
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["ec2:AttachInternetGateway","ec2:AuthorizeSecurityGroupEgress","ec2:AuthorizeSecurityGroupIngress","ec2:Delete*","ec2:Detach*","ec2:Disassociate*","ec2:Modify*","ec2:Replace*","ec2:SearchLocalGatewayRoutes","ec2:SearchTransitGatewayRoutes","ec2:ReleaseAddress","ec2:RevokeSecurityGroupEgress","ec2:RevokeSecurityGroupIngress","ec2:TerminateInstances"],"Resource":"*","Condition":{"StringLike":{"ec2:ResourceTag/aws:eks:cluster-name":"dp-##EXTERNAL_ID##-*"}}},{"Action":["eks:DeleteAddon","eks:DeleteCluster","eks:DeleteNodegroup","eks:TagResource","eks:UntagResource","eks:UpdateAddon","eks:UpdateClusterVersion","eks:UpdateNodegroupConfig","eks:UpdateNodegroupVersion","eks:UpdateClusterConfig"],"Effect":"Allow","Resource":["arn:aws:eks:*:*:cluster/dp-##EXTERNAL_ID##-*","arn:aws:eks:*:*:nodegroup/dp-##EXTERNAL_ID##-*/*/*","arn:aws:eks:*:*:addon/dp-##EXTERNAL_ID##-*/*/*"]},{"Action":["iam:AttachRolePolicy","iam:CreatePolicy","iam:CreateRole","iam:DeletePolicy","iam:DeleteRole","iam:DeleteRolePolicy","iam:DetachRolePolicy","iam:PutRolePolicy","iam:TagPolicy","iam:TagRole","iam:UpdateRole","iam:UpdateAssumeRolePolicy"],"Effect":"Allow","Resource":["arn:aws:iam::*:role/ba-##EXTERNAL_ID##-*","arn:aws:iam::*:policy/biganimal-policy-*","arn:aws:iam::*:policy/*##EXTERNAL_ID##*","arn:aws:iam::*:policy/AmazonEKS*"]},{"Action":["iam:PassRole","logs:FilterLogEvents"],"Effect":"Allow","Resource":["arn:aws:iam::*:role/ba-##EXTERNAL_ID##-*","arn:aws:iam::*:role/biganimal-##ROLE_SUFFIX##","arn:aws:logs:*:*:log-group:/ecs/ba-bootstrap:log-stream:"]},{"Action":["ecs:DeleteCluster","ecs:DescribeClusters","ecs:DescribeTasks","ecs:ListTasks","ecs:StopTask","ecs:TagResource"],"Effect":"Allow","Resource":["arn:aws:ecs:*:*:cluster/BigAnimal*","arn:aws:ecs:*:*:task/BigAnimal*"]},{"Action":["ecs:RunTask"],"Effect":"Allow","Resource":["arn:aws:ecs:*:*:task-definition/dp*","arn:aws:ecs:*:*:task-definition/rr*"],"Condition":{"ArnEquals":{"ecs:cluster":"arn:aws:ecs:*:*:cluster/BigAnimal*"}}},{"Action":["iam:CreateOpenIDConnectProvider","iam:DeleteOpenIDConnectProvider","iam:GetOpenIDConnectProvider","iam:TagOpenIDConnectProvider","iam:UntagOpenIDConnectProvider","iam:UpdateOpenIDConnectProviderThumbprint"],"Effect":"Allow","Resource":"arn:aws:iam::*:oidc-provider/oidc.eks.*.amazonaws.com*","Condition":{"StringEquals":{"aws:ResourceTag/ManagedBy":"BigAnimal"}}},{"Action":["kms:CreateGrant","kms:DescribeKey","kms:EnableKeyRotation","kms:GetKeyPolicy","kms:GetKeyRotationStatus","kms:ListResourceTags","kms:ScheduleKeyDeletion","kms:TagResource"],"Effect":"Allow","Resource":["arn:aws:kms:*:*:key/*"],"Condition":{"StringEquals":{"aws:ResourceTag/ManagedBy":"BigAnimal"}}},{"Action":["kms:DeleteAlias","kms:UpdateAlias"],"Effect":"Allow","Resource":["arn:aws:kms:*:*:key/*","arn:aws:kms:*:*:alias/kms-cmk-*","arn:aws:kms:*:*:alias/telemetry-cmk-*"]},{"Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:DeleteLogGroup","logs:DeleteMetricFilter","logs:DescribeMetricFilters","logs:GetLogGroupFields","logs:PutLogEvents","logs:PutMetricFilter","logs:PutRetentionPolicy","logs:TagLogGroup","logs:UntagLogGroup","logs:TagResource","logs:UntagResource","logs:ListTagsForResource"],"Effect":"Allow","Resource":["arn:aws:logs:*:*:log-group:/biganimal/*","arn:aws:logs:*:*:log-group:/biganimal/*:log-stream:*"]},{"Action":["ssm:AddTagsToResource","ssm:DeleteParameters","ssm:GetParameters","ssm:GetParameter","ssm:PutParameter"],"Effect":"Allow","Resource":"arn:aws:ssm:*:*:parameter/BA_*"},{"Action":"secretsmanager:*","Effect":"Allow","Resource":"arn:aws:secretsmanager:*:*:secret:BA*"}]}
EOF
)
biganimal_addon_policy=$(echo ${biganimal_addon_policy//"##EXTERNAL_ID##"/"${external_id}"})
biganimal_addon_policy=$(echo ${biganimal_addon_policy//"##ROLE_SUFFIX##"/"${suffix_role_name}"})
do_create_iam_policy "biganimal-addon-${suffix_policy_name}" "${biganimal_addon_policy}"
addon_policy_arn=${policy_arn}
# IAM Trust Policy
biganimal_trustpolicy=$(cat <<EOF
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole","Principal":{"AWS":"${biganimal_account_id}"},"Condition":{"StringEquals":{"sts:ExternalId":"${external_id}"}}},{"Effect":"Allow","Action":"sts:AssumeRole","Principal":{"Service":"ecs-tasks.amazonaws.com"}}]}
EOF
)
echo "$biganimal_trustpolicy" > "${TMPDIR}"/biganimal_trustpolicy.json
# verify if an IAM role with the same name is already existing
role_exists=$(aws iam list-roles \
--query "length(Roles[*]|[?starts_with(RoleName, \`biganimal-${suffix_role_name}\`) == \`true\`]|[*].Arn)" \
--output json)
if [ "$role_exists" -gt 0 ]; then
# the IAM role already exists, going to update the same
role_arn=$(aws iam list-roles --query "Roles[*]|[?starts_with(RoleName, \`biganimal-${suffix_role_name}\`) == \`true\`]|[*].Arn" \
--output text)
echo -e "Updating AWS IAM role ${GREEN}biganimal-${suffix_role_name}${NC} within AWS account ${GREEN}${account}${NC}..."
aws iam update-assume-role-policy --role-name "biganimal-$suffix_role_name" --policy-document file://"${TMPDIR}"/biganimal_trustpolicy.json \
--output json > "${TMPDIR}"/biganimal_updaterole_output.json
# checking if the existing role is having the policy attached to it
base_policy_attached=$(aws iam list-attached-role-policies --role-name "biganimal-$suffix_role_name" \
--query "length(AttachedPolicies[*]|[?starts_with(PolicyName, \`biganimal-base-${suffix_policy_name}\`) == \`true\`]|[*].PolicyArn)" \
--output json)
if [ "$base_policy_attached" -gt 0 ]; then
# a policy is attached to the role, going to check if it is the correct one
attached_base_policy_arn=$(aws iam list-attached-role-policies --role-name "biganimal-$suffix_role_name" \
--query "AttachedPolicies[*]|[?starts_with(PolicyName, \`biganimal-base-${suffix_policy_name}\`) == \`true\`]|[*].PolicyArn" \
--output text)
if [ "$attached_base_policy_arn" != "$base_policy_arn" ]; then
# the created policy arn is not the same that is attached to the role, going to detach the old attached policy and attach the new one
echo -e "Attaching AWS IAM policy ${GREEN}biganimal-base-${suffix_policy_name}${NC} to role ${GREEN}biganimal-${suffix_role_name}${NC} within AWS account ${GREEN}${account}${NC}..."
aws iam detach-role-policy --policy-arn "$attached_base_policy_arn" --role-name "biganimal-$suffix_role_name"
aws iam attach-role-policy --policy-arn "$base_policy_arn" --role-name "biganimal-$suffix_role_name"
fi
else
# no policy seems attached to this role, going to attach it
echo -e "Attaching AWS IAM policy ${GREEN}biganimal-base-${suffix_policy_name}${NC} to role ${GREEN}biganimal-${suffix_role_name}${NC} within AWS account ${GREEN}${account}${NC}..."
aws iam attach-role-policy --policy-arn "$base_policy_arn" --role-name "biganimal-$suffix_role_name"
fi
addon_policy_attached=$(aws iam list-attached-role-policies --role-name "biganimal-$suffix_role_name" \
--query "length(AttachedPolicies[*]|[?starts_with(PolicyName, \`biganimal-addon-${suffix_policy_name}\`) == \`true\`]|[*].PolicyArn)" \
--output json)
if [ "$addon_policy_attached" -gt 0 ]; then
# a policy is attached to the role, going to check if it is the correct one
attached_addon_policy_arn=$(aws iam list-attached-role-policies --role-name "biganimal-$suffix_role_name" \
--query "AttachedPolicies[*]|[?starts_with(PolicyName, \`biganimal-addon-${suffix_policy_name}\`) == \`true\`]|[*].PolicyArn" \
--output text)
if [ "$attached_addon_policy_arn" != "$addon_policy_arn" ]; then
# the created policy arn is not the same that is attached to the role, going to detach the old attached policy and attach the new one
echo -e "Attaching AWS IAM policy ${GREEN}biganimal-addon-${suffix_policy_name}${NC} to role ${GREEN}biganimal-${suffix_role_name}${NC} within AWS account ${GREEN}${account}${NC}..."
aws iam detach-role-policy --policy-arn "$attached_addon_policy_arn" --role-name "biganimal-$suffix_role_name"
aws iam attach-role-policy --policy-arn "$addon_policy_arn" --role-name "biganimal-$suffix_role_name"
fi
else
# no policy seems attached to this role, going to attach it
echo -e "Attaching AWS IAM policy ${GREEN}biganimal-addon-${suffix_policy_name}${NC} to role ${GREEN}biganimal-${suffix_role_name}${NC} within AWS account ${GREEN}${account}${NC}..."
aws iam attach-role-policy --policy-arn "$addon_policy_arn" --role-name "biganimal-$suffix_role_name"
fi
# checking if the existing role is having the legacy policy attached to it
legacy_policy_attached=$(aws iam list-attached-role-policies --role-name "biganimal-$suffix_role_name" \
--query "length(AttachedPolicies[*]|[?starts_with(PolicyName, \`biganimal-${suffix_policy_name}\`) == \`true\`]|[*].PolicyArn)" \
--output json)
if [ "$legacy_policy_attached" -gt 0 ]; then
# a legacy policy is attached to the role, going to remove it
attached_legacy_policy_arn=$(aws iam list-attached-role-policies --role-name "biganimal-$suffix_role_name" \
--query "AttachedPolicies[*]|[?starts_with(PolicyName, \`biganimal-${suffix_policy_name}\`) == \`true\`]|[*].PolicyArn" \
--output text)
echo -e "Detaching legacy AWS IAM policy ${GREEN}biganimal-${suffix_policy_name}${NC} from role ${GREEN}biganimal-${suffix_role_name}${NC} within AWS account ${GREEN}${account}${NC}..."
aws iam detach-role-policy --policy-arn "$attached_legacy_policy_arn" --role-name "biganimal-$suffix_role_name"
echo -e "Deleting legacy AWS IAM policy ${GREEN}biganimal-${suffix_policy_name}${NC} from role ${GREEN}biganimal-${suffix_role_name}${NC} within AWS account ${GREEN}${account}${NC}..."
older_legacy_policy_versions="$(aws iam list-policy-versions --policy-arn "$attached_legacy_policy_arn" | jq -r '.Versions[] | select(.IsDefaultVersion == false) | .VersionId')"
for policy_version_id in $older_legacy_policy_versions; do
echo -e "Deleting legacy AWS IAM policy ${GREEN}biganimal-${suffix_policy_name}${NC} version ${GREEN}${policy_version_id}${NC}"
aws iam delete-policy-version --policy-arn "$attached_legacy_policy_arn" --version-id "$policy_version_id"
done
aws iam delete-policy --policy-arn "$attached_legacy_policy_arn"
fi
# checking if the existing role is having other policies attached to it, if so they will be detached and deleted
other_policies_attached=$(aws iam list-attached-role-policies --role-name "biganimal-$suffix_role_name" --query "length(AttachedPolicies[*])" --output json)
if [ "$other_policies_attached" -gt 2 ]; then
# other policies are attached to the role, going to remove them
echo -e "Deleting old AWS IAM policies attached to role ${GREEN}biganimal-${suffix_role_name}${NC} within AWS account ${GREEN}${account}${NC}..."
for (( policy_to_remove=other_policies_attached-1; policy_to_remove>=0; policy_to_remove-- )) ; do
attached_policy_arn=$(aws iam list-attached-role-policies --role-name "biganimal-$suffix_role_name" --query "AttachedPolicies[$policy_to_remove].PolicyArn" --output text)
if [[ "${attached_policy_arn}" != *"biganimal-base-${suffix_policy_name}"* ]] && [[ "${attached_policy_arn}" != *"biganimal-addon-${suffix_policy_name}"* ]]; then
aws iam detach-role-policy --policy-arn "$attached_policy_arn" --role-name "biganimal-$suffix_role_name"
older_policy_versions="$(aws iam list-policy-versions --policy-arn "$attached_policy_arn" | jq -r '.Versions[] | select(.IsDefaultVersion == false) | .VersionId')"
for policy_version_id in $older_policy_versions; do
aws iam delete-policy-version --policy-arn "$attached_policy_arn" --version-id "$policy_version_id"
done
aws iam delete-policy --policy-arn "$attached_policy_arn"
fi
done
fi
else
# create IAM role using aws-cli
echo -e "Creating AWS IAM role ${GREEN}biganimal-${suffix_role_name}${NC} within AWS account ${GREEN}${account}${NC}..."
aws iam create-role --role-name "biganimal-$suffix_role_name" --assume-role-policy-document file://"${TMPDIR}"/biganimal_trustpolicy.json \
--output json > "${TMPDIR}"/biganimal_createrole_output.json
role_arn=$(jq -r '.Role.Arn' "${TMPDIR}"/biganimal_createrole_output.json)
# attach IAM policy to the newly created role
echo -e "Attaching AWS IAM policy ${GREEN}biganimal-base-${suffix_policy_name}${NC} to role ${GREEN}biganimal-${suffix_role_name}${NC} within AWS account ${GREEN}${account}${NC}..."
aws iam attach-role-policy --policy-arn "$base_policy_arn" --role-name "biganimal-$suffix_role_name"
echo -e "Attaching AWS IAM policy ${GREEN}biganimal-addon-${suffix_policy_name}${NC} to role ${GREEN}biganimal-${suffix_role_name}${NC} within AWS account ${GREEN}${account}${NC}..."
aws iam attach-role-policy --policy-arn "$addon_policy_arn" --role-name "biganimal-$suffix_role_name"
fi
# add the tag to the IAM role
aws iam tag-role --role-name "biganimal-$suffix_role_name" --tags Key=ManagedBy,Value=BigAnimal
# create ECS, EKS and ELB service linked roles if not exists
set +e
ecs_service_linked_role=$(aws iam get-role --role-name AWSServiceRoleForECS --output json --no-cli-pager 2>/dev/null)
if [ $? -ne 0 ]; then
echo -e "Cannot find the ECS service-linked role, will create one"
ecs_service_linked_role_arn=$(aws iam create-service-linked-role --aws-service-name "ecs.amazonaws.com" --output json --no-cli-pager | jq -r '.Role.Arn')
echo -e "The ECS service-linked role ${GREEN}${ecs_service_linked_role_arn}${NC} within AWS account ${GREEN}${account}${NC} has been created"
else
ecs_service_linked_role_arn=$(echo "$ecs_service_linked_role" | jq -r .'Role.Arn')
echo -e "Found the ECS service-linked role ${ecs_service_linked_role_arn}, there's no need to create it"
fi
eks_service_linked_role=$(aws iam get-role --role-name AWSServiceRoleForAmazonEKS --output json --no-cli-pager 2>/dev/null)
if [ $? -ne 0 ]; then
echo -e "Cannot find the EKS service-linked role, will create one"
eks_service_linked_role_arn=$(aws iam create-service-linked-role --aws-service-name "eks.amazonaws.com" --output json --no-cli-pager | jq -r '.Role.Arn')
echo -e "The EKS service-linked role ${GREEN}${eks_service_linked_role_arn}${NC} within AWS account ${GREEN}${account}${NC} has been created"
else
eks_service_linked_role_arn=$(echo "$eks_service_linked_role" | jq -r .'Role.Arn')
echo -e "Found the EKS service-linked role ${eks_service_linked_role_arn}, there's no need to create it"
fi
eks_ng_service_linked_role=$(aws iam get-role --role-name AWSServiceRoleForAmazonEKSNodegroup --output json --no-cli-pager 2>/dev/null)
if [ $? -ne 0 ]; then
echo -e "Cannot find the EKS NodeGroup service-linked role, will create one"
eks_ng_service_linked_role_arn=$(aws iam create-service-linked-role --aws-service-name "eks-nodegroup.amazonaws.com" --output json --no-cli-pager | jq -r '.Role.Arn')
echo -e "The EKS NodeGroup service-linked role ${GREEN}${eks_ng_service_linked_role_arn}${NC} within AWS account ${GREEN}${account}${NC} has been created"
else
eks_ng_service_linked_role_arn=$(echo "$eks_ng_service_linked_role" | jq -r .'Role.Arn')
echo -e "Found the EKS NodeGroup service-linked role ${eks_ng_service_linked_role_arn}, there's no need to create it"
fi
elb_service_linked_role=$(aws iam get-role --role-name AWSServiceRoleForElasticLoadBalancing --output json --no-cli-pager 2>/dev/null)
if [ $? -ne 0 ]; then
echo -e "Cannot find the ELB service-linked role, will create one"
elb_service_linked_role_arn=$(aws iam create-service-linked-role --aws-service-name "elasticloadbalancing.amazonaws.com" --output json --no-cli-pager | jq -r '.Role.Arn')
echo -e "The ELB service-linked role ${GREEN}${elb_service_linked_role_arn}${NC} within AWS account ${GREEN}${account}${NC} has been created"
else
elb_service_linked_role_arn=$(echo "$elb_service_linked_role" | jq -r .'Role.Arn')
echo -e "Found the ELB service-linked role ${elb_service_linked_role_arn}, there's no need to create it"
fi
set -e
}
increase_quotas()
{
if [[ "$increase_quota" == "true" ]]; then
if [[ "${region}" == "" ]]; then
region=$(aws configure get region)
fi
# Create AWS support tickets to increase the needed quotas
for quota_code in "${!quota_increases[@]}"; do
for service_code in "${aws_used_service_quota_codes[@]}"; do
quotas=$(aws service-quotas list-service-quotas --service-code "$service_code" --query "Quotas[*].QuotaCode" --output text)
if [[ $quotas == *"$quota_code"* ]]; then
aws service-quotas request-service-quota-increase --service-code "$service_code" --quota-code "$quota_code" \
--desired-value "${quota_increases["$quota_code"]}" --region "$region" > "${TMPDIR}"/biganimal_quotaincrease_output.json
quota_name=$(jq -r '.RequestedQuota.QuotaName' "${TMPDIR}"/biganimal_quotaincrease_output.json)
quota_names["$quota_code"]=$quota_name
fi
done
done
fi
}
save_result()
{
echo ""
echo "######################################################"
echo -e "# Script Results running on AWS account ${GREEN}${account}${NC} #"
echo "######################################################"
echo ""
echo -e "Created AWS IAM policy ${GREEN}biganimal-base-${suffix_policy_name}${NC} ARN is: ${GREEN}${base_policy_arn}${NC}"
echo -e "Created AWS IAM policy ${GREEN}biganimal-addon-${suffix_policy_name}${NC} ARN is: ${GREEN}${addon_policy_arn}${NC}"
echo -e "Created AWS IAM role ${GREEN}biganimal-${suffix_role_name}${NC} ARN is: ${GREEN}${role_arn}${NC}"
if [[ "$increase_quota" == "true" ]]; then
for quota_code in "${!quota_increases[@]}"; do
echo -e "Requested AWS Service quota increase for ${GREEN}${quota_names["$quota_code"]}${NC}, quota requested is: ${GREEN}${quota_increases["$quota_code"]}${NC}"
done
echo -e "You can check your ${GREEN}Quota request history${NC} on the AWS Console here:"
echo -e "${GREEN}https://${region}.console.aws.amazon.com/servicequotas/home/requests?region=${region}#${NC}"
fi
# exporting JSON "ba-passport.json" that will be used by BigAnimal CLI
echo "{\"biganimal-${suffix_role_name}\":\"${role_arn}\",\"roleName\":\"biganimal-${suffix_role_name}\",\"roleArn\":\"${role_arn}\",\"externalID\":\"${external_id}\"}" > "$CURRENT_PATH"/ba-passport.json
}
check
create_iam_role
increase_quotas
save_result