Skip to content

Instantly share code, notes, and snippets.

@hartfordfive
Created December 11, 2015 12:23
Show Gist options
  • Select an option

  • Save hartfordfive/1ada66605a7fa870faff to your computer and use it in GitHub Desktop.

Select an option

Save hartfordfive/1ada66605a7fa870faff to your computer and use it in GitHub Desktop.
PHP script to connect to all EC2 instances in an auto-scaling group on a Mac
#!/usr/bin/php
<?php
/****************************************
Requirements:
- Python 2.7+
- aws-cli
- osascript
*****************************************/
$sshKey = "~/.ssh/id_rsa";
$sshUser = getenv('USER'); // Get the user from your environment variables
$autoScalingGroups = $argv[1]; // A blob pattern of the auto scalling group name to match
$userPrivateIp = true; // Use the VPC private IP to connect?
$profile = getenv('AWS_PROFILE');
$cmd = "aws --profile $profile ec2 describe-instances --filter \"Name=instance-state-name,Values=running\" \"Name=tag-key,Values=aws:autoscaling:groupName\" \"Name=tag-value,Values=$autoScalingGroups\"";
echo "Running: $cmd\n";
$instances = json_decode(`$cmd`, true);
$count = 0;
$ascript_body = "";
foreach($instances['Reservations'] as $instance) {
$count++;
$ip = $userPrivateIp ? $instance['Instances'][0]['PrivateIpAddress'] : $instance['Instances'][0]['PublicIpAddress'];
$name = "";
foreach($instance['Instances'][0]['Tags'] as $id => $tag_details) {
if ($tag_details['Key'] == "Name") {
$name = $tag_details['Value'];
break 1;
}
}
echo "Openning ssh to $ip (Name: $name)\n";
$ascript_body = $ascript_body."
launch session \"Default Session\"
tell the last session
set name to \"$name\"
write text \"ssh $sshUser@$ip -i $sshKey\"
write text \"sudo su -\"
do shell script \"/bin/sleep 0.01\"
end tell\n
";
}
passthru(
"/usr/bin/osascript <<-EOF
set curr_tab to 1
tell application \"iTerm\"
set myterm to (make new terminal)
tell myterm
$ascript_body
end tell
end tell
EOF
"
);
echo "---------------------------------------\n";
echo "Connected to $count instances\n";
echo "---------------------------------------\n\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment