Reputation: 85
I want to create a script that can load and access the ec2 list using bash.
#!/bin/bash
profilelist=`cat ~/.aws/config | grep '\[profile' | cut -f 1 -d']' | cut -f 2 -d' '`
user=`logname`
PS3='select aws account: '
select profile in $profilelist
do
ec2list=`aws ec2 describe-instances --filter "Name=tag:stage,Values=live" "Name=instance-state-name,Values=running" --query "Reservations[].Instances[].[Tags[?Key=='Name'].Value|[0] , PrivateIpAddress]" --profile $profile --output text`
PS3='select endpoint: '
select item in $ec2list
do
ssh $user@$item -p22
break
done
break
done
result
sh test2.sh
1) account1
2) account2
3) account3
4) account4
select aws account: 3
1) ec2host-lv001 5) ec2host-lv003
2) 10.1.30.1 6) 10.1.30.3
3) ec2host-lv002 7) ec2host-lv004
4) 10.1.30.2 8) 10.1.30.4
sh test2.sh
1) account1
2) account2
3) account3
4) account4
select aws account: 3
1) ec2host-lv001 10.1.30.1
2) ec2host-lv002 10.1.30.2
3) ec2host-lv003 10.1.30.3
4) ec2host-lv004 10.1.30.4
How can I get hostname and ip into the same line?
Perhaps select accepts spacing as a different option
Upvotes: 0
Views: 57
Reputation: 69218
As you have spaces in your list you need a different separator, use something like this to use newlines
IFS=$'\n'
select item in $ec2list
do
ssh $user@$item -p22
break
done
...
you may need to save IFS
to be restored later if this is not the end of your script.
Also, an array might be better and add some missing quotes. Use https://www.shellcheck.net/.
According to your comment, if you are going to replace the tab, this would be more efficient
ec2list=${ec2list//$'\t'/:}
and then
${item#*:}
to cut the ip.
Upvotes: 1