Skip to content

Commit

Permalink
Add script to check for security update of given ami
Browse files Browse the repository at this point in the history
  • Loading branch information
hozkaya2000 committed Nov 14, 2023
1 parent ec89cce commit 98e6ea7
Showing 1 changed file with 76 additions and 0 deletions.
76 changes: 76 additions & 0 deletions check-update-security.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#!/usr/bin/env bash

set -eio pipefail

usage() {
echo "Usage:"
echo " $0 AMI_ID"
echo "Example:"
echo " $0 ami-0abc1d2ef34ghij56"
}

error_msg() {
local msg="$1"
echo "ERROR: $msg"
}

#in case of failure, terminate instance
failure_cleanup() {
terminate_out=$(aws ec2 terminate-instances --instance-ids $instance_id)
}

ami_id=$1
if [ -z "$ami_id" ]; then
error_msg "Must give an ami id"
usage
exit 1
fi
if [ -z "$IAM_INSTANCE_PROFILE_ARN" ]; then
error_msg "IAM_INSTANCE_PROFILE_ARN environment variable must exist"
exit 1
fi

#Launch ec2 instance with given ami and SSM access for command execution
#Also get instance id
instance_id=$(aws ec2 run-instances \
--image-id $ami_id \
--instance-type t2.micro \
--iam-instance-profile Arn=$IAM_INSTANCE_PROFILE_ARN \
| jq -r '.Instances[0].InstanceId')

#wait for instance to launch
aws ec2 wait instance-running --instance-ids $instance_id

#If instance got launched, terminate in case of an error
trap 'failure_cleanup' ERR

#Send command
cmd_id=$(aws ssm send-command \
--document-name 'AWS-RunShellScript' \
--parameters 'commands=["yum check-update --sec-severity=CRITICAL -q","echo $?"]' \
--targets Key=instanceids,Values=$instance_id \
--comment "run security check" \
| jq -r '.Command.CommandId')


#Wait for command to be executed
aws ssm wait command-executed --command-id $cmd_id --instance-id $instance_id

#Get command output
cmd_response_code=$(aws ssm get-command-invocation \
--command-id $cmd_id \
--instance-id $instance_id \
| jq -r '.ResponseCode')


#Delete the instance
terminate_out=$(aws ec2 terminate-instances --instance-ids $instance_id)

#Return whether update is necessary
if [ "$cmd_response_code" -eq "100" ]; then
echo "true"
else
echo "false"
fi

exit 0

0 comments on commit 98e6ea7

Please sign in to comment.