从附加实例获取 AWS ELB 名称

Nam*_*yen 4 load-balancing amazon-ec2 amazon-web-services amazon-elb

我创建了一个 ELB 并将一些实例附加到这个 ELB。因此,当我登录到这些附加实例之一时,我想键入一个命令或运行一个 nodejs 脚本,该脚本可以返回其 ELB 名称。是否可以?我知道我可以在 AWS 控制台上查找,但我正在寻找一种以编程方式查找的方法。如果可能,我想看看它是如何在命令或 AWS Nodejs SDK 中完成的。

谢谢!

小智 7

如果有人来这里寻找纯 bash 解决方案。

使用jq过滤和解析 AWS CLI 的响应:

aws elb describe-load-balancers | jq -r '.LoadBalancerDescriptions[] | select(.Instances[].InstanceId == "<YOUR-INSTANCE-ID>") | .LoadBalancerName ' 
Run Code Online (Sandbox Code Playgroud)

同样在 aws-codedeploy-samples 中,他们在common_functions.sh 中定义了这个函数。我没有在使用 ASG 时对其进行测试,但我想它会起作用

# Usage: get_elb_list <EC2 instance ID>
#
#   Finds all the ELBs that this instance is registered to. After execution, the variable
#   "INSTANCE_ELBS" will contain the list of load balancers for the given instance.
#
#   If the given instance ID isn't found registered to any ELBs, the function returns non-zero
get_elb_list() {
    local instance_id=$1

    local elb_list=""

    local all_balancers=$($AWS_CLI elb describe-load-balancers \
        --query LoadBalancerDescriptions[*].LoadBalancerName \
        --output text | sed -e $'s/\t/ /g')

    for elb in $all_balancers; do
        local instance_health
        instance_health=$(get_instance_health_elb $instance_id $elb)
        if [ $? == 0 ]; then
            elb_list="$elb_list $elb"
        fi
    done

    if [ -z "$elb_list" ]; then
        return 1
    else 
        msg "Got load balancer list of: $elb_list"
        INSTANCE_ELBS=$elb_list
        return 0
    fi
}
Run Code Online (Sandbox Code Playgroud)