Last active
July 22, 2016 06:45
-
-
Save nobu666/f43ee05d83d8e01c695cf491790c0feb to your computer and use it in GitHub Desktop.
Sync AWS IAM Users and server users
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
#!/bin/bash | |
function create_authorized_keys() | |
{ | |
if [ $dry_run -eq 1 ]; then | |
echo "mkdir -p /home/$1/.ssh" | |
echo "chown $1:$3 /home/$1/.ssh" | |
echo "chmod 700 /home/$1/.ssh" | |
echo "echo \"$2\" >> /home/$1/.ssh/authorized_keys" | |
echo "chown $1:$3 /home/$1/.ssh/authorized_keys" | |
echo "chmod 600 /home/$1/.ssh/authorized_keys" | |
else | |
mkdir -p /home/$1/.ssh | |
chown $1:$3 /home/$1/.ssh | |
chmod 700 /home/$1/.ssh | |
echo "$2" >> /home/$1/.ssh/authorized_keys | |
chown $1:$3 /home/$1/.ssh/authorized_keys | |
chmod 600 /home/$1/.ssh/authorized_keys | |
fi | |
} | |
function create_user() | |
{ | |
if [ $dry_run -eq 1 ]; then | |
echo "useradd -g $3 $1" | |
else | |
useradd -g $3 $1 | |
fi | |
create_authorized_keys $1 "$2" $3 | |
} | |
dry_run=0 | |
force=0 | |
for opt in "$@"; do | |
case "$opt" in | |
'--dry-run' ) | |
dry_run=1 | |
shift 1 | |
;; | |
esac | |
done | |
if [ $dry_run -eq 1 ]; then | |
echo "This is dry run mode" | |
fi | |
for user in $(aws iam list-users | jq -r ".Users | sort_by(.CreateDate) | .[].UserName"); do | |
for keyid in $(aws iam list-ssh-public-keys --user-name $user | jq -r ".SSHPublicKeys[].SSHPublicKeyId"); do | |
if [ "$keyid" = "" ]; then | |
continue | |
fi | |
res=$(aws iam get-ssh-public-key --encoding SSH --user-name $user --ssh-public-key-id $keyid | jq ".SSHPublicKey") | |
if [ $(echo $res | jq -r ".Status") != "Active" ]; then | |
if id $user > /dev/null 2>&1; then | |
echo "[WARN] $user's SSH key has not active in IAM, but account is exists in this host" 1>&2 | |
fi | |
continue | |
fi | |
key=$(echo $res | jq -r ".SSHPublicKeyBody") | |
group="users" | |
if aws iam list-groups-for-user --user $user | jq -r ".Groups[].GroupName" | grep -q Developers; then | |
group="wheel" | |
fi | |
if id $user > /dev/null 2>&1; then | |
if ! grep -q "$key" /home/$user/.ssh/authorized_keys; then | |
create_authorized_keys $user "$key" $group | |
fi | |
else | |
create_user $user "$key" $group | |
fi | |
done | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment