Last active
November 15, 2020 07:03
-
-
Save quin2/2c269682e0181e7bd1c346e9425c4756 to your computer and use it in GitHub Desktop.
Get API Gateway Key inside Cloudformation, with JSON and Python 3 (Place objects under "Resources" parent)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"LambdaApiGatewayRole": { | |
"Type": "AWS::IAM::Role", | |
"Properties": { | |
"AssumeRolePolicyDocument": { | |
"Version": "2012-10-17", | |
"Statement": [{ "Effect": "Allow", "Principal": {"Service": ["lambda.amazonaws.com"]}, "Action": ["sts:AssumeRole"] }] | |
}, | |
"Path": "/", | |
"Policies": [ | |
{ | |
"PolicyName": "gatewayAccess", | |
"PolicyDocument": { | |
"Version": "2012-10-17", | |
"Statement": [ | |
{ | |
"Effect": "Allow", | |
"Action": "apigateway:GET", | |
"Resource": "*" | |
} | |
] | |
} | |
}, | |
{ | |
"PolicyName": "logging", | |
"PolicyDocument": { | |
"Version": "2012-10-17", | |
"Statement": [ | |
{ | |
"Effect": "Allow", | |
"Action": [ | |
"logs:CreateLogGroup", | |
"logs:CreateLogStream", | |
"logs:PutLogEvents", | |
"logs:DescribeLogStreams" | |
], | |
"Resource": [ | |
"arn:aws:logs:*:*:*" | |
] | |
} | |
] | |
} | |
} | |
] | |
} | |
}, | |
"KeyValueFunc": { | |
"Type": "AWS::Lambda::Function", | |
"Properties": { | |
"Code": { | |
"ZipFile": { "Fn::Join": ["\n", [ | |
"import boto3", | |
"import cfnresponse", | |
"def lambda_handler(e,ctx):", | |
" try:", | |
" apiKeyID=e['ResourceProperties']['ApiKeyID']", | |
" myGateway=boto3.client('apigateway')", | |
" resp2=myGateway.get_api_key(apiKey=apiKeyID,includeValue=True)", | |
" cfnresponse.send(e,ctx,cfnresponse.SUCCESS,{'mykey':resp2['value']})", | |
" except Exception as exceptt:", | |
" print(exceptt)", | |
" cfnresponse.send(e,ctx,cfnresponse.FAILED,{'mykey':'err'})" | |
]]} | |
}, | |
"Description": "Returns API Gateway Key", | |
"FunctionName": "apikey_value_func", | |
"Handler": "index.lambda_handler", | |
"Role": { "Fn::GetAtt" : ["LambdaApiGatewayRole", "Arn"] }, | |
"Runtime": "python3.6" | |
} | |
}, | |
"GetApiKeyValue": { | |
"Type": "Custom::LambdaCallout", | |
"Properties": { | |
"ServiceToken": {"Fn::GetAtt": ["KeyValueFunc", "Arn"]}, | |
"ApiKeyID": {"Ref": "APIKey"} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment