我如何使用标签方法基于应用程序代码调用ec2实例列表

问题描述 投票:-2回答:2

我正在尝试基于该应用程序获取所有实例(服务器名称)ID。假设我在服务器中有一个应用程序。我如何知道哪个服务器下面的应用程序。我希望我的代码查找属于每个应用程序的所有实例(服务器)。有什么方法可以在ec2控制台中浏览该应用程序,并确定服务器与该应用程序相关联。更多使用标签的方法

  import boto3

   client = boto3.client('ec2')


   my_instance = 'i-xxxxxxxx'
amazon-ec2 boto3
2个回答
0
投票

(免责声明:我为AWS资源组工作)

[看到您对所有应用程序都使用标签的评论,您可以使用AWS资源组来创建组-以下示例假定您使用App:Something作为标签,首先创建一个资源组,然后列出该组的所有成员组。

例如,使用该组,您可以自动获得这些资源的CloudWatch dashboarduse this group as a target in RunCommand

import json
import boto3

RG = boto3.client('resource-groups')

RG.create_group(
  Name = 'Something-App-Instances',
  Description = 'EC2 Instances for Something App',
  ResourceQuery = {
    'Type': 'TAG_FILTERS_1_0',
    'Query': json.dumps({
      'ResourceTypeFilters': ['AWS::EC2::Instance'],
      'TagFilters': [{
        'Key': 'App',
        'Values': ['Something']
      }]
    })
  },
  Tags = {
    'App': 'Something'
  }
)

# List all resources in a group using a paginator
paginator = RG.get_paginator('list_group_resources')
resource_pages = paginator.paginate(GroupName = 'Something-App-Instances')
for page in resource_pages:
  for resource in page['ResourceIdentifiers']:
    print(resource['ResourceType'] + ': ' + resource['ResourceArn'])

仅获取列表而不将其保存为组的另一种选择是直接使用Resource Groups Tagging API


0
投票

您完全可以在Amazon EC2实例上安装什么。您可以通过在实例本身上运行代码来做到这一点。 AWS不会参与您在实例上安装什么的决定,它也不知道您在实例上安装了什么

因此,您需要自己跟踪“在什么服务器上安装了哪些应用程序”。

您可能选择在实例上利用Tags来添加一些元数据,例如服务器的用途。您还可以使用AWS Systems Manager在实例上运行命令(例如,安装软件),甚至使用AWS CodeDeploy将软件推广到服务器群中。

但是,即使具有所有这些部署选项,AWS也无法跟踪您放置在每台服务器上的内容。您需要自己做。

更新:可以使用AWS Resource Groups通过标签查看/管理资源。

以下是一些示例Python代码,用于按实例列出标签:

import boto3

ec2_resource = boto3.resource('ec2', region_name='ap-southeast-2')

instances = ec2_resource.instances.all()

for instance in instances:
    for tag in instance.tags:
        print(instance.instance_id, tag['Key'], tag['Value'])
© www.soinside.com 2019 - 2024. All rights reserved.