Skip to content

Instantly share code, notes, and snippets.

@eelzinaty
Created April 25, 2019 15:23
Show Gist options
  • Save eelzinaty/f2e6eaf3f8282f3d66db1a0732e5c6dd to your computer and use it in GitHub Desktop.
Save eelzinaty/f2e6eaf3f8282f3d66db1a0732e5c6dd to your computer and use it in GitHub Desktop.
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "An auto-generated nested stack.",
"Metadata": {},
"Parameters": {
"AppSyncApiId": {
"Type": "String",
"Description": "The id of the AppSync API associated with this project."
},
"AppSyncApiName": {
"Type": "String",
"Description": "The name of the AppSync API",
"Default": "AppSyncSimpleTransform"
},
"env": {
"Type": "String",
"Description": "The environment name. e.g. Dev, Test, or Production",
"Default": "NONE"
}
},
"Conditions": {
"HasEnvironmentParameter": {
"Fn::Not": [
{
"Fn::Equals": [
{
"Ref": "env"
},
"NONE"
]
}
]
}
},
"Resources": {
"AppSyncFixSecurityExecutionRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"RoleName": {
"Fn::If": [
"HasEnvironmentParameter",
{
"Fn::Join": [
"",
[
{
"Ref": "AppSyncApiName"
},
"-",
"fix-security-iam",
"-",
{
"Ref": "env"
}
]
]
},
{
"Fn::Join": [
"",
[
{
"Ref": "AppSyncApiName"
},
"-",
"fix-security-iam"
]
]
}
]
},
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"lambda.amazonaws.com"
]
},
"Action": [
"sts:AssumeRole"
]
}
]
},
"Policies": [
{
"PolicyName": "cloudWatchPolicy",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": {
"Fn::Sub": [
"arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambda}:log-stream:*",
{
"region": {
"Ref": "AWS::Region"
},
"account": {
"Ref": "AWS::AccountId"
},
"lambda": {
"Fn::If": [
"HasEnvironmentParameter",
{
"Fn::Join": [
"",
[
{
"Ref": "AppSyncApiName"
},
"-",
"SecuritySetup",
"-",
{
"Ref": "env"
}
]
]
},
{
"Fn::Join": [
"",
[
{
"Ref": "AppSyncApiName"
},
"-",
"SecuritySetup"
]
]
}
]
}
}
]
}
}
]
}
},
{
"PolicyName": "appsyncPolicy",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"appsync:UpdateGraphqlApi"
],
"Resource": {
"Fn::Sub": [
"arn:aws:appsync:${region}:${account}:apis/${graphqlapi}",
{
"region": {
"Ref": "AWS::Region"
},
"account": {
"Ref": "AWS::AccountId"
},
"graphqlapi": {
"Ref": "AppSyncApiId"
}
}
]
}
}
]
}
}
]
}
},
"AppSyncFixSecurityLambdaFunction": {
"DependsOn": [
"AppSyncFixSecurityExecutionRole"
],
"Type": "AWS::Lambda::Function",
"Properties": {
"Code": {
"ZipFile": {
"Fn::Join": [
"\n",
[
"const aws = require('aws-sdk');",
"exports.handler = async (event, context) => {",
" try {",
" console.log(event.RequestType);",
" console.log(event.ResourceProperties);",
" if (event.RequestType == 'Delete') {",
" await sendResponse(event, context, 'SUCCESS', {});",
" context.done();",
" }",
" else if (event.RequestType == 'Update' || event.RequestType == 'Create') {",
" const appsync = new aws.AppSync({ apiVersion: '2017-07-25', region: event.ResourceProperties.region });",
" const params = {",
" apiId: event.ResourceProperties.appsynclId,",
" name: event.ResourceProperties.appsyncname,",
" authenticationType: 'AWS_IAM'",
" };",
" console.log(params);",
" await appsync.updateGraphqlApi(params).promise();",
" await sendResponse(event, context, 'SUCCESS', {});",
" context.done();",
" }",
" else {",
" console.log('No Event!!!');",
" context.done();",
" }",
" }",
" catch (err) {",
" console.log(err);",
" const responseData = { Error: err };",
" await sendResponse(event, context, 'FAILED', responseData);",
" context.done();",
" }",
"};",
"async function sendResponse(event, context, responseStatus, responseData, physicalResourceId, noEcho) {",
" var responseBody = JSON.stringify({",
" Status: responseStatus,",
" Reason: 'See the details in CloudWatch Log Stream: ' + context.logStreamName,",
" PhysicalResourceId: physicalResourceId || context.logStreamName,",
" StackId: event.StackId,",
" RequestId: event.RequestId,",
" LogicalResourceId: event.LogicalResourceId,",
" NoEcho: noEcho || false,",
" Data: responseData",
" });",
" console.log('Response body:', responseBody);",
" var https = require('https');",
" var url = require('url');",
" let parsedUrl;",
" try {",
" parsedUrl = url.parse(event.ResponseURL);",
" } catch (error) {",
" throw new Error(`Invalid url ${event.ResponseUR}`);",
" }",
" let options = {",
" hostname: parsedUrl.hostname,",
" port: 443,",
" path: parsedUrl.path,",
" method: 'PUT',",
" headers: {",
" 'content-type': '',",
" 'content-length': responseBody.length",
" }",
" };",
" return new Promise((resolve, reject) => {",
" const clientRequest = https.request(options, incomingMessage => { ",
" let response = {",
" statusCode: incomingMessage.statusCode,",
" statusMessage: incomingMessage.statusMessage,",
" headers: incomingMessage.headers,",
" body: []",
" };",
" incomingMessage.on('data', chunk => {",
" response.body.push(chunk);",
" });",
" incomingMessage.on('end', () => {",
" console.log('Status code: ' + response.statusCode);",
" console.log('Status message: ' + response.statusMessage);",
" try {response.body = response.body.join(); console.log('Response Body: ' + JSON.parse(response.body));} catch(e) {}",
" return resolve(response);",
" });",
" });",
" clientRequest.on('error', error => {",
" return reject(error);",
" });",
" if (responseBody) {",
" clientRequest.write(responseBody);",
" }",
" clientRequest.end();",
" });",
"}"
]
]
}
},
"Handler": "index.handler",
"FunctionName": {
"Fn::If": [
"HasEnvironmentParameter",
{
"Fn::Join": [
"",
[
{
"Ref": "AppSyncApiName"
},
"-",
"SecuritySetup",
"-",
{
"Ref": "env"
}
]
]
},
{
"Fn::Join": [
"",
[
{
"Ref": "AppSyncApiName"
},
"-",
"SecuritySetup"
]
]
}
]
},
"Role": {
"Fn::GetAtt": [
"AppSyncFixSecurityExecutionRole",
"Arn"
]
},
"Runtime": "nodejs8.10",
"Timeout": "300"
}
},
"AppSyncFixSecurityFunctionOutputs": {
"Type": "Custom::LambdaCallout",
"Properties": {
"ServiceToken": {
"Fn::GetAtt": [
"AppSyncFixSecurityLambdaFunction",
"Arn"
]
},
"region": {
"Ref": "AWS::Region"
},
"accountId": {
"Ref": "AWS::AccountId"
},
"appsynclId": {
"Ref": "AppSyncApiId"
},
"appsyncname": {
"Fn::If": [
"HasEnvironmentParameter",
{
"Fn::Join": [
"-",
[
{
"Ref": "AppSyncApiName"
},
{
"Ref": "env"
}
]
]
},
{
"Ref": "AppSyncApiName"
}
]
}
}
}
},
"Outputs": {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment