簡體   English   中英

如何在跨賬戶中訪問 Lambda 函數?

[英]How to access Lambda Function in cross account?

我有 2 個 Aws 賬戶(賬戶 A 和賬戶 B)。 我的目標是通過在賬戶 A 中使用 lambda 函數在賬戶 B 中創建自定義 AWS Config 規則。我在賬戶 A 中創建了 lambda 函數作為

import boto3
import json
import logging

log = logging.getLogger()
log.setLevel(logging.DEBUG)
APPLICABLE_RESOURCES = ["AWS::S3::Bucket"]


def evaluate_compliance(configuration_item):
    if configuration_item["resourceType"] not in APPLICABLE_RESOURCES:
        return {
            "compliance_type": "NOT_APPLICABLE",
            "annotation": "The rule doesn't apply to resources of type " +
            configuration_item["resourceType"] + "."
        }

    if configuration_item['configurationItemStatus'] == "ResourceDeleted":
        return {
            "compliance_type": "NOT_APPLICABLE",
            "annotation": "The configurationItem was deleted " +
                          "and therefore cannot be validated"
        }

    bucket_policy = configuration_item["supplementaryConfiguration"].get("BucketPolicy")
    if bucket_policy['policyText'] is None:
        return {
            "compliance_type": "COMPLIANT",
            "annotation": 'Bucket Policy does not exists'
        }

    else:
        return {
            "compliance_type": "NON_COMPLIANT",
            "annotation": 'Bucket Policy exists'
        }


def lambda_handler(event, context):
    log.debug('Event %s', event)
    invoking_event      = json.loads(event['invokingEvent'])
    configuration_item  = invoking_event["configurationItem"]
    evaluation          = evaluate_compliance(configuration_item)
    config              = boto3.client('config')

    config.put_evaluations(
       Evaluations=[
           {
               'ComplianceResourceType':    invoking_event['configurationItem']['resourceType'],
               'ComplianceResourceId':      invoking_event['configurationItem']['resourceId'],
               'ComplianceType':            evaluation["compliance_type"],
               "Annotation":                evaluation["annotation"],
               'OrderingTimestamp':         invoking_event['configurationItem']['configurationItemCaptureTime']
           },
       ],
       ResultToken=event['resultToken'])

我在賬戶 A 中有一個 lambda 執行角色(這是在我創建 lambda 函數時自動創建的),我為賬戶 B 中創建的角色添加了一個 AssumeRole 作為

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "logs:CreateLogGroup",
            "Resource": "arn:aws:logs:us-east-2:Account A:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:us-east-2:Account A:log-group:/aws/lambda/LambdaFunctionName:*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Resource": "arn:aws:iam::Account B:role/AccountBRole"
        }
    ]
}

我正在使用帳戶 A 中的用戶獲取 sts 客戶端所需的憑據訪問權限以獲取角色

在用戶的策略中添加了假設以及:-

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

使用 AWSConfigRulesExecutionRole Aws 托管權限在賬戶 B 中創建角色

和信任關系如下: -

 {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "AWS": [
              "arn:aws:iam::Account A:root",
              "arn:aws:iam::Account A:user/userName"
            ]
          },
          "Action": "sts:AssumeRole"
        }
      ]
    }

這是我使用賬戶 A 的 Lambda 函數在賬戶 B 中創建自定義 AWS 配置規則的 Java 代碼

AWSCredentials ourAwsCredentials = new BasicAWSCredentials("AWSSecretKeyAccountA",
                "AWSAccessKeyAccountA");   

        AWSSecurityTokenServiceClient stsClient = (AWSSecurityTokenServiceClient) AWSSecurityTokenServiceClientBuilder
                .standard()
                .withRegion(Regions.US_EAST_2)
                .withCredentials(new AWSStaticCredentialsProvider(ourAwsCredentials))
                .build();


            AssumeRoleRequest assumeRequest = new AssumeRoleRequest()
                   .withRoleArn("arn:aws:iam::Account B:role/AccountBRole")
                    .withDurationSeconds(3600)
                .withRoleSessionName("demo-1235");

            AssumeRoleResult assumeResult =
            stsClient.assumeRole(assumeRequest);

            BasicSessionCredentials temporaryCredentials =
            new BasicSessionCredentials(
                        assumeResult.getCredentials().getAccessKeyId(),
                        assumeResult.getCredentials().getSecretAccessKey(),
                        assumeResult.getCredentials().getSessionToken());

            AWSCredentialsProvider rolecredentials = new
                    AWSStaticCredentialsProvider(temporaryCredentials);
            AmazonConfigClient roleamazonConfigClient = (AmazonConfigClient) AmazonConfigClientBuilder.standard().withCredentials(rolecredentials)
                    .withRegion(Regions.US_EAST_2).build();


        PutConfigRuleRequest putConfigRuleRequest = new PutConfigRuleRequest();
        ConfigRule configRule = new ConfigRule();
        Source source = new Source();
        source.setOwner("CUSTOM_LAMBDA");
        source.setSourceIdentifier("arn:aws:lambda:us-east-2:Account A:function:TestLmabda");
        SourceDetail sourceDetail = new SourceDetail();     
        sourceDetail.setEventSource(EventSource.AwsConfig);
        sourceDetail.setMaximumExecutionFrequency(MaximumExecutionFrequency.TwentyFour_Hours);
        sourceDetail.setMessageType(MessageType.ScheduledNotification);
        source.setSourceDetails(Arrays.asList(sourceDetail));
        configRule.setSource(source);
        configRule.setConfigRuleName("TestCrossAcRule");
        putConfigRuleRequest.setConfigRule(configRule);
        PutConfigRuleResult putConfigRuleResult=amazonConfigRoleClient.putConfigRule(putConfigRuleRequest);
        logger.info("Put ConfigRuleResult is "+putConfigRuleResult);

它給了我錯誤

Exception in thread "main" com.amazonaws.services.config.model.InsufficientPermissionsException: The AWS Lambda function arn:aws:lambda:us-east-2:Account A:function:TestLmabda cannot be invoked. Check the specified function ARN, and check the function's permissions. (Service: AmazonConfig; Status Code: 400; Error Code: InsufficientPermissionsException; Request ID: 10d99a37-ba7b-4bdd-a7cd-941aa3287895)

編輯:-

這真的是正確的方法嗎? 也歡迎任何其他方式......第一件事是否真的可以從一個帳戶到另一個帳戶使用 lambda 函數?

InsufficientPermissionsException 表示以下錯誤之一:

對於 PutConfigRule,無法創建規則,因為分配給 AWS Config 的 IAM 角色缺乏執行 config:Put* 操作的權限。

對於 PutConfigRule,無法調用 AWS Lambda 函數。 檢查函數 ARN,並檢查函數的權限。

對於 PutOrganizationConfigRule,無法創建組織配置規則,因為您無權調用 IAM GetRole 操作或創建服務相關角色。

對於 PutConformancePack 和 PutOrganizationConformancePack,無法創建一致性包,因為您沒有權限:

調用 IAM GetRole 操作或創建服務相關角色。

讀取 Amazon S3 存儲桶。

HTTP 狀態代碼:400

您正在致電:

amazonConfigRoleClient.putConfigRule(putConfigRuleRequest);

但是您的 IAM 政策缺乏

"config:Put*",

或者您可以使用 AWS 托管策略 AWSConfigRole 並將其附加到您分配給 AWS Config 的 IAM 角色。

此外,您是否檢查了 lambda ARN 以了解它是否正確? 我在錯誤日志中看到您粘貼了以下內容: arn:aws:lambda:us-east-2:Account A:function:TestLmabda 。 TestLmabda錯字可能是問題所在?

參考:

  1. https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/config/AmazonConfig.html#tagResource-com.amazonaws.services.config.model.TagResourceRequest-

  2. https://docs.aws.amazon.com/config/latest/APIReference/API_PutConfigRule.html

  3. https://docs.aws.amazon.com/config/latest/developerguide/iamrole-permissions.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM