Skip to content

Instantly share code, notes, and snippets.

@nivogt
Last active January 3, 2022 09:44
Show Gist options
  • Save nivogt/e81a15e4a63c57dad2296bbc968a7552 to your computer and use it in GitHub Desktop.
Save nivogt/e81a15e4a63c57dad2296bbc968a7552 to your computer and use it in GitHub Desktop.
Generate iam permission from terraform trace
#!/bin/bash
INPUT_FILE=*.log
OUTPUT_FILE=policy.json
# get statements
# group all permissions by group into one statement block
# eg. ec2:CreateInstance and ec2:DeleteInstance will be in the same statement
STATEMENTS=$(grep "DEBUG: Request" $INPUT_FILE |awk '{print $(NF-1)}' | awk -F "/" '{print $1}' | sort | uniq )
LAST_STATEMENT=$(echo $STATEMENTS | awk '{print $NF}')
# empty output file
echo > $OUTPUT_FILE
# start writing headers
echo -e "{" >> $OUTPUT_FILE
echo -e "\t\"Version\": \"$(date +"%Y-%m-%d")\"," >> $OUTPUT_FILE
echo -e "\t\"Statement\": [" >> $OUTPUT_FILE
# iterate over statements
for i in STATEMENTS;
do
# retrieve all permissions
PERMISSIONS=$(grep "DEBUG: Request" $INPUT_FILE |awk '{print $(NF-1)'} | grep $i | awk -F "/" '{print $2}' |sort | uniq )
# need the last permission in order to end the statement properly
LAST_PERMISSION=$(echo $PERMISSIONS | awk '{print $NF}')
echo -e "\t\t{" >> $OUTPUT_FILE
echo -e "\t\t\t\"Action\": [" >> $OUTPUT_FILE
# iterate over the permissions
for j in $PERMISSIONS;
do
if [ "$j" == "$LAST_PERMISSION" ];
then
echo -e "\t\t\t\t\"${i}:${j}\"" >> $OUTPUT_FILE
else
echo -e "\t\t\t\t\"${i}:${j}\"," >> $OUTPUT_FILE
fi
done;
# effect -> allow
# resource -> *
echo -e "\t\t\t]," >> $OUTPUT_FILE
echo -e "\t\t\t\"Effect\": \"Allow\"," >> $OUTPUT_FILE
echo -e "\t\t\t\"Resource\": \"*\"" >> $OUTPUT_FILE
# add a comma until the last statement
if [ "$i" == "$LAST_STATEMENT" ];
then
echo -e "\t\t}" >> $OUTPUT_FILE
else
echo -e "\t\t}," >> $OUTPUT_FILE
fi
done
# footer
echo -e "\t]" >> $OUTPUT_FILE echo -e "}" >> $OUTPUT_FILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment