Skip to content

Instantly share code, notes, and snippets.

@unfor19
Created March 16, 2021 15:13
Show Gist options
  • Save unfor19/7e44727eb59073bcc8c4fe07b5eda572 to your computer and use it in GitHub Desktop.
Save unfor19/7e44727eb59073bcc8c4fe07b5eda572 to your computer and use it in GitHub Desktop.
aws-run-instance with conditions
#!/bin/bash
set -e
set -o pipefail
error_msg(){
local msg=$1
echo -e "$(date) :: [ERROR] ${msg}"
exit 1
}
# Requirements
# Create a new EC2 Keypair - MyKeyPair @ Ohio us-east-2
# Create a new IAM policy, attach the permission `decode-message-string`
# {
# "Version": "2012-10-17",
# "Statement": [
# {
# "Sid": "VisualEditor0",
# "Effect": "Allow",
# "Action": "sts:DecodeAuthorizationMessage",
# "Resource": "*"
# }
# ]
# }
# Create a new IAM policy test-iam-policy-tags - https://aws.amazon.com/premiumsupport/knowledge-center/iam-policy-tags-restrict/
# Create an IAM user and directly attach the created IAM policies, save the credentials
# Usage
# Use the credentials and run the script
# $ export AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=...
# $ bash ./aws-run-instance.sh $SG_ID $SUBNET_ID
# IAM Policy restriction:
#
# "Sid": "AllowRunInstancesWithRestrictions",
# "Effect": "Allow",
# "Action": [
# "ec2:CreateVolume",
# "ec2:RunInstances"
# ],
# "Resource": [
# "arn:aws:ec2:*:*:volume/*",
# "arn:aws:ec2:*:*:instance/*"
# ],
# "Condition": {
# "StringEquals": {
# "aws:RequestTag/key1": "value1",
# "aws:RequestTag/key2": "value2"
# },
# "ForAllValues:StringEquals": {
# "aws:TagKeys": [
# "key1",
# "key2"
# ]
# }
### Set tags list according to the IAM policy -----------------
_TAGS_LIST="[{Key=key1,Value=value1},{Key=key2,Value=value2}]"
### -----------------------------------------------------------
_AWS_REGION="${AWS_REGION:-"us-east-2"}" # Default: Ohio
_SG_ID="${1:-$SG_ID}"
_SUBNET_ID="${2:-$SUBNET_ID}"
[[ -z $_SG_ID ]] && error_msg "Set SG_ID env var or pass as first arg"
[[ -z $_SUBNET_ID ]] && error_msg "Set SUBNET_ID env var or pass as second arg"
_AMI_ID="ami-07a0844029df33d7d" # Amazon Linux 2 @ Ohio
_INSTANCE_COUNT=1
_INSTANCE_TYPE="t2.micro"
_KEYPAIR_NAME="${KEYPAIR_NAME:-MyKeyPair}"
response="$(aws ec2 run-instances \
--region "$_AWS_REGION" \
--image-id "$_AMI_ID" \
--count "$_INSTANCE_COUNT" \
--instance-type "$_INSTANCE_TYPE" \
--key-name "$_KEYPAIR_NAME" \
--security-group-ids "$_SG_ID" \
--subnet-id "$_SUBNET_ID" \
--tag-specifications \
ResourceType=volume,Tags="$_TAGS_LIST" \
ResourceType=instance,Tags="$_TAGS_LIST" \
2>&1 || true)"
if [[ "$response" =~ .*UnauthorizedOperation.* ]]; then
# requires jq - decodes the error message
encoded_message="$(echo "$response" | cut -f3 -d : | cut -c2-)"
aws sts decode-authorization-message --encoded-message "$encoded_message" --query DecodedMessage --output text | jq '.'
else
echo "$response"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment