使用 Python 的 AWSCLI 命令

AWSCLI Commands using Python

我想获取活动 EMR 集群的 ClusterId、ClusterArn、Public DNS 并将它们加载到 Postgres Table.I 我能够在控制台中使用 CLI 命令获取 ClusterId 和 Arn .

aws emr list-clusters --active --query "Clusters[*].{ClusterId:Id}" --output text
aws emr list-clusters --active --query "Clusters[*].{ClusterArn:ClusterArn}" --output text

获得 cluster_id 后,我可以使用 CLI 命令获取 DNS。

cluster_id=j-xxx
aws emr describe-cluster --output text --cluster-id $cluster_id --query Cluster.MasterPublicDnsName

但我必须在 Python 脚本中执行此操作。 我无法将此命令集成到 python 脚本中。 所以为了我的目的,我做了以下 - 运行 下面的命令并将输出重定向到 json 文件。

aws emr list-clusters --active > test.json

test.json 文件的内容 -

{
    "Clusters": [
        {
            "Id": "j-xxx",
            "Name": "xxx",
            "Status": {
                "State": "WAITING",
                "StateChangeReason": {
                    "Message": "Cluster ready after last step completed."
                },
                "Timeline": {
                    "CreationDateTime": "2021-12-01T01:08:10.755000-06:00",
                    "ReadyDateTime": "2021-12-01T01:20:13.483000-06:00"
                }
            },
            "NormalizedInstanceHours": 832,
            "ClusterArn": "arn:aws:elasticmapreduce:xxx:xxx:cluster/j-xxx"
        }
    ]
}

现在使用 Python -

读取 json 文件
import json
import psycopg2

with open("cluster_info.json") as file:
    data=json.load(file)
CId=data["Clusters"][0]["Id"]
CArn=data["Clusters"][0]["ClusterArn"]
print(CId)
print(CArn)
#CDNS=`aws emr describe-cluster --output text --cluster-id $CId --query Cluster.MasterPublicDnsName`
#print(CDNS)
conn = psycopg2.connect(
   database="postgres", user='xxx', password='xxx', host='xxxx.rds.amazonaws.com', port= '5432'
)
cursor = conn.cursor()
query = '''INSERT INTO STAGE.EMR_CLUSTER_INFO (Cluster_ID, Cluster_Arn, Public_DNS) VALUES (%s,%s,%s)'''
values = (CId, CArn, 'ip-xxxx.ec2.internal') #Since I wasnt able to fetch DNS,so hardcoded the value just to test if the record is getting inserted in the tale or not
cursor.execute(query,values)
conn.commit()
print("Records inserted........")
conn.close()

我能够在 Table 中插入记录。 但我需要在同一脚本中获取 ClusterID、Arn、DNS,然后将值加载到 table 中。 尝试使用 Boto3 ...无法成功 ...请帮忙。 提前致谢。

这是您要找的吗? How do I list all running EMR clusters using Boto? and https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/emr.html#client

您可以从 boto 获取 MasterPublicDnsName、Id 和 clusterARN 的详细信息。如果您需要了解更多信息,请告诉我。

来自 boto3 describe_cluster():

import boto3

emr_client = boto3.client('emr')

clusters = emr_client.list_clusters()

for cluster in clusters['Clusters']:

  cluster_id = cluster['Id']

  response = emr_client.describe_cluster(ClusterId=cluster_id)

  cluster_arn = response['Cluster']['ClusterArn']
  cluster_dns_name = response['Cluster']['MasterPublicDnsName']

  # Insert into database here