Last Updated: May 13, 2019
·
542
· Curio

EC2 Completion using AWS CLI, fzf, and zsh

Use of HEREDOCs (EOF) here means that this needs to live in a tab-indented file.

_aws_profiles() {
    sed -n -e 's#\[profile \(.*\)\]#\1#p' ~/.aws/config;
}

ec2_hosts() {
    (
        for p in $(_aws_profiles); do
            aws ec2 --profile "$p" \
                            describe-instances \
                            --filters 'Name=instance-state-name,Values=running' \
                            --query "$(cat <<-EOF | tr -d '\n' | tr -d ' '
                                    Reservations[*].{
                                        account:OwnerId,
                                        deets:Instances[*].[
                                            (not_null(Tags[?Key==\`Name\`][].Value)[0]||\`_\`),
                                            InstanceId,
                                            PrivateDnsName,
                                            VpcId,
                                            SubnetId,
                                            (not_null(PublicDnsName)||\`_\`),
                                            (not_null(Tags[?Key==\`Client\`][].Value)[0]||\`_\`)
                                        ][]
                                    }
                                EOF
                                )" \
                            --output json \
                                | jq -r '.[]|[.account] + .deets|join(",")' &
        done
        wait
    ) \
        | sort -u
}

ec2() {
    # should match list of tags above
    echo -e "$(cat <<-EOF  | tr -d '\n' | sed -e 's#\ \{2,\}##g'
        Account,
        Name tag,
        Instance ID,
        Private DNS,
        VPC,
        Subnet,
        Public DNS,
        Client tag
    EOF
    )\n$(ec2_hosts)" \
        | column -t -s ',' \
            | fzf --header-lines 1
}