ZSH

AWS ZSH Helper

This morning I’m going to go with a new recurring weekly post: Friday Functions! While some of it will aim to share my large inventory of zsh functions I’ve acquired over the years I’ll also be finding new additions if I run out of material. So it also serves to help me learn more!

This week’s function is probably only useful if you’re into AWS and use the awscli tool to interact with it from the command line. Using the awscli command direction can be quite verbose so some nice shortcuts are useful. I actually learned of this handy function from Kris’s awesome collection of zsh configuration and made a few small adaptions to it.

function aws-instances-describe() {
    zparseopts -D -E -A opts -- o: t: s:
    output=${opts[-o]:-"table"}
    tag_name=${opts[-t]:-"Name"}
    state=${opts[-s]:-"running"}

    name=${1}
    query=(
        "Reservations[].Instances[]"
        ".{"
        "Name             : Tags[?Key == \`Name\`].Value | [0],"
        "State            : State.Name,"
        "LaunchTime       : LaunchTime,"
        "InstanceId       : InstanceId,"
        "PrivateIpAddress : PrivateIpAddress,"
        "PublicIpAddress  : PublicIpAddress,"
        "ImageId          : ImageId,"
        "InstanceType     : InstanceType"
        "}"
    )

    aws --output ${output} \
        ec2 describe-instances \
        --filters "Name=tag:${tag_name},Values=*${name}*" "Name=instance-state-name,Values=${state}" \
        --query "${query}"
}

This is pretty useful. If you want to find all instances with http in the name you just run aws-instances-describe http.

Screen-Shot-2016-03-31-at-6.14.42-PM

Or if you want to look for instances by a specific tag you can use the `-t` switch. For example, to find all instances with the worker_email role tag we can just run aws-instance-describe -t role worker_email. You can add -s to changed the filter to include the running state and like the actual call you can include multiple instances. So if you wanted to find all stopped instances with thetaskhistory role you’d run aws-instance-describe -t role taskhistory -s stopped. The function sets this to default to running instances only since that’s what I’m looking for 99% of the time… looking for stopped or terminated instances is definitely the exception.

Hope this was interesting enough. Ideas, thoughts, comments or criticism are all welcome in the comments below! Let me know what you think!

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button