본문으로 건너뛰기
번역된 페이지

이 페이지는 AI의 도움을 받아 영어에서 번역되었습니다. 두 내용이 다를 경우 영어 버전을 기준으로 합니다.

AWS 글로벌 인벤토리

이 가이드에서는 StackQL을 사용하여 지정된 AWS 계정 내 모든 리전의 모든 서비스에 있는 모든 리소스에 대한 포괄적인 인벤토리를 생성하는 방법을 보여 줍니다. StackQL은 SQL 구문을 사용하여 클라우드 인프라와 리소스를 쿼리하고 배포할 수 있는 강력한 개발 도구입니다.

테스트 환경 임베디드 SQL 백엔드 postgres SQL 백엔드 macos linux powershell

작동 방식​

StackQL은 여러 쿼리를 비동기적으로 처리할 수 있는 SQL 엔진을 구현합니다. 예를 들면 다음과 같습니다.

SELECT region, COUNT(*) as num_functions
FROM aws.lambda.functions
WHERE region IN (
'us-east-1','us-east-2','us-west-1','us-west-2',
'ap-south-1','ap-northeast-3','ap-northeast-2',
'ap-southeast-1','ap-southeast-2','ap-northeast-1',
'ca-central-1','eu-central-1','eu-west-1',
'eu-west-2','eu-west-3','eu-north-1','sa-east-1')
GROUP BY region;

위 쿼리는 실제로는 병렬로 실행되는 17개의 쿼리(리전당 쿼리 1개)이며, 그 결과가 집계되어 보고서로 표시됩니다. StackQL용 Python 래퍼인 pystackql 라이브러리를 사용하면 해당 서비스가 지원하는 모든 리전에 대해 모든 서비스의 모든 리소스를 반복 처리할 수 있습니다. 그 결과로 아래 예제와 같이 각 리전에 리소스별로 배포된 인스턴스 수를 보여 주는 보고서가 생성됩니다.

AWS 인벤토리 예제

사전 요구 사항​

  • pip install pystackql 명령으로 설치할 수 있는 pystackql
  • ReadOnlyAccess 정책 이상이 연결된 AWS 사용자 또는 역할(역할은 sts assume-role 명령으로 수임할 수 있음)
  • AWS_ACCESS_KEY_ID 및 AWS_SECRET_ACCESS_KEY 환경 변수 설정(AWS CloudShell을 사용하면 자동으로 설정할 수 있음)

코드​

아래 코드는 다음 작업을 수행합니다.

  1. 모든 AWS 리전 목록(regions)과 서비스별로 지원되는 리전 목록(supported_regions)을 정의합니다. supported_regions 목록을 도출하는 방법에 대한 자세한 내용은 AWS Service Support by Region at a Glance를 참조하세요.
  2. aws 및 awscc StackQL 프로바이더가 아직 설치되어 있지 않으면 가져옵니다.
  3. SHOW SERVICES 문을 사용하여 각 서비스를 반복 처리한 다음, 서비스마다 SHOW RESOURCES 문을 사용하여 각 리소스를 반복 처리합니다.
  4. SELECT 문으로 모든 리전에 걸쳐 각 리소스의 모든 인스턴스를 비동기적으로 조회하고, 데이터를 리전별로 그룹화한 다음 리전별로 각 리소스의 인스턴스 수를 계산합니다.

코드는 다음과 같습니다.

from regions import supported_regions, regions
from resources import excluded_resources, resource_filters
import time
from pystackql import StackQL
import pandas as pd

stackql = StackQL(output='pandas', page_limit=-1, execution_concurrency_limit=-1)

def pull_stackql_providers():
providers_df = stackql.execute("SHOW PROVIDERS")
installed = providers_df['name'].values if not providers_df.empty else []
for provider in ('aws', 'awscc'):
if provider not in installed:
print(f"{provider} not installed. Installing {provider}")
res = stackql.executeStmt(f"REGISTRY PULL {provider}")
print(res['message'])

def get_s3_buckets():
# special case for s3 buckets - use the awscc provider's list view, which
# returns each bucket alongside its region in a single query across all regions
regions_in = ", ".join([f"'{region}'" for region in regions])
buckets_df = stackql.execute(f"""
SELECT region, bucket_name
FROM awscc.s3.buckets_list_only
WHERE region IN ({regions_in});
""")
# Group by region and count the total resources (buckets) in each region
grouped = buckets_df.groupby('region').size().reset_index(name='total_resources')
grouped['svc'] = 's3'
grouped['res'] = 'buckets'
output_df = grouped[['svc', 'res', 'region', 'total_resources']]
return output_df

def main():
start_time = time.time()
pull_stackql_providers()
results_df = pd.DataFrame(columns=['svc', 'res', 'region', 'total_resources'])
# get all enumerable aws services
services_df = stackql.execute("SHOW SERVICES IN aws")
for svcIx, svcRow in services_df.iterrows():
service = svcRow['name']
if service in supported_regions:
# check all enumerable aws resources in the service against supported regions
resources_df = stackql.execute(f"SHOW RESOURCES IN aws.{service}")
plural_resources = [resource for resource in resources_df['name'].tolist() if resource.endswith('s')]
if plural_resources:
for resource in plural_resources:
print(f"Checking {resource} in {service}...")
if service == 's3' and resource == 'buckets':
print(f"Checking location for s3 buckets...")
resource_df = get_s3_buckets()
else:
# should we skip this service?
if service in excluded_resources and resource in excluded_resources[service]:
continue
# check if the resource is global or regional
if 'global' in supported_regions[service]:
regions_in = ", ".join([f"'{region}'" for region in regions])
else:
regions_in = ", ".join([f"'{region}'" for region in supported_regions[service]])

# check if there are additional where clauses for this resource
where_clause = resource_filters.get(service, {}).get(resource, '')

resource_df = stackql.execute(f"""
SELECT '{service}' as svc, '{resource}' as res, region, COUNT(*) as total_resources
FROM aws.{service}.{resource}
WHERE region IN ({regions_in}){where_clause}
GROUP BY svc, res, region
""")

if not resource_df.empty:
# Append resource_df to the results_df
if not 'error' in resource_df.columns:
results_df = pd.concat([results_df, resource_df], ignore_index=True)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"Elapsed time: {elapsed_time:.2f} seconds")
results_df.to_csv('all_aws_resources.csv', index=False)

if __name__ == "__main__":
main()