|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +function _substitute_environment_variables() { |
| 4 | + eval "cat << EOF |
| 5 | +$(cat $1) |
| 6 | +EOF" |
| 7 | +} |
| 8 | + |
| 9 | +AWS_REGION_NAME="eu-west-2" |
| 10 | + |
| 11 | +ACCOUNT_ID=$(aws sts get-caller-identity | jq -r .Account) |
| 12 | + |
| 13 | +# |
| 14 | +# Check we're running this against MGMT |
| 15 | +# |
| 16 | +. "./scripts/aws/helpers.sh" |
| 17 | +if ! _validate_current_account "MGMT"; then |
| 18 | + echo "Please login to mgmt profile before running this script" |
| 19 | + exit 1 |
| 20 | +fi |
| 21 | + |
| 22 | +# |
| 23 | +# Create the NHSDevelopmentPolicy that will be used for Developer access and |
| 24 | +# NHSDevelopmentRole. This policy is split into 2 as the file size was too large. |
| 25 | +# |
| 26 | + |
| 27 | +policy_name="NHSSupportPolicy" |
| 28 | + |
| 29 | +for policy_number in "1" "2"; do |
| 30 | + tf_policy=$(_substitute_environment_variables ./scripts/infrastructure/policies/support${policy_number}-policy.json) |
| 31 | + aws iam get-policy --policy-arn "arn:aws:iam::${ACCOUNT_ID}:policy/${policy_name}${policy_number}" &>/dev/null |
| 32 | + if [ $? != 0 ]; then |
| 33 | + aws iam create-policy \ |
| 34 | + --policy-name "${policy_name}${policy_number}" \ |
| 35 | + --policy-document "${tf_policy}" \ |
| 36 | + --region "${AWS_REGION_NAME}" || |
| 37 | + exit 1 |
| 38 | + fi |
| 39 | + # We update the version because this updates all roles and we don't have to detach and delete. |
| 40 | + versions=$(aws iam list-policy-versions --policy-arn "arn:aws:iam::${ACCOUNT_ID}:policy/${policy_name}${policy_number}" --region "${AWS_REGION_NAME}") |
| 41 | + num_versions=$(echo "$versions" | jq -r '.Versions | length') |
| 42 | + # There has got to be at least 2 versions. |
| 43 | + if [ "$num_versions" -ge 2 ]; then |
| 44 | + # Extract the oldest version using jq |
| 45 | + oldest_version=$(echo "$versions" | jq -r '.Versions | sort_by(.CreateDate) | .[0].VersionId') |
| 46 | + |
| 47 | + aws iam delete-policy-version \ |
| 48 | + --policy-arn "arn:aws:iam::${ACCOUNT_ID}:policy/${policy_name}${policy_number}" \ |
| 49 | + --version-id "${oldest_version}" || |
| 50 | + exit 1 |
| 51 | + fi |
| 52 | + |
| 53 | + aws iam create-policy-version \ |
| 54 | + --policy-arn "arn:aws:iam::${ACCOUNT_ID}:policy/${policy_name}${policy_number}" \ |
| 55 | + --policy-document "${tf_policy}" \ |
| 56 | + --set-as-default \ |
| 57 | + --region "${AWS_REGION_NAME}" || |
| 58 | + exit 1 |
| 59 | +done |
0 commit comments