Как получить доступ к возвращаемому значению лямбды в другом ресурсе облачной информации? - PullRequest
1 голос
/ 08 ноября 2019
  GetClientId:
    Type: "AWS::Lambda::Function"
    Properties:
      Handler: index.handler
      Role: !GetAtt LambdaESCognitoRole.Arn
      Code:
        ZipFile: !Sub |
          var AWS = require('aws-sdk');
          const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
          var response = require('cfn-response');
          var responseData = {};
          exports.handler = async (event, context) => {
            console.log(JSON.stringify(event, null, 2));
            var params = {
              UserPoolId: event.ResourceProperties.UserPoolId
            };
            await cognitoidentityserviceprovider.listUserPoolClients(params, function(err, data) {
              if (err) console.log(err, err.stack); // an error occurred
              else {
                console.log(data); // successful response 
                responseData = {'ClientId': data.UserPoolClients[0].ClientId};
              }
            }).promise();
            response.send(event, context, response.SUCCESS, responseData);
            return;
            }
      Runtime: nodejs8.10 

   CallGetClientId:
     Type: 'Custom::CallGetClientId'
     Version: 1.0
     Properties:
       ServiceToken: !GetAtt GetClientId.Arn
       UserPoolId: !Ref CognitoUserPool

  IdentityPoolRoleMapping:
    Type: "AWS::Cognito::IdentityPoolRoleAttachment"
    Properties:
      IdentityPoolId: !Ref CognitoIdentityPool
      Roles:
        authenticated: !GetAtt AuthenticatedRole.Arn
        unauthenticated: !GetAtt UnauthenticatedRole.Arn
      RoleMappings:
        "cognito-identity-provider":
          IdentityProvider: !Join ['', [ !GetAtt CognitoUserPool.ProviderName, ':', !GetAtt CallGetClientId.ClientId ]] #Need to get the ClientID here
          AmbiguousRoleResolution: Deny
          Type: Rules
          RulesConfiguration:
            Rules:
              - Claim: "custom:groups"
                MatchType: "Contains"
                RoleARN: !GetAtt AuthenticatedRole.Arn
                Value: "user"
              - Claim: "custom:groups"
                MatchType: "Contains"
                RoleARN: !GetAtt AuthenticatedAdminRole.Arn
                Value: "admin"

1 Ответ

0 голосов
/ 08 ноября 2019

Я вижу два способа решения проблемы.

Один - используйте параметр cfnresponse.send(...responseData). Смотрите здесь: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-lambda-function-code-cfnresponsemodule.html#w2ab1c17c25c14b9c11

Мой пример:

cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, responseData['ClientSecret'])

После того, как вы вернули данные из Lambda, вы можете ссылаться на них в шаблоне CFN с помощью! GetAtt:

Value: !GetAtt HapiUserPoolClientPostProc.ClientSecret

Два - я использую пользовательские ресурсы в качестве компонентов «постпроцессора», т.е. создаю ресурсы и после них обновляю их параметры с помощью пользовательского ресурса. Этот порядок будет гарантирован заданными входными параметрами лямбда-ресурса (зависимость).

Мой пример - подача URL-адресов обратного вызова Cognito AppClient из моего ElasticBeanstalk WebApp. Поэтому я создаю и UserPool AppClient, и веб-приложение EB, затем лямбда-настраиваемый ресурс постпроцессора берет URL-адрес из EB и обновляет CallbackURL в Cognito.

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...