Advertisement
Javi

AWS: Lambda with custom resource

Apr 12th, 2022
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.71 KB | None | 0 0
  1. const aws = require('aws-sdk');
  2. const s3 = new aws.S3();
  3. const { configure, sendSuccess, sendFailure, sendResponse, LOG_VERBOSE } = require('./cfn-custom-resource.js');
  4.  
  5. configure({ logLevel: LOG_VERBOSE });
  6.  
  7. function generatePhysicalId(resourceProperties) {
  8. return `cfexample-${resourceProperties.BucketName}-${resourceProperties.Countdown}`;
  9. }
  10.  
  11. async function createObjectResource(bucketName, countdown) {
  12. let data = '';
  13. for (let i=0; i < countdown; i++) {
  14. data = data + i + '\r\n';
  15. }
  16.  
  17. const objectKey = `data-${countdown}.txt`;
  18. const s3Path = `s3://${bucketName}/${objectKey}`;
  19. console.log(`Creating objetct on S3: ${s3Path}.`);
  20.  
  21. const params = {
  22. Bucket : bucketName,
  23. Key : objectKey,
  24. Body : data
  25. };
  26. const result = await s3.putObject(params).promise();
  27.  
  28. return {
  29. props : {
  30. DataFile : s3Path,
  31. Metadata : JSON.stringify(result)
  32. }
  33. };
  34. }
  35.  
  36. async function deleteObjectResource(bucketName, countdown) {
  37. let objectKey = `data-${countdown}.txt`;
  38. const s3Path = `s3://${bucketName}/${objectKey}`;
  39. console.log(`Deleting objetct on S3: ${s3Path}.`);
  40.  
  41. const params = {
  42. Bucket : bucketName,
  43. Key : objectKey
  44. };
  45. const result = await s3.deleteObject(params).promise();
  46.  
  47. return {
  48. props : {
  49. DataFile : `s3://${bucketName}/${objectKey}`,
  50. Metadata : JSON.stringify(result)
  51. }
  52. };
  53. }
  54.  
  55. exports.handler = async (event) => {
  56. console.log(`Event payload: ${JSON.stringify(event)}.`);
  57. const physicalResourceId =
  58. generatePhysicalId(event.ResourceProperties);
  59. try {
  60. let result;
  61. if (event.RequestType === 'Create') {
  62. console.info(`New Create event received.`);
  63. result = await createObjectResource(event.ResourceProperties.BucketName, event.ResourceProperties.Countdown);
  64. } else if (event.RequestType === 'Update') {
  65. console.info(`New Update event received.`);
  66. // Only the creation of the new object is required: by changing the physical name of the
  67. // resource, a Delete event for the old version will be triggered
  68. result = await createObjectResource(event.ResourceProperties.BucketName, event.ResourceProperties.Countdown);
  69. } else if (event.RequestType === 'Delete') {
  70. console.info(`New Delete event received.`);
  71. result = await deleteObjectResource(event.ResourceProperties.BucketName, event.ResourceProperties.Countdown);
  72. } else {
  73. throw `Not supported request type: ${event.RequestType}.`;
  74. }
  75. console.log(`Operation completed succesfully. Notifying Cloudformation.`);
  76. await sendSuccess(physicalResourceId, result, event);
  77. } catch (err) {
  78. console.error(`Failed to execute the request. Event <<${JSON.stringify(event)}>> Error <<${JSON.stringify(err)}>>`);
  79. await sendFailure(physicalResourceId, {Error : err}, event);
  80. }
  81.  
  82. };
  83.  
  84.  
  85.  
  86.  
  87.  
  88. /*
  89.  
  90. - Create the bucket (custom-resource-example) or delete its content if exists
  91. - Create the lambda
  92. - Make https://github.com/jgriepentrog/cfn-custom-resource available as file
  93. - Provide permissions to write to s3
  94. - Update the cloudformation templates with the ARN of the lambda
  95. - Update the cloudformation templates with the name of the bucket
  96.  
  97. */
  98.  
  99. /*
  100.  
  101. cat << EOF > v1.yaml
  102. AWSTemplateFormatVersion: 2010-09-09
  103.  
  104. Resources:
  105. CountdownResource:
  106. Type: 'Custom::CountdownResource'
  107. Version: '1.0'
  108. Properties:
  109. ServiceToken: arn:aws:lambda:eu-west-1:436628946705:function:cf-custom-resource-example
  110. BucketName : custom-resource-example
  111. Countdown : 100
  112. EOF
  113.  
  114. cat << EOF > v2.yaml
  115. AWSTemplateFormatVersion: 2010-09-09
  116.  
  117. Resources:
  118. CountdownResource:
  119. Type: 'Custom::CountdownResource'
  120. Version: '1.0'
  121. Properties:
  122. ServiceToken: arn:aws:lambda:eu-west-1:436628946705:function:cf-custom-resource-example
  123. BucketName : custom-resource-example
  124. Countdown : 50
  125. EOF
  126.  
  127.  
  128. // Open the lambda logs
  129. aws s3 ls s3://custom-resource-example
  130. aws cloudformation create-stack --stack-name cr-demo --template-body file://v1.yaml
  131. aws s3 ls s3://custom-resource-example
  132. aws cloudformation create-change-set --stack-name cr-demo --change-set-name cr-demo-1-2 --template-body file://v2.yaml
  133. aws cloudformation describe-change-set --stack-name cr-demo --change-set-name cr-demo-1-2
  134. aws cloudformation update-stack --stack-name cr-demo --template-body file://v2.yaml
  135. aws s3 ls s3://custom-resource-example
  136. aws cloudformation delete-stack --stack-name cr-demo
  137. aws s3 ls s3://custom-resource-example
  138.  
  139. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement