-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add script to check for security update of given ami
- Loading branch information
1 parent
ec89cce
commit f9640e9
Showing
1 changed file
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
#!/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 |