简体   繁体   中英

SSH into EC2 by using a zsh script to fetch EC2 IP Address

I'd like to create an alias in my zprofile that will fetch the EC2 IP address based on name tags, and then SSH into that machine. I'm using a mac.

This zsh script successfully retrieves the IP address of the EC2 machine I want to ssh into:

aws ec2 describe-instances \
--filters "Name=tag:Name, Values=my-name" \
--query "Reservations[*].Instances[*].[PrivateIpAddress]" \
--output text

The output might look like: some.ip.address

This zsh script lets me SSH into my EC2 machine:

alias ec2="ssh person@some.ip.address.us-east-1.place"

How do I substitute the IP address of the second script with the output of my first script?

Thanks!

Probably the easiest way to do this would be to set up a second alias, so you could have something like:

alias get_ec2_ip='aws ec2 describe-instances --filters "Name=tag:Name, Values=my-name" --query "Reservations[*].Instances[*].[PrivateIpAddress]" --output text'

And then you could use zsh's command substitution , like so:

alias ec2='ssh person@`get_ec2_ip`'

Note that it's super important to use single quotes there, not double quotes, Otherwise, you'll run get_ec2_ip when setting the alias, which is not what you want—you want it to save the literal string ssh person@`get_ec2_ip` as the alias, so that get_ec2_ip is run every time you run ec2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM