【发布时间】:2022-01-10 02:19:15
【问题描述】:
我想获取活动 EMR 集群的 ClusterId、ClusterArn、Public DNS 并将它们加载到 Postgres 表中。我可以在控制台中使用 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()
我能够在表格中插入记录。 但我需要在同一个脚本中获取 ClusterID、Arn、DNS,然后加载表中的值。 尝试使用 Boto3 ...无法成功 ...请帮助。 提前致谢。
【问题讨论】:
-
您应该不从 Python 调用 AWS CLI。请改用
boto3,这是适用于 Python 的 AWS 开发工具包。
标签: python amazon-web-services boto3 aws-cli amazon-emr