首页 > 解决方案 > 无法通过 lamda 跨 aws 账户进行 Elastic Search 查询

问题描述

我有一个简单的代码,它在不同的 aws 帐户中对 Elastic Search 集群进行查询。这是代码

def get_es_client():
    sts_connection = boto3.client('sts')
    es_gamma_act = sts_connection.assume_role(
        RoleArn="arn:aws:iam::<HIDDEN>:role/SIP_Metrics_Cross_Account_Access",
        RoleSessionName="cross_acct_lambda"
    )

    access_key = es_gamma_act['Credentials']['AccessKeyId']
    secret_key = es_gamma_act['Credentials']['SecretAccessKey']
    session_token = es_gamma_act['Credentials']['SessionToken']

    aws_auth = AWS4Auth(access_key, secret_key, region, "es", session_token=session_token)
    return Elasticsearch(
        hosts=[{'host': es_host, 'port': 443}],
        http_auth=aws_auth,
        use_ssl=True,
        verify_certs=True,
        connection_class=RequestsHttpConnection,
        timeout=120
    )


def datetime_to_millis(date):
    return int(date.timestamp() * 1000)


def get_summary_count(es_client, start_date, end_date, summary_type=None, workflow=None):
    query = {
        "query": {
            "bool": {
                "filter": [
                    {"term": {"locale.keyword": "en-US"}},
                    {
                        "range": {
                            "indexedAt": {
                                "gte": datetime_to_millis(start_date),
                                "lt": datetime_to_millis(end_date)
                            }
                        }
                    }
                ]
            }
        }
    }

    print(json.dumps(query))

    count = es_client.count(query, "summary-news-index")
    return count['count']


def get_es_data():
    es_client = get_es_client()

    start_date = datetime(2021, 7, 1)
    end_date = datetime(2021, 7, 3)

    count = get_summary_count(es_client, start_date, end_date)
    print(count)


if __name__ == "__main__":
    get_es_data()

运行此程序时出现以下错误

elasticsearch.exceptions.AuthorizationException: AuthorizationException(403, '{"Message":"User: arn:aws:sts::<HIDDEN>:assumed-role/SIP_Metrics_Cross_Account_Access/cross_acct_lambda is not authorized to perform: es:ESHttpPost"}')

我正在使用 STS 在有权执行 ESHttpPost 的目标帐户(与 ES 相同的帐户)中担任角色。似乎我能够正确承担该角色,但即使我拥有 ESHttpPost 权限,我仍然会收到此错误。当我从 lambda 函数运行此代码时也会发生这种情况。

如果我在这里遗漏了什么,你能告诉我吗?感谢您的回复

PS 根据要求,附加到代入角色 arn:aws:iam:::role/SIP_Metrics_Cross_Account_Access 的 IAM 策略

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "es:*",
            "Resource": "*"
        }
    ]
}

标签: amazon-web-serviceselasticsearchaws-lambdaamazon-iamsts

解决方案


推荐阅读