Route53のレコード情報、全リージョンのELB-EC2紐付け情報、全リージョンのEIPが割り当てられたEC2を抽出するスクリプトを作成したので備忘録として残します。
見ての通り、完全な自分用のメモなので、使用に関しては自己責任でお願いします。
1、事前準備
作成したスクリプトはPython で動作させるため、動作環境の設定を行います。
今回はCentOS8にて、AWSCLIのインストール・Python3のインストール・Boto3のインストール手順について記載したいと思います。
1-1、AWSCLIのインストール
以下リンクを参照してAWSCLIのインストールを行います。
Linux での AWS CLI バージョン 2 のインストール、更新、アンインストール
1-2、Python3のインストール
pyenvを使用して、Python3のインストールを行います。
yum install gcc zlib-devel bzip2 bzip2-devel readline readline-devel sqlite sqlite-devel openssl openssl-devel git make
git clone git://github.com/yyuu/pyenv.git ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
source ~/.bash_profile
pyenv -v
→バージョンが表示される事を確認
pyenv install --list
→最新バージョンのPythonを確認
pyenv install 3.X.X
→最新バージョンを入力してインストール
pyenv global 3.X.X
→OS全体で使用するPythonを設定
pyenv versions
python --version
→バージョン確認
1-3、Boto3のインストール
pipコマンドを使用してBoto3をインストールする
pip install boto3
2、情報取得用スクリプト
2-1、Route53のゾーン情報取得
Route53のホストゾーンに設定された全レコードを取得します。
「HostedZoneId」に対象となるゾーンのIDを設定して実行します。
#Route53_record_extraction.py
import boto3
client = boto3.client('route53')
HostedZoneId = ''
num = 0
flag = True
ResourceRecordSets = client.list_resource_record_sets(HostedZoneId = HostedZoneId, MaxItems='400')
while flag:
for ResourceRecordSet in ResourceRecordSets['ResourceRecordSets']:
num = num +1
if 'ResourceRecords' in ResourceRecordSet:
for ResourceRecord in ResourceRecordSet['ResourceRecords']:
print(ResourceRecordSet['Name'], ResourceRecordSet['Type'], ResourceRecord['Value'])
if 'AliasTarget' in ResourceRecordSet:
print(ResourceRecordSet['Name'], ResourceRecordSet['Type'], ResourceRecordSet['AliasTarget']['DNSName'])
IsTruncated = str(ResourceRecordSets['IsTruncated'])
if IsTruncated == "False":
flag = False
if IsTruncated == "True":
StartRecordName = ResourceRecordSets['NextRecordName']
if flag:
ResourceRecordSets = client.list_resource_record_sets(HostedZoneId = HostedZoneId, StartRecordName = StartRecordName, MaxItems='400')
print('レコード数:',num)
2-2、パブリックIPが割り当てられたEC2取得
アカウント内の全リージョンに存在する、Elastic IP アドレスが設定されたEC2情報を取得します。
#Extract_EC2_EIP_resources_from_all_regions.py
import boto3
client_ec2 = boto3.client('ec2')
regions_response = client_ec2.describe_regions()
for region in regions_response['Regions']:
client_ec2_region = boto3.client('ec2', region_name=region['RegionName'])
response = client_ec2_region.describe_instances()
reservations = response['Reservations']
if not reservations:
continue
for reservation in reservations:
instance_id = reservation['Instances'][0]['InstanceId']
tags = reservation['Instances'][0]['Tags']
for tag in tags:
if tag['Key'] == 'Name':
instance_name = tag['Value']
for NetworkInterface in reservation['Instances'][0]['NetworkInterfaces']:
for PrivateIpAddresse in NetworkInterface['PrivateIpAddresses']:
if "Association" in PrivateIpAddresse:
PublicIp = PrivateIpAddresse['Association']['PublicIp']
print(instance_id,";",instance_name,";",PublicIp,";",region['RegionName'])
2-3、ELB-EC2の対応を取得
アカウント内の全リージョンに存在するALB・CLBのDNS名と、ELBに紐づくEC2情報を取得します。
#Extract_ELB-EC2_resources_from_all_regions.py
import boto3
client_ec2 = boto3.client('ec2')
regions_response = client_ec2.describe_regions()
num = 0
for region in regions_response['Regions']:
client_elb_region = boto3.client('elb', region_name=region['RegionName'])
client_ec2_region = boto3.client('ec2', region_name=region['RegionName'])
try:
response = client_elb_region.describe_load_balancers()
for LoadBalancerDescription in response['LoadBalancerDescriptions']:
num = num + 1
DNSName = LoadBalancerDescription['DNSName']
Instances_Id = []
Instances_Name = []
if "Instances" in LoadBalancerDescription:
for Instance in LoadBalancerDescription["Instances"]:
Instances_Id.append(Instance["InstanceId"])
if not Instances_Id == []:
response_describe_instances = client_ec2_region.describe_instances(InstanceIds=Instances_Id)
for instance in response_describe_instances['Reservations']:
for instance_tag in instance['Instances'][0]['Tags']:
if instance_tag['Key'] == "Name":
Instances_Name.append(instance_tag['Value'])
print(DNSName,";",Instances_Id,";",Instances_Name,";",region['RegionName'],"; CLB")
except Exception as e:
print(e)
#print(num)
#ALB全リージョンのリソースを抜き出す
client_ec2 = boto3.client('ec2')
regions_response = client_ec2.describe_regions()
num = 0
for region in regions_response['Regions']:
client_elbv2_region = boto3.client('elbv2', region_name=region['RegionName'])
client_ec2_region = boto3.client('ec2', region_name=region['RegionName'])
try:
response = client_elbv2_region.describe_load_balancers()
for LoadBalancer in response['LoadBalancers']:
num = num + 1
Instances_Id = []
Instances_Name = []
DNSName = LoadBalancer['DNSName']
LoadBalancerArn = LoadBalancer['LoadBalancerArn']
response_describe_target_groups = client_elbv2_region.describe_target_groups(LoadBalancerArn = LoadBalancerArn)
for target_group in response_describe_target_groups['TargetGroups']:
response_target_health = client_elbv2_region.describe_target_health(TargetGroupArn = target_group['TargetGroupArn'])
for TargetHealthDescription in response_target_health["TargetHealthDescriptions"]:
Instances_Id.append(TargetHealthDescription["Target"]["Id"])
if not Instances_Id == []:
response_describe_instances = client_ec2_region.describe_instances(InstanceIds=Instances_Id)
for instance in response_describe_instances['Reservations']:
for instance_tag in instance['Instances'][0]['Tags']:
if instance_tag['Key'] == "Name":
Instances_Name.append(instance_tag['Value'])
print(DNSName,";",Instances_Id,";",Instances_Name,";",region['RegionName'],"; ALB")
except Exception as e:
print(e)
2-4、CFのアクセス元取得
各Cloud frontに設定されたオリジン情報を取得します。
#Extract_CF-Origins_resources.py
import boto3
CF_client = boto3.client('cloudfront')
response_list_distributions = CF_client.list_distributions()['DistributionList']['Items']
for distribution in response_list_distributions:
CF_DomainName = distribution['DomainName']
Origins_DomainName = []
for Item in distribution['Origins']['Items']:
Origins_DomainName.append(Item['DomainName'])
print(CF_DomainName,";",Origins_DomainName)
2-5、ACMの構成情報取得
アカウント内の全リージョンに存在するACM情報を取得します。
#Extract_ACM_resources_from_all_regions.py
import boto3
client_ec2 = boto3.client('ec2')
regions_response = client_ec2.describe_regions()
num = 0
for region in regions_response['Regions']:
try:
client_acm = boto3.client('acm', region_name=region['RegionName'])
response_list_certificates = client_acm.list_certificates()
for CertificateArn in response_list_certificates['CertificateSummaryList']:
response_describe_certificate = client_acm.describe_certificate(CertificateArn = CertificateArn['CertificateArn'])
CertificateArn = response_describe_certificate["Certificate"]['CertificateArn']
SubjectAlternativeNames = response_describe_certificate["Certificate"]['SubjectAlternativeNames']
Type = response_describe_certificate["Certificate"]["Type"]
Serial = response_describe_certificate["Certificate"]["Serial"]
NotAfter = response_describe_certificate["Certificate"]["NotBefore"]
print(CertificateArn,";",SubjectAlternativeNames,";",Type,";",region['RegionName'],";",Serial,";",NotAfter)
except Exception as e:
print(e)
2-6、ELB・CFに設定された証明書情報取得
アカウント内の全リージョンに存在するALB・CLBとCloudFrontに設定された証明書情報を取得します。
証明書はARNを取得します。
#Extract_resourcesELB-ACM_from_all_regions.py
#CLB全リージョンのリソースを抜き出す
import boto3
client_ec2 = boto3.client('ec2')
regions_response = client_ec2.describe_regions()
num = 0
for region in regions_response['Regions']:
client_elb_region = boto3.client('elb', region_name=region['RegionName'])
try:
response = client_elb_region.describe_load_balancers()
for LoadBalancerDescription in response['LoadBalancerDescriptions']:
num = num + 1
DNSName = LoadBalancerDescription['DNSName']
for ListenerDescription in LoadBalancerDescription['ListenerDescriptions']:
if "SSLCertificateId" in ListenerDescription['Listener']:
SSLCertificateId = ListenerDescription['Listener']['SSLCertificateId']
print(DNSName,";",SSLCertificateId,";",region['RegionName'])
except Exception as e:
print(e)
#print(num)
#ALB全リージョンのリソースを抜き出す
client_ec2 = boto3.client('ec2')
regions_response = client_ec2.describe_regions()
num = 0
for region in regions_response['Regions']:
client_elbv2_region = boto3.client('elbv2', region_name=region['RegionName'])
try:
response = client_elbv2_region.describe_load_balancers()
for LoadBalancer in response['LoadBalancers']:
num = num + 1
Certificates = []
DNSName = LoadBalancer['DNSName']
LoadBalancerArn = LoadBalancer['LoadBalancerArn']
response_describe_listeners = client_elbv2_region.describe_listeners(LoadBalancerArn = LoadBalancerArn)
for Listener in response_describe_listeners['Listeners']:
if "Certificates" in Listener:
response_describe_listener_certificates = client_elbv2_region.describe_listener_certificates(ListenerArn = Listener['ListenerArn'])
for Certificate in response_describe_listener_certificates['Certificates']:
Certificates.append(Certificate['CertificateArn'])
print(DNSName,";",Certificates,";",region['RegionName'])
except Exception as e:
print(e)
#print(num)
#CFのリソースを抜き出す
client_cf = boto3.client('cloudfront')
cf_list = client_cf.list_distributions()['DistributionList']
num = 0
for Distribution in cf_list['Items']:
num = 1 + num
DomainName = Distribution['DomainName']
if "IAMCertificateId" in Distribution['ViewerCertificate']:
CertificateId = Distribution['ViewerCertificate']['IAMCertificateId']
if "ACMCertificateArn" in Distribution['ViewerCertificate']:
CertificateId = Distribution['ViewerCertificate']['ACMCertificateArn']
print(DomainName,";",CertificateId)
#print(num)