Skip to content

Instantly share code, notes, and snippets.

@5HARK
Last active March 17, 2024 10:47
Show Gist options
  • Save 5HARK/453bdb8293be63d5f744bb22d9138f97 to your computer and use it in GitHub Desktop.
Save 5HARK/453bdb8293be63d5f744bb22d9138f97 to your computer and use it in GitHub Desktop.
Shell script: Connect to EC2 instances of Auto scaling Group and simultaneous control
#!/usr/bin/env bash
# ssh-as-group.sh
# AWS EC2 오토스케일 그룹의 모든 EC2 인스턴스에 SSH 연결 및 동시 제어하는 스크립트
# Requirements: awscli, tmux, tmux-xpanes
# 인자 검증
if [ $# -lt 4 ]; then
echo "오류: 인자가 필요합니다."
echo "사용법: $0 AutoscaleGroupName SSHPublicKeyPath SSHPortNumber EC2LoginUserName"
exit 1
fi
output_file=$(mktemp) # 임시 파일 생성
# Auto Scaling 그룹의 인스턴스 ID 목록을 가져오고, 각 인스턴스에 대해 병렬로 조회
while read line; do
(
aws ec2 describe-instances --output text --instance-id "$line" --query 'Reservations[*].Instances[*].[PublicDnsName]' >> "$output_file"
) &
done < <(aws autoscaling describe-auto-scaling-instances --query "AutoScalingInstances[?AutoScalingGroupName==\`$1\`].[InstanceId]" --output text)
wait # 모든 백그라운드 프로세스가 완료될 때까지 기다림
# 개행문자를 공백으로 변경
tr '\n' ' ' < $output_file
# xpanes 실행
hosts=$(cat "$output_file")
xpanes -c "ssh -i $2 -p $3 $4@{}" $hosts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment