简体   繁体   English

获取 EC2 自动缩放组中的实例列表?

[英]Getting a list of instances in an EC2 auto scale group?

Is there a utility or script available to retrieve a list of all instances from AWS EC2 auto scale group?是否有实用程序或脚本可用于从 AWS EC2 自动缩放组检索所有实例的列表?

I need a dynamically generated list of production instance to hook into our deploy process.我需要一个动态生成的生产实例列表来连接到我们的部署过程。 Is there an existing tool or is this something I am going to have to script?是否有现有的工具或者这是我必须编写的脚本?

Here is a bash command that will give you the list of IP addresses of your instances in an AutoScaling group.这是一个 bash 命令,它将为您提供 AutoScaling 组中实例的 IP 地址列表。

for ID in $(aws autoscaling describe-auto-scaling-instances --region us-east-1 --query AutoScalingInstances[].InstanceId --output text);
do
aws ec2 describe-instances --instance-ids $ID --region us-east-1 --query Reservations[].Instances[].PublicIpAddress --output text
done

(you might want to adjust the region and to filter per AutoScaling group if you have several of them) (如果您有多个 AutoScaling 组,您可能需要调整区域并过滤每个 AutoScaling 组)

On a higher level point of view - I would question the need to connect to individual instances in an AutoScaling Group.从更高层次的角度来看 - 我会质疑连接到 AutoScaling 组中的单个实例的必要性。 The dynamic nature of AutoScaling would encourage you to fully automate your deployment and admin processes. AutoScaling 的动态特性会鼓励您完全自动化您的部署和管理流程。 To quote an AWS customer : "If you need to ssh to your instance, change your deployment process"引用 AWS 客户的话:“如果您需要 ssh 到您的实例,请更改您的部署过程”

--Seb --塞伯

The describe-auto-scaling-groups command from the AWS Command Line Interface looks like what you're looking for. AWS 命令​​行界面中的describe-auto-scaling-groups命令看起来像您要查找的内容。

Edit: Once you have the instance IDs, you can use the describe-instances command to fetch additional details, including the public DNS names and IP addresses.编辑:获得实例 ID 后,您可以使用describe-instances命令获取其他详细信息,包括公共 DNS 名称和 IP 地址。

You can use the describe-auto-scaling-instances cli command, and query for your autoscale group name.您可以使用describe-auto-scaling-instances cli 命令,并查询您的自动缩放组名称。

Example:例子:

aws autoscaling describe-auto-scaling-instances --region us-east-1 --query 'AutoScalingInstances[?AutoScalingGroupName==`YOUR_ASG`]' --output text aws autoscaling describe-auto-scaling-instances --region us-east-1 --query 'AutoScalingInstances[?AutoScalingGroupName==`YOUR_ASG`]' --output text

Hope that helps希望有帮助

You can also use below command to fetch private ip address without any jq/awk/sed/cut您也可以使用以下命令来获取私有 IP 地址,而无需任何 jq/awk/sed/cut

$ aws autoscaling describe-auto-scaling-instances --region us-east-1 --output text \
--query "AutoScalingInstances[?AutoScalingGroupName=='ASG-GROUP-NAME'].InstanceId" \
| xargs -n1 aws ec2 describe-instances --instance-ids $ID --region us-east-1 \
--query "Reservations[].Instances[].PrivateIpAddress" --output text

courtesy this礼貌这个

I actually ended up writing a script in Python because I feel more comfortable in Python then Bash,我实际上最终用 Python 编写了一个脚本,因为我觉得 Python 比 Bash 更舒服,

#!/usr/bin/env python

"""
ec2-autoscale-instance.py

Read Autoscale DNS from AWS

Sample config file,
{
    "access_key": "key",
    "secret_key": "key",
    "group_name": "groupName"
}
"""

from __future__ import print_function
import argparse
import boto.ec2.autoscale
try:
    import simplejson as json
except ImportError:
    import json

CONFIG_ACCESS_KEY = 'access_key'
CONFIG_SECRET_KEY = 'secret_key'
CONFIG_GROUP_NAME = 'group_name'


def main():
    arg_parser = argparse.ArgumentParser(description=
                                         'Read Autoscale DNS names from AWS')
    arg_parser.add_argument('-c', dest='config_file',
                            help='JSON configuration file containing ' +
                                 'access_key, secret_key, and group_name')
    args = arg_parser.parse_args()
    config = json.loads(open(args.config_file).read())
    access_key = config[CONFIG_ACCESS_KEY]
    secret_key = config[CONFIG_SECRET_KEY]
    group_name = config[CONFIG_GROUP_NAME]

    ec2_conn = boto.connect_ec2(access_key, secret_key)
    as_conn = boto.connect_autoscale(access_key, secret_key)

    try:
        group = as_conn.get_all_groups([group_name])[0]
        instances_ids = [i.instance_id for i in group.instances]
        reservations = ec2_conn.get_all_reservations(instances_ids)
        instances = [i for r in reservations for i in r.instances]
        dns_names = [i.public_dns_name for i in instances]
        print('\n'.join(dns_names))
    finally:
        ec2_conn.close()
        as_conn.close()


if __name__ == '__main__':
    main()

Gist要旨

The answer at https://stackoverflow.com/a/12592543/20774 was helpful in developing this script. https://stackoverflow.com/a/12592543/20774 上的答案有助于开发此脚本。

Use the below snippet for sorting out ASGs with specific tags and listing out its instance details.使用以下代码段整理具有特定标签的 ASG 并列出其实例详细信息。

#!/usr/bin/python

import boto3

ec2 = boto3.resource('ec2', region_name='us-west-2')

def get_instances():
        client = boto3.client('autoscaling', region_name='us-west-2')
        paginator = client.get_paginator('describe_auto_scaling_groups')
        groups = paginator.paginate(PaginationConfig={'PageSize': 100})
        #print groups
        filtered_asgs = groups.search('AutoScalingGroups[] | [?contains(Tags[?Key==`{}`].Value, `{}`)]'.format('Application', 'CCP'))

        for asg in filtered_asgs:
                print asg['AutoScalingGroupName']
                instance_ids = [i for i in asg['Instances']]
                running_instances = ec2.instances.filter(Filters=[{}])
                for instance in running_instances:
                        print(instance.private_ip_address)

if __name__ == '__main__':
    get_instances()

for ruby using aws-sdk gem v2 First create ec2 object as this:对于使用 aws-sdk gem v2 的 ruby​​ 首先创建 ec2 对象,如下所示:

ec2 = Aws::EC2::Resource.new(region: 'region', credentials: Aws::Credentials.new('IAM_KEY', 'IAM_SECRET') ) ec2 = Aws::EC2::Resource.new(region: 'region', 凭证: Aws::Credentials.new('IAM_KEY', 'IAM_SECRET') )

instances = []实例 = []

ec2.instances.each do |i|
   p "instance id---", i.id
   instances << i.id

end结尾

This will fetch all instance ids in particular region and can use more filters like ip_address.这将获取特定区域的所有实例 ID,并可以使用更多过滤器,如 ip_address。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在相对复杂的基础架构中正确自动扩展AWS EC2 Instances组? - How to properly auto-scale AWS EC2 Instances group in a relatively complex infrastructures? AWS:如何在自动扩展期间配置EC2实例 - AWS: how to configure EC2 instances during auto scale 如何在CloudFormation中的Auto Scaling组中安排其他EC2实例? - How to schedule additional EC2 instances in an Auto Scaling group in CloudFormation? 如何将现有 EC2 实例附加到 terraform 中的 Auto Scaling 组? - How to attach existing EC2 instances to auto scaling group in terraform? 如何在 ec2 实例的 Auto Scaling 组中添加交换内存 - How to add swap memory in auto scaling group of ec2 instances Ansible:将正在运行的EC2实例添加到“自动伸缩”组 - Ansible : Add running EC2 instances to Auto-scaling group 为自动伸缩组的 ec2 实例提供索引号 - give index number to ec2 instances of auto scaling group EC2 实例的功能是否按比例扩展? - Do the capabilities of EC2 instances scale proportionately? Auto Scaling:从“扩大保护”开始阻止EC2实例吗? - Auto Scaling: Stop EC2 instances from starting with “scale-in protection”? 找到新的启动配置后,自动更新Auto Scaling组中的EC2实例 - Auto renew EC2 instances in an Auto Scaling Group when a new launch config is found
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM