Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Manage an AWS profile instance given environment variables
# Given environment variables of INSTANCE_PROFILE and INSTANCE_ROLE, this will create the profile,
# swap out the role, remove the role, add the role to make sure at the end, INSTANCE_PROFILE contains
# one and only one role, INSTANCE_ROLE
if aws iam get-instance-profile --instance-profile-name "${INSTANCE_PROFILE}" ; then
echo "Profile already exists. Checking instance profile..."
OLD_ROLE="$(aws iam get-instance-profile --instance-profile-name $INSTANCE_PROFILE | ./jq.dms -r '.InstanceProfile.Roles[0].RoleName')"
if [ "${OLD_ROLE}" = "null" ] || [ -z "${OLD_ROLE}" ] ; then
OLD_ROLE=none
fi
if [ "${INSTANCE_ROLE}" = "${OLD_ROLE}" ] ; then
echo "No change to instance profile needed."
else
echo "Profile has wrong role - ${OLD_ROLE}. Removing role..."
if [ "${OLD_ROLE}" = "none" ] || aws iam remove-role-from-instance-profile --role-name "${OLD_ROLE}" --instance-profile-name "${INSTANCE_PROFILE}" ; then
echo "Role removed!"
fi
if [ "${INSTANCE_ROLE}" != "none" ] ; then
echo "Adding role to profile..."
if aws iam add-role-to-instance-profile --role-name "${INSTANCE_ROLE}" --instance-profile-name "${INSTANCE_PROFILE}" ; then
echo "Role added!"
fi
fi
fi
else
echo "Profile doesn't exist - creating profile..."
if aws iam create-instance-profile --instance-profile-name "${INSTANCE_PROFILE}" ; then
echo "Created!"
fi
if [ "${INSTANCE_ROLE}" != "none" ] ; then
echo "Adding role to profile..."
if aws iam add-role-to-instance-profile --role-name "${INSTANCE_ROLE}" --instance-profile-name "${INSTANCE_PROFILE}" ; then
echo "Role added!"
fi
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment