Can we get output from a Lambda function as CloudFormation Parameter?

0

Hi,
I am creating an s3 bucket policy where I have to enter the VPC endpoint id. Since this id is different for each region, I want to run a lambda function to get the ID. Now this ID should be inserted in the bucket policy.
Everything has to be done through a Cloudformation template.

My issue is - how to get the vpc endpoint ID from my lambda function to my bucket policy.

CloudFormation Snippet:
LambdaGetVpce:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: !Sub |
import json
import boto3

      def handler(event, context):  
        ec2 = boto3.client('ec2')  
        endp = ec2.describe_vpc_endpoints()  
        endpointId = endp\[/'VpcEndpoints/']\[0]\[/' VpcEndpointId/'] #Get this ID in bucket policy (Ignore the forward slash. Forum was putting some random value without slash)  

BucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref S3Bucket
PolicyDocument:
Statement:
-
Effect: Deny
Principal: ''
Action: 's3:
'
Resource: !Sub '${S3Bucket.Arn}/*'
Condition:
StringNotEquals:
'aws:SourceVpce': !Ref endpointId #Need to insert VPC Endpoint ID here

Edited by: ShuchitaTripathi on Jan 30, 2020 8:00 AM

gefragt vor 4 Jahren1282 Aufrufe
1 Antwort
0

I was able to achieve this using !GetAtt RunLambdaVpce.Endpoint

Here is the CF template snippet (Ignore the forward slashes near 'Endpoint'):

LambdaGetVpce:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: !Sub |
import json
import boto3
import cfnresponse
import logging

      def handler(event, context):  
        logging.basicConfig(level=logging.DEBUG)  
        log = logging.getLogger(__name__)  
        ec2 = boto3.client('ec2')  
        responseData = {}  
        physicalResourceId = {}  
        try:  
          endp = ec2.describe_vpc_endpoints()  
          endpointId = endp\[/'VpcEndpoints/']\[0]\[/'VpcEndpointId/']  
          responseData\[/'Endpoint/'] = endpointId  
          cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, physicalResourceId)  
          return  
        except:  
          cfnresponse.send(event, context, cfnresponse.FAILED, responseData, physicalResourceId)  
          log.exception("Lambda execution has failed!")  
          return  

BucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref S3Bucket
PolicyDocument:
Statement:
-
Sid: 'Stmt1573075545385'
Effect: Deny
Principal: ''
Action: 's3:
'
Resource: !Sub '${S3Bucket.Arn}/*'
Condition:
StringNotEquals:
'aws:SourceVpce': !GetAtt RunLambdaVpce.Endpoint

beantwortet vor 4 Jahren

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen