Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor and add new services #10

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,6 @@ typings/

# next.js build output
.next

# IDE
.idea/
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,20 @@ plugins:

### Suported AWS resources
```
AWS::Lambda::Function
AWS::SQS::Queue
AWS::Kinesis::Stream
AWS::DynamoDB::Table
AWS::S3::Bucket
AWS::ApiGateway::RestApi
AWS::ApiGateway::Stage
AWS::ApiGatewayV2::Api
AWS::ApiGatewayV2::Stage
AWS::CloudFront::Distribution
AWS::DynamoDB::Table
AWS::IAM::Role
AWS::Kinesis::Stream
AWS::Lambda::Function
AWS::Logs::LogGroup
AWS::S3::Bucket
AWS::SNS::Topic
AWS::SQS::Queue
AWS::SSM::Parameter
AWS::StepFunctions::StateMachine
AWS::WAFv2::WebACL
```
151 changes: 70 additions & 81 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,112 +1,101 @@
'use strict';

const _ = require('underscore');

class ServerlessPlugin {
constructor(serverless, options) {
constructor(serverless) {
this.serverless = serverless;
this.options = options || {};
this.provider = serverless ? serverless.getProvider('aws') : null;
this.service = serverless.service;
this.stage = null;
this.region = null;
this.isApiGatewayStageAvailableInTemplate = false;
this.supportedTypes = [
"AWS::Lambda::Function",
"AWS::SQS::Queue",
"AWS::Kinesis::Stream",
"AWS::DynamoDB::Table",
"AWS::S3::Bucket",
"AWS::ApiGateway::Stage",
"AWS::CloudFront::Distribution",
"AWS::Logs::LogGroup"
this.listTagsResources = [
'AWS::ApiGateway::RestApi',
'AWS::ApiGateway::Stage',
'AWS::CloudFront::Distribution',
'AWS::DynamoDB::Table',
'AWS::IAM::Role',
'AWS::Kinesis::Stream',
'AWS::Lambda::Function',
'AWS::Logs::LogGroup',
'AWS::S3::Bucket',
'AWS::SNS::Topic',
'AWS::SQS::Queue',
'AWS::StepFunctions::StateMachine',
'AWS::WAFv2::WebACL',
];
this.objectTagsResources = [
'AWS::ApiGatewayV2::Api',
'AWS::ApiGatewayV2::Stage',
'AWS::SSM::Parameter',
];

if (!this.provider) {
throw new Error('This plugin must be used with AWS');
}

this.hooks = {
'deploy:finalize': this._addAPIGatewayStageTags.bind(this),
'after:deploy:deploy': this._addTagsToResource.bind(this),
'after:aws:package:finalize:mergeCustomProviderResources': this._addTagsToResource.bind(this)
'after:aws:package:finalize:mergeCustomProviderResources': this._addTagsToResources.bind(this),
};
}

_addTagsToResource() {
var stackTags = [];
var self = this;
const template = this.serverless.service.provider.compiledCloudFormationTemplate;


this.stage = this.serverless.service.provider.stage;
if (this.options.stage) {
this.stage = this.options.stage;
_addTagsToResources() {
const stackTags = this._getStackTags();
if (stackTags.length === 0) {
this.serverless.cli.log('No stack tags, not updating AWS resource tags');
return;
}

this.region = this.serverless.service.provider.region;
if (this.options.region) {
this.region = this.options.region;
}
const template = this.serverless.service.provider.compiledCloudFormationTemplate;

if (typeof this.serverless.service.provider.stackTags === 'object') {
var tags = this.serverless.service.provider.stackTags
Object.keys(tags).forEach(function (key) {
stackTags.push({ "Key": key, "Value": tags[key] })
});
}
Object.keys(template.Resources).forEach((key) => {
const resourceType = template.Resources[key]['Type'];
const properties = template.Resources[key]['Properties'];

Object.keys(template.Resources).forEach(function (key) {
var resourceType = template.Resources[key]['Type']
if ((self.supportedTypes.indexOf(resourceType) !== -1) && Array.isArray(stackTags) && stackTags.length > 0) {
if (template.Resources[key]['Properties']) {
var tags = template.Resources[key]['Properties']['Tags']
if (tags) {
template.Resources[key]['Properties']['Tags'] = tags.concat(stackTags.filter(obj => (self._getTagNames(tags).indexOf(obj["Key"]) === -1)))
} else {
template.Resources[key]['Properties']['Tags'] = stackTags
}
} else {
self.serverless.cli.log('Properties not available for ' + resourceType);
if (properties) {
if (this.listTagsResources.includes(resourceType)) {
const resourceTags = this._readTagsFromList(properties['Tags']);
properties['Tags'] = this._mergeTags(resourceTags, stackTags);
} else if (this.objectTagsResources.includes(resourceType)) {
const resourceTags = this._readTagsFromObject(properties['Tags']);
properties['Tags'] = this._tagsListToObject(this._mergeTags(resourceTags, stackTags));
}
}

//Flag to avoid _addAPIGatewayStageTags() call if stage config is available in serverless.yml
if (resourceType === "AWS::ApiGateway::Stage") {
self.isApiGatewayStageAvailableInTemplate = true;
}
});
self.serverless.cli.log('Updated AWS resource tags..');

this.serverless.cli.log('Updated AWS resource tags');
}

_addAPIGatewayStageTags() {
var self = this;
var stackName = this.provider.naming.getStackName();
if (!self.isApiGatewayStageAvailableInTemplate) {
return this.provider.request('CloudFormation', 'describeStackResources', { StackName: stackName })
.then(function (resp) {
var promiseStack = [];
_.each(_.filter(resp.StackResources, resource => resource.ResourceType === 'AWS::ApiGateway::RestApi'), function (resource) {
var apiStageParams = {
resourceArn: 'arn:aws:apigateway:' + self.region + '::/restapis/' + resource.PhysicalResourceId + '/stages/' + self.stage,
tags: self.service.provider.stackTags
};
promiseStack.push(self.provider.request('APIGateway', 'tagResource', apiStageParams))
});
return Promise.all(promiseStack).then(resp => self.serverless.cli.log('Updated APIGateway resource tags..'));
});
} else {
self.serverless.cli.log('APIGateway stage already available in serverless.yml. Tag update skipped.');
return null;
_readTagsFromList(tags) {
return tags || [];
}

_readTagsFromObject(tags) {
if (!tags) {
return [];
}

return Object.keys(tags).map(key => ({
Key: key,
Value: tags[key],
}));
}

_getTagNames(srcArray) {
var tagNames = []
srcArray.forEach(function (element) {
tagNames.push(element["Key"])
});
return tagNames
_tagsListToObject(tags) {
return tags.reduce((acc, tag) => {
acc[tag['Key']] = tag['Value'];
return acc;
}, {});
}

_mergeTags(resourceTags, stackTags) {
return [
...resourceTags,
...stackTags.filter(tag => !resourceTags.map(t => t['Key']).includes(tag['Key'])),
];
}

_getStackTags() {
if (typeof this.serverless.service.provider.stackTags === 'object') {
return this._readTagsFromObject(this.serverless.service.provider.stackTags);
}
return [];
}
}

Expand Down
12 changes: 2 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 1 addition & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,5 @@
"bugs": {
"url": "https://github.com/ilayanambi86/serverless-plugin-resource-tagging/issues"
},
"homepage": "https://github.com/ilayanambi86/serverless-plugin-resource-tagging#readme",
"dependencies": {
"user": "0.0.0",
"underscore": "^1.12.1"
}
"homepage": "https://github.com/ilayanambi86/serverless-plugin-resource-tagging#readme"
}