#!/bin/bash
# List of AWS profiles
profiles=("profile1" "profile2" "profile3" "profile4")
# Iterate through each AWS profile
for profile in "${profiles[@]}"; do
echo "Executing commands with AWS profile: $profile"
# Set the AWS profile for the current iteration
export AWS_PROFILE="$profile"
# Step 0: Get all regions in the AWS account.
for region_name in $(aws ec2 describe-regions --query "Regions[].{Name:RegionName}" --output text); do
echo "Checking the region: $region_name"
# Step 1: Get List of Instances in the Region
instances_info=$(aws ec2 describe-instances --region "$region_name" --query 'Reservations[].Instances[].[InstanceId, Tags[?Key==`Name`].Value | [0]]' --output text)
# Step 2: Loop Through Instances
IFS=$'\n'
for instance in $(echo "${instances_info}"); do
instance_id=$(echo "${instance}" | awk '{print $1}')
instance_name=$(echo "${instance}" | awk '{print $2}')
# Step 3: Check Patch Compliance and update status
cstatus=$(aws ssm list-compliance-items --resource-id "${instance_id}" --region "$region_name" | awk 'NR > 1 {print}')
if [[ "$cstatus" != *"COMPLIANT"* && "$cstatus" != *"NON_COMPLIANT"* ]]; then
cstatus="NOT REPORTED"
elif [[ "$cstatus" == *"NON_COMPLIANT"* ]]; then
# Step 4: Check patch non-compliance count
ncpcount=$(echo -e "$cstatus" | grep -i NON_COMPLIANT | wc -l)
cstatus="NON_COMPLIANT"
elif [[ "$cstatus" == *"COMPLIANT"* && "$cstatus" != *"NON_COMPLIANT"* ]]; then
cstatus="COMPLIANT"
elif [ -z "$cstatus" ]; then
cstatus="CHECK FAILED"
else
cstatus="UNKNOWN"
fi
# Step 5: Store Information in CSV File
echo "${instance_id},${instance_name},${region_name},${cstatus},${ncpcount:-0}" >> compliance_info.csv
unset cstatus
unset ncpcount
done
done
echo "+++++++++++++ Completed on the AWS Account: $profile +++++++++++++++++++++++++++++"
done
Comments
Post a Comment