├── src ├── test │ ├── resources │ │ ├── test-projects │ │ │ └── basic-test │ │ │ │ ├── lambda-test-0.0.1-SNAPSHOT.jar │ │ │ │ └── basic-pom.xml │ │ └── lambda-configuration-test.json │ └── java │ │ └── com │ │ └── github │ │ └── seanroy │ │ └── plugins │ │ ├── JsonUtilTest.java │ │ └── LambdaTest.java └── main │ └── java │ └── com │ └── github │ └── seanroy │ ├── plugins │ ├── UpdateLambdaCodeMojo.java │ ├── DeleteLambdaMojo.java │ ├── Trigger.java │ ├── LambdaFunction.java │ ├── AbstractLambdaMojo.java │ └── DeployLambdaMojo.java │ └── utils │ ├── AWSEncryption.java │ └── JsonUtil.java ├── .gitignore ├── CONTRIBUTING.md ├── .project ├── NOTICE ├── .classpath ├── pom.xml ├── LICENSE └── README.md /src/test/resources/test-projects/basic-test/lambda-test-0.0.1-SNAPSHOT.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SeanRoy/lambda-maven-plugin/HEAD/src/test/resources/test-projects/basic-test/lambda-test-0.0.1-SNAPSHOT.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # ignore .class 2 | *.class 3 | .settings 4 | *.asc 5 | *.jar 6 | *.swp 7 | .idea 8 | *.iml 9 | target 10 | pom.xml.versionsBackup 11 | src/test/resources/test-project/basic-pom.xml 12 | /bin/ 13 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | If you are interested in contributing to this project, please note that current development can be found in the SNAPSHOT branch of the coming release. When making pull requests, please create them against this branch. 2 | 3 | A test harness has been provided which can be run with mvn test Please use this and feel free to add additional tests. Note that the basic-pom.xml file requires you to add your role arn in order to work. As such, basic-pom.xml has been added to .gitignore so that you don't accidentally commit your role to the file. If you add more pom's as part of enhancing the test suite, please remember to add them to .gitignore. 4 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | lambda-maven-plugin 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.m2e.core.maven2Nature 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/test/resources/lambda-configuration-test.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "functionName": "flowlab-example-lambda", 4 | "description": "Receives input and logs it", 5 | "handler": "no.flowlab.ExampleLambda", 6 | "lambdaRoleArn": "arn:aws:iam::280237693431:role/lambda_basic_execution", 7 | "triggers": [ 8 | { 9 | "integration": "SNS", 10 | "SNSTopic": "flowlab-example-in" 11 | }, 12 | { 13 | "integration": "CloudWatch Events - Schedule", 14 | "ruleName": "flowlab-example-every-5-minutes", 15 | "ruleDescription": "Drain queue", 16 | "scheduleExpression": "rate(5 minutes)" 17 | }, 18 | { 19 | "integration": "Alexa Skills Kit" 20 | } 21 | ], 22 | "environmentVariables": { 23 | "key0": "value0", 24 | "key1": "key1" 25 | } 26 | }, 27 | { 28 | "functionName": "flowlab-example-lambda1", 29 | "description": "Receives input and logs it", 30 | "handler": "no.flowlab.ExampleLambda0" 31 | } 32 | ] 33 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Lambda Maven plugin 2 | Copyright 2022 Sean N. Roy 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | 16 | This product includes software developed by Sean N. Roy which enables 17 | the user to automate deployment of AWS Lambda code functions. 18 | 19 | Class Names: com.github.seanroy.plugins.AbstractLambdaMojo.class 20 | com.github.seanroy.plugins.DeleteLambdaMojo.class 21 | com.github.seanroy.plugins.DeployLambdaMojo.class 22 | 23 | Portions of this product make use of SDKs provided by 24 | Amazon (AWS API) and Apache Software Foundation. 25 | -------------------------------------------------------------------------------- /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/main/java/com/github/seanroy/plugins/UpdateLambdaCodeMojo.java: -------------------------------------------------------------------------------- 1 | package com.github.seanroy.plugins; 2 | 3 | import com.amazonaws.services.lambda.model.GetFunctionRequest; 4 | import com.amazonaws.services.lambda.model.ResourceNotFoundException; 5 | import org.apache.maven.plugin.MojoExecutionException; 6 | import org.apache.maven.plugins.annotations.Mojo; 7 | 8 | import java.util.function.Function; 9 | 10 | /** 11 | * I am a update code mojo responsible to update lambda function code in AWS. 12 | * 13 | * @author Joseph Wortmann, Joseph Wortmann 2/1/2018. 14 | */ 15 | @Mojo(name = "update-lambda-code") 16 | public class UpdateLambdaCodeMojo extends AbstractLambdaMojo { 17 | 18 | @Override 19 | public void execute() throws MojoExecutionException { 20 | if(checkSkip()) return; 21 | super.execute(); 22 | try { 23 | uploadJarToS3(); 24 | lambdaFunctions.stream().map(f -> { 25 | getLog().info("---- Update function code " + f.getFunctionName() + " -----"); 26 | return f; 27 | }).forEach(lf -> updateFunctionCodeIfExists.apply(lf)); 28 | } catch (Exception e) { 29 | getLog().error("Error during processing", e); 30 | throw new MojoExecutionException(e.getMessage()); 31 | } 32 | } 33 | 34 | private Function updateFunctionCodeIfExists = (LambdaFunction lambdaFunction) -> { 35 | try { 36 | lambdaFunction.setFunctionArn(lambdaClient.getFunction( 37 | new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName())).getConfiguration().getFunctionArn()); 38 | updateFunctionCode.apply(lambdaFunction); 39 | } catch (ResourceNotFoundException e) { 40 | getLog().info("Lambda function not found", e); 41 | } 42 | return lambdaFunction; 43 | }; 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/github/seanroy/utils/AWSEncryption.java: -------------------------------------------------------------------------------- 1 | package com.github.seanroy.utils; 2 | 3 | import com.amazonaws.encryptionsdk.AwsCrypto; 4 | import com.amazonaws.encryptionsdk.CryptoResult; 5 | import com.amazonaws.encryptionsdk.kms.KmsMasterKey; 6 | import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider; 7 | 8 | /** 9 | * A simple encryption module that allows for the encryption/decryption of strings using AWS KMS 10 | * encryption keys. This code is mostly taken from amazon example code. 11 | * @author sean 12 | * 13 | */ 14 | public class AWSEncryption { 15 | private String keyArn; 16 | 17 | public AWSEncryption(String keyArn) { 18 | this.keyArn = keyArn; 19 | } 20 | 21 | public String encryptString(String data) { 22 | // Instantiate the SDK 23 | final AwsCrypto crypto = AwsCrypto.builder().build(); 24 | 25 | // Set up the KmsMasterKeyProvider backed by the default credentials 26 | final KmsMasterKeyProvider prov = KmsMasterKeyProvider.builder().buildStrict(keyArn); 27 | 28 | return crypto.encryptString(prov, data).getResult(); 29 | } 30 | 31 | public String decryptString(String cipherText) { 32 | // Instantiate the SDK 33 | final AwsCrypto crypto = AwsCrypto.builder().build(); 34 | 35 | // Set up the KmsMasterKeyProvider backed by the default credentials 36 | final KmsMasterKeyProvider prov = KmsMasterKeyProvider.builder().buildStrict(keyArn); 37 | 38 | // Decrypt the data 39 | final CryptoResult decryptResult = crypto.decryptString(prov, cipherText); 40 | 41 | // Before returning the plaintext, verify that the customer master key that 42 | // was used in the encryption operation was the one supplied to the master key provider. 43 | if (!decryptResult.getMasterKeyIds().get(0).equals(keyArn)) { 44 | throw new IllegalStateException("Wrong encryption key ARN!"); 45 | } 46 | 47 | return decryptResult.getResult(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/github/seanroy/utils/JsonUtil.java: -------------------------------------------------------------------------------- 1 | package com.github.seanroy.utils; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.core.type.TypeReference; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.github.seanroy.plugins.LambdaFunction; 7 | 8 | import java.io.IOException; 9 | import java.util.List; 10 | 11 | import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY; 12 | import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; 13 | import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; 14 | import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD; 15 | import static com.fasterxml.jackson.annotation.PropertyAccessor.GETTER; 16 | import static com.fasterxml.jackson.annotation.PropertyAccessor.IS_GETTER; 17 | import static com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES; 18 | import static com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES; 19 | import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; 20 | import static com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS; 21 | import static com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS; 22 | 23 | /** 24 | * I am serializing and deserializing classes to/from json. 25 | * 26 | * @author Krzysztof Grodzicki 06/08/16. 27 | */ 28 | public class JsonUtil { 29 | public static final ObjectMapper mapper = new ObjectMapper() 30 | .setVisibility(FIELD, ANY) 31 | .setVisibility(GETTER, NONE) 32 | .setVisibility(IS_GETTER, NONE) 33 | .enable(ALLOW_UNQUOTED_FIELD_NAMES) 34 | .enable(ALLOW_SINGLE_QUOTES) 35 | .disable(FAIL_ON_UNKNOWN_PROPERTIES) 36 | .disable(WRITE_DATES_AS_TIMESTAMPS) 37 | .disable(WRITE_DATE_KEYS_AS_TIMESTAMPS) 38 | .setSerializationInclusion(NON_NULL); 39 | 40 | private JsonUtil() { 41 | } 42 | 43 | public static String toJson(Object message) throws JsonProcessingException { 44 | return mapper.writeValueAsString(message); 45 | } 46 | 47 | public static T fromJson(String body) throws IOException { 48 | return (T) mapper.readValue(body, new TypeReference>(){}); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/test/java/com/github/seanroy/plugins/JsonUtilTest.java: -------------------------------------------------------------------------------- 1 | package com.github.seanroy.plugins; 2 | 3 | import org.apache.commons.io.IOUtils; 4 | import org.junit.Test; 5 | 6 | import com.github.seanroy.utils.JsonUtil; 7 | 8 | import java.io.IOException; 9 | import java.util.Arrays; 10 | import java.util.HashMap; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | import static org.junit.Assert.assertTrue; 15 | 16 | /** 17 | * @author Krzysztof Grodzicki 11/08/16. 18 | */ 19 | public class JsonUtilTest { 20 | 21 | @Test 22 | public void testFromJson() throws IOException { 23 | String json = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("lambda-configuration-test.json")); 24 | 25 | List lambdaFunctions = JsonUtil.fromJson(json); 26 | 27 | assertTrue(lambdaFunctions.size() == 2); 28 | } 29 | 30 | @Test 31 | public void testGenerateConfiguration() throws IOException { 32 | LambdaFunction lambdaFunction0 = build("LambdaFunction0", "Test description 0", "com.kgrodzicki.Lambda0", environmentVariablesMock()); 33 | LambdaFunction lambdaFunction1 = build("LambdaFunction1", "Test description 1", "com.kgrodzicki.Lambda1", environmentVariablesMock()); 34 | 35 | List lambdaFunctions = Arrays.asList(lambdaFunction0, lambdaFunction1); 36 | String json = JsonUtil.toJson(lambdaFunctions); 37 | 38 | assertTrue(json.contains("[{\"functionName\":\"LambdaFunction0\",\"description\":\"Test description 0\",\"handler\":\"com.kgrodzicki.Lambda0\",\"environmentVariables\"" 39 | + ":{\"key1\":\"value1\",\"key0\":\"value0\"}},{\"functionName\":\"LambdaFunction1\",\"description\":\"Test description 1\"," 40 | + "\"handler\":\"com.kgrodzicki.Lambda1\",\"environmentVariables\":{\"key1\":\"value1\",\"key0\":\"value0\"}}]")); 41 | assertTrue(JsonUtil.fromJson(json) != null); 42 | } 43 | 44 | private LambdaFunction build(String functionName, String description, String handler, Map environmentVariables) { 45 | return new LambdaFunction() 46 | .withFunctionName(functionName) 47 | .withDescription(description) 48 | .withHandler(handler) 49 | .withEnvironmentVariables(environmentVariables); 50 | } 51 | 52 | private Map environmentVariablesMock() { 53 | HashMap result = new HashMap<>(); 54 | result.put("key0", "value0"); 55 | result.put("key1", "value1"); 56 | return result; 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/test/java/com/github/seanroy/plugins/LambdaTest.java: -------------------------------------------------------------------------------- 1 | package com.github.seanroy.plugins; 2 | 3 | import static java.util.Optional.of; 4 | 5 | import java.io.File; 6 | 7 | import org.apache.maven.plugin.MojoExecutionException; 8 | import org.apache.maven.plugin.testing.AbstractMojoTestCase; 9 | import org.junit.Test; 10 | 11 | import com.amazonaws.auth.AWSCredentials; 12 | import com.amazonaws.auth.BasicAWSCredentials; 13 | import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; 14 | import com.amazonaws.regions.Regions; 15 | import com.amazonaws.services.lambda.AWSLambdaClient; 16 | 17 | public class LambdaTest extends AbstractMojoTestCase { 18 | 19 | private AWSCredentials credentials; 20 | public AWSLambdaClient lambdaClient; 21 | private String accessKey = null; 22 | private String secretKey = null; 23 | private String regionName = "us-east-1"; 24 | 25 | protected void setUp() 26 | throws Exception 27 | { 28 | super.setUp(); 29 | 30 | Regions region = Regions.fromName(regionName); 31 | 32 | DefaultAWSCredentialsProviderChain defaultChain = new DefaultAWSCredentialsProviderChain(); 33 | if (accessKey != null && secretKey != null) { 34 | credentials = new BasicAWSCredentials(accessKey, secretKey); 35 | } else if (defaultChain.getCredentials() != null) { 36 | credentials = defaultChain.getCredentials(); 37 | } 38 | 39 | if (credentials == null) { 40 | throw new MojoExecutionException("AWS Credentials config error"); 41 | } 42 | 43 | lambdaClient = of(credentials) 44 | .map(credentials -> new AWSLambdaClient(credentials).withRegion(region)) 45 | .orElse(new AWSLambdaClient().withRegion(region)); 46 | } 47 | 48 | protected void tearDown() 49 | throws Exception 50 | { 51 | super.tearDown(); 52 | } 53 | 54 | @Test 55 | public void testNOOP() { 56 | assertTrue(true); 57 | } 58 | 59 | @Test 60 | public void testBasic() throws Exception { 61 | File pom = getTestFile("src/test/resources/test-projects/basic-test/basic-pom.xml"); 62 | assertNotNull( pom ); 63 | assertTrue( pom.exists() ); 64 | 65 | DeployLambdaMojo lambduhMojo = (DeployLambdaMojo) lookupMojo( "deploy-lambda", pom ); 66 | assertNotNull( lambduhMojo ); 67 | lambduhMojo.execute(); 68 | 69 | UpdateLambdaCodeMojo updateMojo = (UpdateLambdaCodeMojo) lookupMojo( "update-lambda-code", pom); 70 | assertNotNull( updateMojo ); 71 | updateMojo.execute(); 72 | 73 | DeleteLambdaMojo deleteMojo = (DeleteLambdaMojo) lookupMojo( "delete-lambda", pom); 74 | assertNotNull( deleteMojo ); 75 | deleteMojo.execute(); 76 | 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/test/resources/test-projects/basic-test/basic-pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | 6 | org.apache.maven.plugin.my.unit 7 | test-project 8 | 1.0-SNAPSHOT 9 | jar 10 | Test Lambduh 11 | 12 | 13 | 14 | junit 15 | junit 16 | 3.8.1 17 | test 18 | 19 | 20 | com.github.seanroy 21 | lambduh-maven-annotations 22 | 1.0.0 23 | 24 | 25 | 26 | 27 | 28 | 29 | lambda-maven-plugin 30 | 31 | false 32 | src/test/resources/test-projects/basic-test/lambda-test-0.0.1-SNAPSHOT.jar 33 | 0.1.1-Test 34 | 512 35 | us-east-1 36 | java8 37 | lambda-function-code 38 | 60 39 | arn:aws:iam::280237693431:role/lambda_basic_execution 40 | 41 | [ 42 | { 43 | "functionName": "HelloWorld", 44 | "description": "HelloWorld Test Function", 45 | "handler": "com.github.seanroy.lambduh_test::hello_world", 46 | "timeout": 30, 47 | "memorySize": 512, 48 | "keepAlive": 2, 49 | "triggers": [ 50 | { 51 | "integration": "CloudWatch Events - Schedule", 52 | "ruleName": "every-minute", 53 | "ruleDescription": "foo z bar", 54 | "scheduleExpression": "rate(1 minute)" 55 | }, 56 | { 57 | "integration": "CloudWatch Events - Schedule", 58 | "ruleName": "every-other-minute", 59 | "ruleDescription": "this does it every other minute.", 60 | "scheduleExpression": "rate(13 minutes)" 61 | } 62 | ] 63 | }, 64 | { 65 | "functionName": "GoodbyeWorld", 66 | "description": "GoodByeWorld Test function", 67 | "handler": "com.github.seanroy.lambduh_test::goodbye_world", 68 | "timeout": 45, 69 | "memorySize": 256, 70 | "topics": [], 71 | "triggers": [] 72 | } 73 | ] 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /src/main/java/com/github/seanroy/plugins/DeleteLambdaMojo.java: -------------------------------------------------------------------------------- 1 | package com.github.seanroy.plugins; 2 | 3 | 4 | import java.util.List; 5 | import java.util.function.Function; 6 | 7 | import org.apache.maven.plugin.MojoExecutionException; 8 | import org.apache.maven.plugins.annotations.Mojo; 9 | 10 | import com.amazonaws.services.cloudwatchevents.model.DeleteRuleRequest; 11 | import com.amazonaws.services.cloudwatchevents.model.ListRuleNamesByTargetRequest; 12 | import com.amazonaws.services.cloudwatchevents.model.RemoveTargetsRequest; 13 | import com.amazonaws.services.lambda.model.DeleteFunctionRequest; 14 | import com.amazonaws.services.lambda.model.GetFunctionRequest; 15 | 16 | 17 | 18 | 19 | /** 20 | * I am a delete mojo responsible for deleteing lambda function configuration and code from AWS. 21 | * 22 | * @author Sean N. Roy 23 | */ 24 | @Mojo(name = "delete-lambda") 25 | public class DeleteLambdaMojo extends AbstractLambdaMojo { 26 | 27 | /** 28 | * The entry point into the AWS lambda function. 29 | */ 30 | public void execute() throws MojoExecutionException { 31 | if(checkSkip()) return; 32 | super.execute(); 33 | try { 34 | lambdaFunctions.forEach(context -> { 35 | try { 36 | deleteTriggers.andThen(deleteFunction).apply( 37 | context.withFunctionArn(lambdaClient.getFunction(new GetFunctionRequest() 38 | .withFunctionName(context.getFunctionName())).getConfiguration().getFunctionArn())); 39 | } catch (Exception e) { 40 | getLog().error(e.getMessage()); 41 | } 42 | }); 43 | } catch (Exception e) { 44 | getLog().error(e.getMessage(), e); 45 | } 46 | } 47 | 48 | private Function deleteDynamoDBTrigger = lambdaFunction -> {return lambdaFunction;}; 49 | private Function deleteKinesisTrigger = lambdaFunction -> {return lambdaFunction;}; 50 | private Function deleteSNSTrigger = lambdaFunction -> {return lambdaFunction;}; 51 | private Function deleteAlexaSkillsTrigger = lambdaFunction -> {return lambdaFunction;}; 52 | private Function deleteSQSTrigger = lambdaFunction -> {return lambdaFunction;}; 53 | 54 | 55 | /* 56 | * Delete cloudwatch event rules. 57 | */ 58 | private Function deleteCloudWatchEventRules = lambdaFunction -> { 59 | // Get the list of cloudwatch event rules defined for this function (if any). 60 | List existingRuleNames = cloudWatchEventsClient.listRuleNamesByTarget(new ListRuleNamesByTargetRequest() 61 | .withTargetArn(lambdaFunction.getFunctionArn())).getRuleNames(); 62 | 63 | existingRuleNames.stream().forEach(ern -> { 64 | getLog().info(" Deleting CloudWatch Event Rule: " + ern); 65 | cloudWatchEventsClient.removeTargets(new RemoveTargetsRequest() 66 | .withIds("1") 67 | .withRule(ern)); 68 | try { 69 | cloudWatchEventsClient.deleteRule(new DeleteRuleRequest().withName(ern)); 70 | } catch (Exception e) { 71 | getLog().info(" Could not delete orphaned rule: " + e.getMessage()); 72 | } 73 | }); 74 | 75 | return lambdaFunction; 76 | }; 77 | 78 | /** 79 | * Deletes the lambda function from AWS Lambda and removes the function code 80 | * package from S3. 81 | *

82 | * TODO: Make this more sophisticated by checking for the existence of the 83 | * TODO: resources first, or reacting to the ResourceNotFoundException. I 84 | * TODO: prefer the first option. 85 | *

86 | * 87 | * @param functionName to delete 88 | * @throws Exception the exception from AWS API 89 | */ 90 | private Function deleteFunction = context -> { 91 | String functionName = context.getFunctionName(); 92 | 93 | // Delete Lambda Function 94 | DeleteFunctionRequest dfr = new DeleteFunctionRequest().withFunctionName(functionName); 95 | 96 | lambdaClient.deleteFunction(dfr); 97 | getLog().info("Lambda function " + functionName + " successfully deleted."); 98 | 99 | s3Client.deleteObject(s3Bucket, fileName); 100 | getLog().info("Lambda function code successfully removed from S3."); 101 | 102 | return context; 103 | }; 104 | 105 | /** 106 | * For every Integration, ie Trigger, andThen a delete function for it here. 107 | */ 108 | private Function deleteTriggers = lambdaFunction -> { 109 | return deleteCloudWatchEventRules 110 | .andThen(deleteDynamoDBTrigger) 111 | .andThen(deleteKinesisTrigger) 112 | .andThen(deleteSNSTrigger) 113 | .andThen(deleteAlexaSkillsTrigger) 114 | .andThen(deleteSQSTrigger) 115 | .apply(lambdaFunction); 116 | }; 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/github/seanroy/plugins/Trigger.java: -------------------------------------------------------------------------------- 1 | package com.github.seanroy.plugins; 2 | 3 | /** 4 | * I am a Trigger. 5 | * 6 | * @author Krzysztof Grodzicki 12/10/16. 7 | */ 8 | public class Trigger { 9 | // By now can be "DynamoDB" or "CloudWatch Events - Schedule" 10 | // SQS for Simple Queue Service 11 | private String integration; 12 | 13 | // Support for DynamoDB 14 | private String dynamoDBTable; 15 | private Integer batchSize; 16 | 17 | // Support for Kinesis Streams 18 | private String kinesisStream; 19 | 20 | /** 21 | *

Starting position.

22 | */ 23 | private String startingPosition; 24 | 25 | // Support for CloudWatch Events - Schedule 26 | private String ruleName; 27 | private String ruleDescription; 28 | private String scheduleExpression; 29 | 30 | // Support for SNS 31 | private String SNSTopic; 32 | 33 | // Support for Lex Bots 34 | private String lexBotName; 35 | 36 | // Support for SQS 37 | // SQS Trigger requires batch size as well, it is already 38 | // created as part of Dynamo DB Table 39 | private String standardQueue; 40 | 41 | // Support for Alexa Skills Kit 42 | private String alexaSkillId; 43 | 44 | // After create Trigger gets own arn 45 | private String triggerArn; 46 | 47 | private Boolean enabled; 48 | 49 | public Trigger() { 50 | } 51 | 52 | public String getIntegration() { 53 | return integration; 54 | } 55 | 56 | public void setIntegration(String integration) { 57 | this.integration = integration; 58 | } 59 | 60 | public String getDynamoDBTable() { 61 | return dynamoDBTable; 62 | } 63 | 64 | public void setDynamoDBTable(String dynamoDBTable) { 65 | this.dynamoDBTable = dynamoDBTable; 66 | } 67 | 68 | public String getKinesisStream() { 69 | return kinesisStream; 70 | } 71 | 72 | public void setKinesisStream(String kinesisStream) { 73 | this.kinesisStream = kinesisStream; 74 | } 75 | 76 | public Integer getBatchSize() { 77 | return batchSize; 78 | } 79 | 80 | public void setBatchSize(Integer batchSize) { 81 | this.batchSize = batchSize; 82 | } 83 | 84 | public String getStartingPosition() { 85 | return startingPosition; 86 | } 87 | 88 | public void setStartingPosition(String startingPosition) { 89 | this.startingPosition = startingPosition; 90 | } 91 | 92 | 93 | public String getRuleName() { 94 | return ruleName; 95 | } 96 | 97 | public void setRuleName(String ruleName) { 98 | this.ruleName = ruleName; 99 | } 100 | 101 | public String getRuleDescription() { 102 | return ruleDescription; 103 | } 104 | 105 | public void setRuleDescription(String ruleDescription) { 106 | this.ruleDescription = ruleDescription; 107 | } 108 | 109 | public String getScheduleExpression() { 110 | return scheduleExpression; 111 | } 112 | 113 | public void setScheduleExpression(String scheduleExpression) { 114 | this.scheduleExpression = scheduleExpression; 115 | } 116 | 117 | public Boolean getEnabled() { 118 | return enabled; 119 | } 120 | 121 | public void setEnabled(Boolean enabled) { 122 | this.enabled = enabled; 123 | } 124 | 125 | public String getTriggerArn() { 126 | return triggerArn; 127 | } 128 | 129 | public void setTriggerArn(String triggerArn) { 130 | this.triggerArn = triggerArn; 131 | } 132 | 133 | public String getSNSTopic() { 134 | return SNSTopic; 135 | } 136 | 137 | public void setSNSTopic(String SNSTopic) { 138 | this.SNSTopic = SNSTopic; 139 | } 140 | 141 | public void setLexBotName(String arn) { 142 | this.lexBotName = arn; 143 | } 144 | 145 | public String getLexBotName() { 146 | return lexBotName; 147 | } 148 | 149 | public String getStandardQueue() { 150 | return standardQueue; 151 | } 152 | 153 | public void setStandardQueue(String standardQueue) { 154 | this.standardQueue = standardQueue; 155 | } 156 | 157 | public String getAlexaSkillId() { 158 | return alexaSkillId; 159 | } 160 | 161 | public void setAlexaSkillId(String alexaSkillId) { 162 | this.alexaSkillId = alexaSkillId; 163 | } 164 | 165 | public Trigger withIntegration(String integration) { 166 | this.integration = integration; 167 | return this; 168 | } 169 | 170 | public Trigger withDynamoDBTable(String dynamoDBTable) { 171 | this.dynamoDBTable = dynamoDBTable; 172 | return this; 173 | } 174 | 175 | public Trigger withKinesisStream(String kinesisStream) { 176 | this.kinesisStream = kinesisStream; 177 | return this; 178 | } 179 | 180 | public Trigger withBatchSize(Integer batchSize) { 181 | this.batchSize = batchSize; 182 | return this; 183 | } 184 | 185 | public Trigger withRuleName(String ruleName) { 186 | this.ruleName = ruleName; 187 | return this; 188 | } 189 | 190 | public Trigger withDescription(String ruleDescription) { 191 | this.ruleDescription = ruleDescription; 192 | return this; 193 | } 194 | 195 | public Trigger withScheduleExpression(String scheduleExpression) { 196 | this.scheduleExpression = scheduleExpression; 197 | return this; 198 | } 199 | 200 | public Trigger withTriggerArn(String triggerArn) { 201 | this.triggerArn = triggerArn; 202 | return this; 203 | } 204 | 205 | public Trigger withSNSTopic(String sNSTopic) { 206 | this.SNSTopic = sNSTopic; 207 | return this; 208 | } 209 | 210 | public Trigger withLexBotName(String arn) { 211 | this.lexBotName = arn; 212 | return this; 213 | } 214 | 215 | public Trigger withStandardQueue(String standardQueue) { 216 | this.standardQueue = standardQueue; 217 | return this; 218 | } 219 | 220 | public Trigger withAlexaSkillId(String alexaSkillId) { 221 | this.alexaSkillId = alexaSkillId; 222 | return this; 223 | } 224 | 225 | @Override 226 | public String toString() { 227 | return new StringBuilder("Trigger{") 228 | .append("integration='").append(integration).append('\'') 229 | .append(", dynamoDBTable='").append(dynamoDBTable).append('\'') 230 | .append(", kinesisStream='").append(kinesisStream).append('\'') 231 | .append(", batchSize=").append(batchSize) 232 | .append(", startingPosition='").append(startingPosition).append('\'') 233 | .append(", ruleName='").append(ruleName).append('\'') 234 | .append(", ruleDescription='").append(ruleDescription).append('\'') 235 | .append(", scheduleExpression='").append(scheduleExpression).append('\'') 236 | .append(", SNSTopic='").append(SNSTopic).append('\'') 237 | .append(", triggerArn='").append(triggerArn).append('\'') 238 | .append(", lextBotName='").append(lexBotName).append('\'') 239 | .append(", standardQueue='").append(standardQueue).append('\'') 240 | .append(", alexaSkillId='").append(alexaSkillId).append('\'') 241 | .append(", enabled=").append(enabled) 242 | .append('}').toString(); 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /src/main/java/com/github/seanroy/plugins/LambdaFunction.java: -------------------------------------------------------------------------------- 1 | package com.github.seanroy.plugins; 2 | 3 | import static java.util.Optional.ofNullable; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | import com.amazonaws.auth.policy.Policy; 10 | import com.fasterxml.jackson.annotation.JsonIgnore; 11 | 12 | /** 13 | * I am a domain class for Lambda Function. 14 | * 15 | * @author sean, Krzysztof Grodzicki 11/08/16. 16 | */ 17 | @SuppressWarnings({"unused", "ClassWithTooManyFields", "ClassWithTooManyMethods"}) 18 | public class LambdaFunction { 19 | /** 20 | *

21 | * The existing Lambda function name whose code you want to replace. 22 | *

23 | */ 24 | private String functionName; 25 | /** 26 | *

27 | * A short user-defined function description. AWS Lambda does not use this 28 | * value. Assign a meaningful description as you see fit. 29 | *

30 | */ 31 | private String description; 32 | /** 33 | *

34 | * The function that Lambda calls to begin executing your function. For 35 | * Node.js, it is the module-name.export value in your 36 | * function. 37 | *

38 | */ 39 | private String handler; 40 | /** 41 | *

@see {@link AbstractLambdaMojo}

42 | */ 43 | private Integer memorySize; 44 | /** 45 | *

@see {@link AbstractLambdaMojo}

46 | */ 47 | private Integer timeout; 48 | /** 49 | *

@see {@link AbstractLambdaMojo}

50 | */ 51 | private String version; 52 | /** 53 | *

@see {@link AbstractLambdaMojo}

54 | */ 55 | private List securityGroupIds; 56 | /** 57 | *

@see {@link AbstractLambdaMojo}

58 | */ 59 | private List subnetIds; 60 | /** 61 | *

Lambda function aliases genereted based on publish flag.

62 | */ 63 | private List aliases; 64 | 65 | /** 66 | *

@see {@link AbstractLambdaMojo}

67 | */ 68 | private Integer keepAlive; 69 | /** 70 | *

71 | * This boolean parameter can be used to request AWS Lambda to update the 72 | * Lambda function and publish a version as an atomic operation. 73 | *

74 | */ 75 | private Boolean publish; 76 | /** 77 | *

78 | * The Amazon Resource Name (ARN) of the IAM role that Lambda will assume when it executes your function. 79 | *

80 | */ 81 | private String lambdaRoleArn; 82 | /** 83 | *

The Amazon Resource Name (ARN) assigned to the function

84 | */ 85 | private String functionArn; 86 | /** 87 | *

The triggers that generates events that Lambda responds to

88 | */ 89 | private List triggers; 90 | 91 | private Map environmentVariables; 92 | 93 | private String qualifier; 94 | 95 | @JsonIgnore 96 | private Policy existingPolicy; 97 | 98 | public Policy getExistingPolicy() { 99 | return existingPolicy; 100 | } 101 | 102 | public void setExistingPolicy(Policy existingPolicy) { 103 | this.existingPolicy = existingPolicy; 104 | } 105 | 106 | public LambdaFunction() { 107 | } 108 | 109 | public String getFunctionName() { 110 | return functionName; 111 | } 112 | 113 | public void setFunctionName(String functionName) { 114 | this.functionName = functionName; 115 | } 116 | 117 | public String getDescription() { 118 | return description; 119 | } 120 | 121 | public void setDescription(String description) { 122 | this.description = description; 123 | } 124 | 125 | public String getHandler() { 126 | return handler; 127 | } 128 | 129 | public void setHandler(String handler) { 130 | this.handler = handler; 131 | } 132 | 133 | public Integer getMemorySize() { 134 | return memorySize; 135 | } 136 | 137 | public void setMemorySize(Integer memorySize) { 138 | this.memorySize = memorySize; 139 | } 140 | 141 | public Integer getTimeout() { 142 | return timeout; 143 | } 144 | 145 | public void setTimeout(Integer timeout) { 146 | this.timeout = timeout; 147 | } 148 | 149 | public String getVersion() { 150 | return version; 151 | } 152 | 153 | public void setVersion(String version) { 154 | this.version = version; 155 | } 156 | 157 | public List getSecurityGroupIds() { 158 | if (securityGroupIds == null) { 159 | return new ArrayList<>(); 160 | } 161 | return securityGroupIds; 162 | } 163 | 164 | public void setSecurityGroupIds(List securityGroupIds) { 165 | this.securityGroupIds = securityGroupIds; 166 | } 167 | 168 | public List getSubnetIds() { 169 | if (subnetIds == null) { 170 | return new ArrayList<>(); 171 | } 172 | return subnetIds; 173 | } 174 | 175 | public void setSubnetIds(List subnetIds) { 176 | this.subnetIds = subnetIds; 177 | } 178 | 179 | public List getAliases() { 180 | return aliases; 181 | } 182 | 183 | public void setAliases(List aliases) { 184 | this.aliases = aliases; 185 | } 186 | 187 | public Boolean isPublish() { 188 | return publish; 189 | } 190 | 191 | public void setPublish(boolean publish) { 192 | this.publish = publish; 193 | } 194 | 195 | public String getLambdaRoleArn() { return lambdaRoleArn; } 196 | 197 | public void setLambdaRoleArn(String lambdaRoleArn) { this.lambdaRoleArn = lambdaRoleArn; } 198 | 199 | public String getFunctionArn() { 200 | return functionArn; 201 | } 202 | 203 | public void setKeepAlive(Integer keepAlive) { 204 | this.keepAlive = keepAlive; 205 | } 206 | 207 | public Integer getKeepAlive() { 208 | return keepAlive; 209 | } 210 | 211 | public void setQualifier(String qualifier) { 212 | this.qualifier = qualifier; 213 | } 214 | 215 | public String getQualifier() { 216 | return qualifier; 217 | } 218 | 219 | public String getUnqualifiedFunctionArn() { 220 | return ofNullable(functionArn) 221 | .map(arn -> arn.replaceAll(functionName + ".*", functionName)) 222 | .orElse(null); 223 | } 224 | 225 | public List getTriggers() { 226 | return triggers; 227 | } 228 | 229 | public void setFunctionArn(String functionArn) { 230 | this.functionArn = functionArn; 231 | } 232 | 233 | public Map getEnvironmentVariables() { 234 | return environmentVariables; 235 | } 236 | 237 | public void setEnvironmentVariables(Map environmentVariables) { 238 | this.environmentVariables = environmentVariables; 239 | } 240 | 241 | public LambdaFunction withDescription(String description) { 242 | this.description = description; 243 | return this; 244 | } 245 | 246 | public LambdaFunction withFunctionName(String functionName) { 247 | this.functionName = functionName; 248 | return this; 249 | } 250 | 251 | public LambdaFunction withHandler(String handler) { 252 | this.handler = handler; 253 | return this; 254 | } 255 | 256 | public LambdaFunction withMemorySize(Integer memorySize) { 257 | this.memorySize = memorySize; 258 | return this; 259 | } 260 | 261 | public LambdaFunction withSecurityGroupsIds(List securityGroupsIds) { 262 | this.securityGroupIds = securityGroupsIds; 263 | return this; 264 | } 265 | 266 | public LambdaFunction withSubnetIds(List subnetIds) { 267 | this.subnetIds = subnetIds; 268 | return this; 269 | } 270 | 271 | public LambdaFunction withTimeout(Integer timeout) { 272 | this.timeout = timeout; 273 | return this; 274 | } 275 | 276 | public LambdaFunction withVersion(String version) { 277 | this.version = version; 278 | return this; 279 | } 280 | 281 | public LambdaFunction withAliases(List aliases) { 282 | this.aliases = aliases; 283 | return this; 284 | } 285 | 286 | public LambdaFunction withPublish(Boolean publish) { 287 | this.publish = publish; 288 | return this; 289 | } 290 | 291 | public LambdaFunction withLambdaRoleArn(String lambdaRoleArn) { 292 | this.lambdaRoleArn = lambdaRoleArn; 293 | return this; 294 | } 295 | 296 | public LambdaFunction withFunctionArn(String functionArn) { 297 | this.functionArn = functionArn; 298 | return this; 299 | } 300 | 301 | public LambdaFunction withTriggers(List triggers) { 302 | this.triggers = triggers; 303 | return this; 304 | } 305 | 306 | public LambdaFunction withEnvironmentVariables(Map environmentVariables) { 307 | this.environmentVariables = environmentVariables; 308 | return this; 309 | } 310 | 311 | public LambdaFunction withKeepAlive(Integer keepAlive) { 312 | this.keepAlive = keepAlive; 313 | return this; 314 | } 315 | 316 | public LambdaFunction withQualifier(String qualifier) { 317 | this.qualifier = qualifier; 318 | return this; 319 | } 320 | 321 | public LambdaFunction withExistingPolicy(Policy policy) { 322 | this.existingPolicy = policy; 323 | return this; 324 | } 325 | 326 | public String getKeepAliveRuleName() { 327 | return String.format("KEEP-ALIVE-%s", getFunctionName()); 328 | } 329 | 330 | public String getKeepAliveScheduleExpression() { 331 | return String.format("rate(%d %s)", keepAlive, keepAlive > 1 ? "minutes" : "minute"); 332 | } 333 | 334 | @SuppressWarnings("StringBufferReplaceableByString") 335 | @Override 336 | public String toString() { 337 | return new StringBuilder("LambdaFunction{") 338 | .append("functionName='").append(functionName).append('\'') 339 | .append(", description='").append(description).append('\'') 340 | .append(", handler='").append(handler).append('\'') 341 | .append(", memorySize=").append(memorySize) 342 | .append(", timeout=").append(timeout) 343 | .append(", version='").append(version).append('\'') 344 | .append(", securityGroupIds=").append(securityGroupIds) 345 | .append(", subnetIds=").append(subnetIds) 346 | .append(", aliases=").append(aliases) 347 | .append(", publish=").append(publish) 348 | .append(", lambdaRoleArn=").append(lambdaRoleArn) 349 | .append(", triggers=").append(triggers) 350 | .append(", keepAlive=").append(keepAlive) 351 | .append(", environmentVariables=").append(environmentVariables) 352 | .append('}').toString(); 353 | } 354 | } 355 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | com.github.seanroy 4 | lambda-maven-plugin 5 | maven-plugin 6 | 2.3.5 7 | 8 | lambda-maven-plugin Maven Mojo 9 | A maven plugin that deploys functions to AWS Lambda 10 | https://github.com/SeanRoy/lambda-maven-plugin 11 | 12 | 13 | 14 | Apache License, Version 2.0 15 | http://www.apache.org/licenses/LICENSE-2.0.txt 16 | repo 17 | 18 | 19 | 20 | 21 | 22 | Sean N. Roy 23 | Sean.Roy@gmail.com 24 | https://github.com/SeanRoy/lambda-maven-plugin 25 | 26 | 27 | 28 | 29 | 30 | Joseph Wortmann 31 | joseph.wortmann@gmail.com 32 | 33 | 34 | Philip M. White 35 | philip@mailworks.org 36 | 37 | 38 | Guillermo Menendez 39 | 40 | 41 | Jem Rayfield 42 | jem.rayfield@ft.com 43 | 44 | 45 | Krzysztof Grodzicki 46 | krzysztof@flowlab.no 47 | 48 | 49 | 50 | 51 | 1.12.68 52 | UTF-8 53 | 54 | 55 | 56 | scm:git:git@github.com:QuiNovas/lambda-maven-plugin.git 57 | scm:git:git@github.com:QuiNovas/lambda-maven-plugin.git 58 | git@github.com:QuiNovas/lambda-maven-plugin.git 59 | 60 | 61 | 62 | 63 | org.apache.maven 64 | maven-plugin-api 65 | 3.3.3 66 | provided 67 | 68 | 69 | org.apache.maven.plugin-testing 70 | maven-plugin-testing-harness 71 | 3.3.0 72 | test 73 | 74 | 75 | org.apache.maven.plugin-tools 76 | maven-plugin-annotations 77 | 3.4 78 | provided 79 | 80 | 81 | org.apache.maven 82 | maven-compat 83 | 3.3.3 84 | provided 85 | 86 | 87 | org.apache.maven 88 | maven-core 89 | 3.3.3 90 | test 91 | 92 | 93 | maven 94 | maven-model 95 | 3.0.2.javadoc 96 | javadoc.jar 97 | test 98 | 99 | 100 | org.apache.maven 101 | maven-aether-provider 102 | 3.3.3 103 | test 104 | 105 | 106 | com.amazonaws 107 | aws-java-sdk-lambda 108 | ${aws.version} 109 | 110 | 111 | com.amazonaws 112 | aws-java-sdk-s3 113 | ${aws.version} 114 | 115 | 116 | com.amazonaws 117 | aws-java-sdk-sns 118 | ${aws.version} 119 | 120 | 121 | com.amazonaws 122 | aws-java-sdk-events 123 | ${aws.version} 124 | 125 | 126 | com.amazonaws 127 | aws-java-sdk-dynamodb 128 | ${aws.version} 129 | 130 | 131 | com.amazonaws 132 | aws-java-sdk-kinesis 133 | ${aws.version} 134 | 135 | 136 | com.amazonaws 137 | aws-java-sdk-api-gateway 138 | ${aws.version} 139 | 140 | 141 | com.amazonaws 142 | aws-java-sdk-kms 143 | ${aws.version} 144 | 145 | 146 | com.amazonaws 147 | aws-java-sdk-sqs 148 | ${aws.version} 149 | 150 | 151 | com.amazonaws 152 | aws-encryption-sdk-java 153 | 2.2.0 154 | 155 | 156 | junit 157 | junit 158 | 4.13.1 159 | test 160 | 161 | 162 | commons-codec 163 | commons-codec 164 | 1.10 165 | 166 | 167 | de.juplo 168 | scannotation 169 | 1.0.4 170 | 171 | 172 | org.apache.httpcomponents 173 | httpclient 174 | 4.5.13 175 | 176 | 177 | com.google.code.gson 178 | gson 179 | 2.8.1 180 | 181 | 182 | org.mockito 183 | mockito-core 184 | 2.10.0 185 | test 186 | 187 | 188 | 189 | 190 | 191 | ossrh 192 | https://oss.sonatype.org/content/repositories/snapshots 193 | 194 | 195 | ossrh 196 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 197 | 198 | 199 | 200 | 201 | 202 | 203 | org.apache.maven.plugins 204 | maven-compiler-plugin 205 | 3.5.1 206 | 207 | 1.8 208 | 1.8 209 | 210 | 211 | 212 | org.apache.maven.plugins 213 | maven-source-plugin 214 | 3.2.1 215 | 216 | 217 | attach-sources 218 | 219 | jar 220 | 221 | 222 | 223 | 224 | 225 | org.apache.maven.plugins 226 | maven-javadoc-plugin 227 | 3.3.2 228 | 229 | 230 | attach-javadocs 231 | 232 | jar 233 | 234 | 235 | 236 | 237 | 8 238 | 239 | 240 | 241 | org.apache.maven.plugins 242 | maven-gpg-plugin 243 | 244 | 245 | sign-artifacts 246 | verify 247 | 248 | sign 249 | 250 | 251 | 252 | 253 | 254 | org.sonatype.plugins 255 | nexus-staging-maven-plugin 256 | true 257 | 258 | ossrh 259 | https://oss.sonatype.org/ 260 | true 261 | false 262 | 263 | 264 | 265 | org.sonatype.plugins 266 | maven-version-plugin 267 | 1.0 268 | 269 | 270 | org.apache.maven.plugins 271 | maven-plugin-plugin 272 | 3.6.2 273 | 274 | 275 | default-descriptor 276 | 277 | descriptor 278 | 279 | process-classes 280 | 281 | 282 | 283 | 284 | 285 | 286 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # lambda-maven-plugin 2 | 3 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.seanroy/lambda-maven-plugin/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.seanroy/lambda-maven-plugin) 4 |
5 | ### Usage 6 | `group id: com.github.seanroy`
7 | `artifact id: lambda-maven-plugin`
8 | `version: 2.3.5`
9 |

10 | Please note that the artifact has been renamed from lambduh-maven-plugin to 11 | lambda-maven-plugin. 12 | 13 | ### Deploy from command line 14 | ``` 15 | mvn package shade:shade lambda:deploy-lambda 16 | ``` 17 | 18 | ### Delete from command line 19 | ``` 20 | mvn lambda:delete-lambda 21 | ``` 22 | 23 | ### Configuration 24 | All of the AWS Lambda configuration parameters may be set within the lambda plugin configuration or on the Maven command line using the -D directive. 25 | 26 | * `accessKey` Your user's AWS access key. 27 | * `secretKey` Your user's AWS secret access key. 28 | * `functionCode` REQUIRED The location of your deliverable. For instance, a jar file for a Java8 lambda function. 29 | * `version` REQUIRED version of the deliverable. Note that this is the version you assign to your function, not the one assigned by AWS when publish=true. 30 | * `alias` OPTIONAL, but requires publish=true. Assigns an alias to the AWS version of this function. Useful for maintaining versions intended for different environments on the same function. For instance, development, qa, production, etc. 31 | * `s3Bucket` REQUIRED Defaults to lambda-function-code. The AWS S3 bucket to which to upload your code from which it will be deployed to Lambda. 32 | * `sse` OPTIONAL Turns on Server Side Encryption when uploading the function code 33 | * `sseKmsEncryptionKeyArn` OPTIONAL Specifies a kms arn used to encrypt the lambda code, if desired. 34 | * `keyPrefix` OPTIONAL Specifies the key prefix to use when uploading the function code jar. Defaults to "/" 35 | * `region` Defaults to us-east-1 The AWS region to use for your function. 36 | * `runtime` Defaults to Java8 Specifies whether this is Java8, NodeJs and Python. 37 | * `lambdaRoleArn` The ARN of the AWS role which the lambda user will assume when it executes. Note that the role must be assumable by Lambda and must have Cloudwatch Logs permissions and AWSLambdaDynamoDBExecutionRole policy. 38 | * `lambdaFunctions` Lamda functions that can be configured using tags in pom.xml. 39 | * `lambdaFunctionsJSON` JSON configuration for Lambda Functions. This is preferable configuration. 40 | * `timeout` Defaults to 30 seconds. The amount of time in which the function is allowed to run. 41 | * `memorySize` Defaults to 1024MB NOTE: Please review the AWS Lambda documentation on this setting as it could have an impact on your billing. 42 | * `vpcSubnetIds` The VPC Subnets that Lambda should use to set up your VPC configuration. Format: "subnet-id (cidr-block) | az name-tag". 43 | * `vpcSecurityGroupIds` The VPC Security Groups that Lambda should use to set up your VPC configuration. Format: "sg-id (sg-name) | name-tag". Should be configured. 44 | * `publish` This boolean parameter can be used to request AWS Lambda to update the Lambda function and publish a version as an atomic operation. This is global for all functions and won't overwrite publish paramter in provided Lambda configuration. Setting to false will only update $LATEST. 45 | * `functionNameSuffix` The suffix for the lambda function. Function name is automatically suffixed with it. When left blank no suffix will be applied. 46 | * `forceUpdate` This boolean parameter can be used to force update of existing configuration. Use it when you don't publish a function and want to deploy code in your Lambda function. This is automatically set to `true` if the version contains `SNAPSHOT`. 47 | * `triggers` A list of one or more triggers that execute Lambda function. Currently `CloudWatch Events - Schedule`, `SNS`, `SQS`, `DynamoDB` and `Kinesis` are supported. When `functionNameSuffix` is present then suffix will be added automatically. 48 | * `environmentVariables` Map to define environment variables for Lambda functions enable you to dynamically pass settings to your function code and libraries, without making changes to your code. Deployment functionality merges those variables with the one provided in json configuration. 49 | * `keepAlive` When specified, a CloudWatch event is scheduled to "ping" your function every X minutes, where X is the 50 | value you specify. This keeps your lambda function resident and ready to receive real requests at all times. This is 51 | useful for when you need your function to be responsive. 52 | * `passThrough` This directive is to be used only on the command line. It allows you to pass environment variables from the command line to your functions using json. Example: 53 | ``` 54 | mvn package shade:shade lambda:deploy-lambda -DpassThrough="{'KEY1' : 'VAL1', 'KEY2' : 'VAL2'}" 55 | ``` 56 | * `kmsEncryptionKeyArn` The AWS KMS encryption key you wish to use to encrypt/decrypt sensitive environment variables. 57 | * `encryptedPassThrough` Similar to passThrough (see above), but these variables will be encrypted using the KMS encryption key specified above. Requires that kmsEncryptionKeyArn is specified. 58 | * `clientConfiguration` Allows you to specify a http(s) proxy when communicating with AWS. The following parameters may be specified, see the Example configuration below for an example. 59 | * `protocol` 60 | * `proxyHost` 61 | * `proxyPort` 62 | * `proxyDomain` 63 | * `proxyUsername` 64 | * `proxyPassword` 65 | * `proxyWorkstation` 66 | 67 | Current configuration of LambdaFunction can be found in LambdaFunction.java. 68 | 69 | ### Example configuration in pom.xml 70 | ``` 71 | 76 | ${project.build.directory}/${project.build.finalName}.jar 77 | ${project.version} 78 | true 79 | true 80 | dev 81 | 82 | 83 | ... 84 | 85 | 86 | com.github.seanroy 87 | lambda-maven-plugin 88 | 2.3.2 89 | 90 | false 91 | ${lambda.functionCode} 92 | ${lambda.version} 93 | development 94 | sg-123456 95 | subnet-123456,subnet-123456,subnet-123456 96 | arn:aws:iam::1234567:role/YourLambdaS3Role 97 | mys3bucket 98 | my/awesome/prefix 99 | ${lambda.publish} 100 | ${lambda.forceUpdate} 101 | ${lambda.functionNameSuffix} 102 | 103 | value0 104 | 105 | 106 | https 107 | proxy-host.net 108 | 1234 109 | 110 | 111 | [ 112 | { 113 | "functionName": "my-function-name-0", 114 | "description": "I am awesome function", 115 | "handler": "no.flowlab.lambda0::test", 116 | "timeout": 30, 117 | "memorySize": 512, 118 | "keepAlive": 15, 119 | "triggers": [ 120 | { 121 | "integration": "CloudWatch Events - Schedule", 122 | "ruleName": "every-minute", 123 | "ruleDescription": "foo bar", 124 | "scheduleExpression": "rate(1 minute)" 125 | }, 126 | { 127 | "integration": "DynamoDB", 128 | "dynamoDBTable": "myTable", 129 | "batchSize": 100, 130 | "startingPosition": "TRIM_HORIZON" 131 | }, 132 | { 133 | "integration": "Kinesis", 134 | "kinesisStream": "myStream", 135 | "batchSize": 100, 136 | "startingPosition": "TRIM_HORIZON" 137 | }, 138 | { 139 | "integration": "SNS", 140 | "SNSTopic": "SNSTopic-1" 141 | }, 142 | { 143 | "integration": "SNS", 144 | "SNSTopic": "SNSTopic-2" 145 | }, 146 | { 147 | "integration": "Alexa Skills Kit" 148 | "alexaSkillId": "amzn1.ask.skill..." 149 | }, 150 | { 151 | "integration": "Lex", 152 | "lexBotName": "BookCar" 153 | }, 154 | { 155 | "integration": "SQS", 156 | "standardQueue": "queueName" 157 | } 158 | ], 159 | "environmentVariables": { 160 | "key1": "value1", 161 | "key2": "value2" 162 | } 163 | }, 164 | { 165 | "functionName": "my-function-name-1", 166 | "description": "I am awesome function too", 167 | "handler": "no.flowlab.lambda1" 168 | } 169 | ] 170 | 171 | 172 | 173 | 174 | ... 175 | 176 | 177 | ``` 178 | ### A Note About Environment Variables 179 | Environment variables set by this plugin respect the following hierarchy: 180 | 1. Variables set within the AWS Lambda Console. 181 | 2. Variables set within the Configuration block of the plugin (See above). 182 | 3. Variables set within the JSON lambda function descriptors (See above). 183 | 4. Pass through variables defined on the command line when deploying the function. 184 | 185 | Variables defined at a higher level (top of the list above) may be overridden by those at a lower level. 186 | 187 | ### Credentials 188 | Your AWS credentials may be set on the command line or in the plugin configuration. If `accessKey` and 189 | `secretKey` are not explicitly defined, the plugin will look for them in your environment or in your 190 | ~/.aws/credentials file 191 | 192 | IAM permissions required by this plugin: 193 | * action `s3:GetObject` and `s3:PutObject` on resource `arn:aws:s3:::/*` 194 | * action `s3:ListBucket` on resource `arn:aws:s3:::` 195 | * action `s3:CreateBucket` if you want the plugin to create the S3 bucket you specify. 196 | * action `lambda:CreateFunction` 197 | * action `lambda:InvokeFunction` 198 | * action `lambda:GetFunction` 199 | * action `lambda:UpdateFunctionCode` 200 | * action `lambda:UpdateFunctionConfiguration` 201 | * action `lambda:ListAliases` 202 | * action `lambda:GetPolicy` on resource: `arn:aws:lambda:::function:` 203 | * action `lambda:UpdateAlias` on resource: `arn:aws:lambda:::function:` 204 | * action `lambda:ListEventSourceMappings` on resource: * 205 | * action `events:PutRule` on resource `arn:aws:events:::rule/*` 206 | * action `events:PutTargets` on resource `arn:aws:events:::rule/*` 207 | * action `events:ListRuleNamesByTarget` on resource `arn:aws:events:::rule/*` 208 | * action `events:DescribeRule` on resource `arn:aws:events:::rule/KEEP-ALIVE-` 209 | * action `kinesis:GetRecords, GetShardIterator, DescribeStream, and ListStreams on Kinesis streams` 210 | * action `sqs:GetQueueUrl, sqs:GetQueueAttributes on SQS` 211 | * action `iam:PassRole` on resource `` 212 | * action `SNS:ListSubscriptions` on resource `arn:aws:events:::*` 213 | 214 | ### Developers 215 | If you are interested in contributing to this project, please note that current development can be found in the SNAPSHOT branch of the coming release. When making pull requests, please create them against this branch. 216 | 217 | A test harness has been provided which can be run with `mvn test` Please use 218 | this and feel free to add additional tests. Note that the basic-pom.xml file 219 | requires you to add your role arn in order to work. As such, basic-pom.xml 220 | has been added to .gitignore so that you don't accidentally commit your role 221 | to the file. If you add more pom's as part of enhancing the test suite, 222 | please remember to add them to .gitignore. 223 | 224 | ### Releases 225 | 2.3.5 226 | * Ability to set skill Id for Alexa Skills Kit trigger. Thanks [mphartman1@gmail.com](mailto:mphartman1@gmail.com) 227 | * Auto force update if version contains SNAPSHOT. Thanks [dimeo@elderresearch.com](mailto:dimeo@elderresearch.com) 228 | 229 | 2.3.4 230 | * Resolves [Issue 117](https://github.com/SeanRoy/lambda-maven-plugin/issues/117) https://github.com/juger89 231 | * Thanks [juger89@gmail.com](mailto:juger89@gmail.com) 232 | 233 | 2.3.3 234 | * Added Support for SQS Trigger 235 | 236 | 2.3.2 237 | * Resolves [Issue 89](https://github.com/SeanRoy/lambda-maven-plugin/issues/89), allowing for encryption of environment variables defined on the command line. See kmsEncryptionKey and encryptedPassThrough above. 238 | 239 | 2.3.1 240 | * Resolves [Issue 87](https://github.com/SeanRoy/lambda-maven-plugin/issues/87), which was introduced in 2.3.0. 241 | 242 | 2.3.0 243 | * Resolves [Issue 84](https://github.com/SeanRoy/lambda-maven-plugin/issues/84), Environment variables respect a hierarchy of definition and plugin will no longer wipe out existing variables 244 | 245 | 2.2.9 246 | * Added ability to set http proxy on AWS clients. [Issue 39](https://github.com/SeanRoy/lambda-maven-plugin/issues/39) 247 | 248 | 2.2.8 249 | * Added the ability to set an alias for the new function version, provided publish=true. Fixes [Issue 74](https://github.com/SeanRoy/lambda-maven-plugin/issues/74) 250 | 251 | 2.2.7 252 | * Added SNS & Kinesis trigger orphan handling. This resolves [Issue 50](https://github.com/SeanRoy/lambda-maven-plugin/issues/50) 253 | 254 | 2.2.6 255 | * Fixed another potential NPE, added orphan trigger cleanup for DynamoDB integrations. 256 | 257 | 2.2.5 258 | * Fixed [Issue 77](https://github.com/SeanRoy/lambda-maven-plugin/issues/77) 259 | 260 | 2.2.4 261 | * Smarter orphaned permission handling. 262 | 263 | 2.2.3 264 | * Fixed [Issue 71](https://github.com/SeanRoy/lambda-maven-plugin/issues/71) 265 | * Fixed [Issue 72](https://github.com/SeanRoy/lambda-maven-plugin/issues/72) By adding Lex integration 266 | 267 | 2.2.2 268 | * Fixed [Issue 66](https://github.com/SeanRoy/lambda-maven-plugin/issues/66) 269 | * Fixed sources of potential NPEs, thank [Jean Blanchard](https://github.com/jeanblanchard) 270 | 271 | 2.2.1 272 | * Added passThrough environment variables feature, allowing you to pass environment variables from the command line. 273 | * Added cleanup code to remove cloudwatch event rules that have become orphaned on when the function is being deleted. More triggers will be added to the cleanup list in a later revision. 274 | 275 | 2.2.0 276 | * Added Keep Alive functionality 277 | * Fixed broken update schedule code. 278 | * Added Kinesis trigger, thanks [Matt Van](https://github.com/mattvv) 279 | * Deletion of triggers on lambda delete and the update code needs serious re-working. 280 | * Need to work on cleaning up after orphaned resources. 281 | 282 | 2.1.7 283 | * Fixed critical credentials bug introduced in 2.1.6. 284 | 285 | 2.1.6 286 | * Removed some deprecated code 287 | * functionNameSuffix is no longer automatically hyphenated. If you want a hyphen, specify it in the functionNameSuffix directive. 288 | 289 | 2.1.5 290 | * Add support for environment variables [Issue 48](https://github.com/SeanRoy/lambda-maven-plugin/issues/48) 291 | * Thanks [krzysztof@flowlab.no](mailto:krzysztof@flowlab.no) 292 | 293 | 2.1.4 294 | * Fixed [Issue 46] (https://github.com/SeanRoy/lambda-maven-plugin/issues/46) 295 | * Thanks [krzysztof@flowlab.no](mailto:krzysztof@flowlab.no) 296 | 297 | 2.1.3 298 | * Fixed [Issue 42] (https://github.com/SeanRoy/lambda-maven-plugin/issues/42) 299 | * Thanks [krzysztof@flowlab.no](mailto:krzysztof@flowlab.no) 300 | 301 | 2.1.2 302 | * Added trigger to allow Alexa Skills Kit Integration. 303 | 304 | 2.1.1 305 | * Remove deprecated `scheduledRules` and `topics` functionality 306 | * Thanks [krzysztof@flowlab.no](mailto:krzysztof@flowlab.no) 307 | 308 | 2.1.0 309 | * Add support for triggers. Deprecated `scheduledRules` and `topics` as thouse have been moved to triggers 310 | * Add support for DynamoDB stream. `lambdaRoleArn` requires AWSLambdaDynamoDBExecutionRole policy 311 | * Update to AWS SDK 1.11.41 312 | * Thanks [krzysztof@flowlab.no](mailto:krzysztof@flowlab.no) 313 | 314 | 2.0.1 315 | * Fixed [Issue 33] (https://github.com/SeanRoy/lambda-maven-plugin/pull/33) Thank Vũ Mạnh Tú. 316 | 317 | 2.0.0 318 | * Add support for configuration many lambda functions in one deliverable, supports config in JSON, each lumbda function configuration can be fully customized 319 | * Add support for version aliases when publish is activated 320 | * Change defaults 321 | * Fixed some mainor code smells 322 | * Remove support for annotations 323 | * Refactor code to java8 324 | * Add publish flag, which controls Lambda versioning in AWS 325 | * Force update support 326 | * Add support for SNS topics 327 | * Add support for scheduled rules, cron jobs which trigger lambda function 328 | * Thanks [krzysztof@flowlab.no](mailto:krzysztof@flowlab.no) 329 | 330 | 1.1.6 331 | * Removed debugging related code. 332 | 333 | 1.1.5 334 | * Fixed bug where default value of functionNameSuffix evaluating to null instead of a blank string. 335 | 336 | 1.1.4 337 | * Added functionNameSuffix optional property. 338 | 339 | 1.1.3 340 | * Fixed [Issue 28] (https://github.com/SeanRoy/lambda-maven-plugin/issues/28) 341 | 342 | 1.1.2 343 | * Fixed invalid dependency to lambda-maven-annotations 344 | 345 | 1.1.1 346 | * Added support for Virtual Private Clouds. Thanks Jem Rayfield. 347 | * Added ability to designate functions for deployment via LambduhFunction annotations. (Details coming soon). 348 | 349 | 1.1.0 350 | * Added delete goal. 351 | 352 | 1.0.6 353 | * Issue 19 Added test harness. 354 | * Update function code if code or configuration has changed instead of 355 | deleting and recreating every time. Thanks Guillermo Menendez 356 | 357 | 1.0.5 358 | * Accidental deployment of release. Should be functionally equivalent to 359 | 1.0.4. 360 | 361 | 1.0.4 362 | * Fixed issue 8 363 | * No longer uploads function code to S3 when no changes have been made to speed up 364 | development cycle over slow connections. Thanks Philip M. White. 365 | * Fixed logging. 366 | 367 | 1.0.3 368 | * Fixed a bug where getting a bucket fails if existing. Thanks buri17 369 | * Fixed problem with region specification. Thanks buri17 370 | * Adding ability to pull creds from the default provider. Thanks Chris Weiss 371 | 372 | 1.0.2 373 | * Fixed PatternSyntaxException on windows https://github.com/SeanRoy/lambda-maven-plugin/issues/1 374 | -------------------------------------------------------------------------------- /src/main/java/com/github/seanroy/plugins/AbstractLambdaMojo.java: -------------------------------------------------------------------------------- 1 | package com.github.seanroy.plugins; 2 | 3 | import static com.amazonaws.util.CollectionUtils.isNullOrEmpty; 4 | import static java.util.Collections.emptyList; 5 | import static java.util.Optional.of; 6 | import static java.util.Optional.ofNullable; 7 | import static java.util.stream.Collectors.toList; 8 | 9 | import java.io.File; 10 | import java.io.FileInputStream; 11 | import java.io.IOException; 12 | import java.lang.reflect.Type; 13 | import java.util.*; 14 | import java.util.function.BiFunction; 15 | import java.util.function.Function; 16 | import java.util.regex.Pattern; 17 | import java.util.stream.Collectors; 18 | import java.util.stream.Stream; 19 | 20 | import com.amazonaws.services.lambda.model.GetFunctionRequest; 21 | import com.amazonaws.services.lambda.model.GetFunctionResult; 22 | import com.amazonaws.services.lambda.model.UpdateFunctionCodeRequest; 23 | import com.amazonaws.services.lambda.model.UpdateFunctionCodeResult; 24 | import com.amazonaws.services.s3.model.*; 25 | import org.apache.commons.codec.digest.DigestUtils; 26 | import org.apache.maven.plugin.AbstractMojo; 27 | import org.apache.maven.plugin.MojoExecutionException; 28 | import org.apache.maven.plugins.annotations.Parameter; 29 | 30 | import com.amazonaws.AmazonWebServiceClient; 31 | import com.amazonaws.ClientConfiguration; 32 | import com.amazonaws.Protocol; 33 | import com.amazonaws.auth.AWSCredentials; 34 | import com.amazonaws.auth.AWSStaticCredentialsProvider; 35 | import com.amazonaws.auth.BasicAWSCredentials; 36 | import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; 37 | import com.amazonaws.client.builder.AwsClientBuilder; 38 | import com.amazonaws.regions.Regions; 39 | import com.amazonaws.services.cloudwatchevents.AmazonCloudWatchEvents; 40 | import com.amazonaws.services.cloudwatchevents.AmazonCloudWatchEventsClientBuilder; 41 | import com.amazonaws.services.dynamodbv2.AmazonDynamoDBStreams; 42 | import com.amazonaws.services.dynamodbv2.AmazonDynamoDBStreamsClientBuilder; 43 | import com.amazonaws.services.kinesis.AmazonKinesis; 44 | import com.amazonaws.services.kinesis.AmazonKinesisClientBuilder; 45 | import com.amazonaws.services.lambda.AWSLambda; 46 | import com.amazonaws.services.lambda.AWSLambdaClientBuilder; 47 | import com.amazonaws.services.lambda.model.GetFunctionConfigurationRequest; 48 | import com.amazonaws.services.lambda.model.ResourceNotFoundException; 49 | import com.amazonaws.services.s3.AmazonS3; 50 | import com.amazonaws.services.s3.AmazonS3ClientBuilder; 51 | import com.amazonaws.services.sns.AmazonSNS; 52 | import com.amazonaws.services.sns.AmazonSNSClientBuilder; 53 | import com.amazonaws.services.sqs.AmazonSQS; 54 | import com.amazonaws.services.sqs.AmazonSQSClientBuilder; 55 | import com.github.seanroy.utils.AWSEncryption; 56 | import com.github.seanroy.utils.JsonUtil; 57 | import com.google.gson.GsonBuilder; 58 | import com.google.gson.reflect.TypeToken; 59 | 60 | /** 61 | * Abstracts all common parameter handling and initiation of AWS service clients. 62 | * 63 | * @author sean, Krzysztof Grodzicki 11/08/16. 64 | */ 65 | @SuppressWarnings("ClassWithTooManyFields") 66 | public abstract class AbstractLambdaMojo extends AbstractMojo { 67 | public static final String TRIG_INT_LABEL_CLOUDWATCH_EVENTS = "CloudWatch Events - Schedule"; 68 | public static final String TRIG_INT_LABEL_DYNAMO_DB = "DynamoDB"; 69 | public static final String TRIG_INT_LABEL_KINESIS = "Kinesis"; 70 | public static final String TRIG_INT_LABEL_SNS = "SNS"; 71 | public static final String TRIG_INT_LABEL_ALEXA_SK = "Alexa Skills Kit"; 72 | public static final String TRIG_INT_LABEL_LEX = "Lex"; 73 | public static final String TRIG_INT_LABEL_SQS = "SQS"; 74 | 75 | public static final String PERM_LAMBDA_INVOKE = "lambda:InvokeFunction"; 76 | 77 | public static final String PRINCIPAL_ALEXA = "alexa-appkit.amazon.com"; 78 | public static final String PRINCIPAL_LEX = "lex.amazonaws.com"; 79 | public static final String PRINCIPAL_SNS = "sns.amazonaws.com"; 80 | public static final String PRINCIPAL_EVENTS = "events.amazonaws.com"; // Cloudwatch events 81 | public static final String PRINCIPAL_SQS = "sqs.amazonaws.com"; 82 | 83 | @Parameter(property = "skip", defaultValue = "false") 84 | public boolean skip; 85 | 86 | /** 87 | *

The AWS access key.

88 | */ 89 | @Parameter(property = "accessKey", defaultValue = "${accessKey}") 90 | public String accessKey; 91 | /** 92 | *

The AWS secret access key.

93 | */ 94 | @Parameter(property = "secretKey", defaultValue = "${secretKey}") 95 | public String secretKey; 96 | /** 97 | *

The path to deliverable.

98 | */ 99 | @Parameter(property = "functionCode", defaultValue = "${functionCode}", required = true) 100 | public String functionCode; 101 | /** 102 | *

The version of deliverable. Example value can be 1.0-SNAPSHOT.

103 | */ 104 | @Parameter(property = "version", defaultValue = "${version}", required = true) 105 | public String version; 106 | 107 | @Parameter(property = "alias") 108 | public String alias; 109 | 110 | /** 111 | *

Amazon region. Default value is us-east-1.

112 | */ 113 | @Parameter(property = "region", alias = "region", defaultValue = "us-east-1") 114 | public String regionName; 115 | /** 116 | *

117 | * Amazon S3 bucket name where the .zip file containing your deployment 118 | * package is stored. This bucket must reside in the same AWS region where 119 | * you are creating the Lambda function. 120 | *

121 | */ 122 | @Parameter(property = "s3Bucket", defaultValue = "lambda-function-code") 123 | public String s3Bucket; 124 | /** 125 | *

126 | * AWS S3 Server Side Encryption (SSE) 127 | *

128 | */ 129 | @Parameter(property = "sse", defaultValue = "false") 130 | public boolean sse; 131 | /** 132 | *

133 | * AWS KMS Key ID for S3 Server Side Encryption (SSE) 134 | *

135 | */ 136 | @Parameter(property = "sseKmsEncryptionKeyArn") 137 | public String sseKmsEncryptionKeyArn; 138 | /** 139 | *

140 | * S3 key prefix for the uploaded jar 141 | *

142 | */ 143 | @Parameter(property = "keyPrefix", defaultValue = "/") 144 | public String keyPrefix; 145 | /** 146 | *

147 | * The runtime environment for the Lambda function. 148 | *

149 | *

150 | * To use the Node.js runtime v4.3, set the value to "nodejs4.3". To use 151 | * earlier runtime (v0.10.42), set the value to "nodejs". 152 | *

153 | */ 154 | @Parameter(property = "runtime", defaultValue = "java8") 155 | public String runtime; 156 | /** 157 | *

The Amazon Resource Name (ARN) of the IAM role that Lambda will assume when it executes your function.

158 | */ 159 | @Parameter(property = "lambdaRoleArn", defaultValue = "${lambdaRoleArn}") 160 | public String lambdaRoleArn; 161 | /** 162 | *

The JSON confuguration for Lambda functions. @see {@link LambdaFunction}.

163 | */ 164 | @Parameter(property = "lambdaFunctionsJSON") 165 | public String lambdaFunctionsJSON; 166 | /** 167 | *

The confuguration for Lambda functions. @see {@link LambdaFunction}. Can be configured in pom.xml. Automaticall parsed from JSON configuration.

168 | */ 169 | @Parameter(property = "lambdaFunctions", defaultValue = "${lambdaFunctions}") 170 | public List lambdaFunctions; 171 | /** 172 | *

173 | * The function execution time at which AWS Lambda should terminate the 174 | * function. Because the execution time has cost implications, we recommend 175 | * you set this value based on your expected execution time. The default is 30 seconds. 176 | *

177 | */ 178 | @Parameter(property = "timeout", defaultValue = "30") 179 | public int timeout; 180 | /** 181 | *

182 | * The amount of memory, in MB, your Lambda function is given. AWS Lambda 183 | * uses this memory size to infer the amount of CPU allocated to your 184 | * function. Your function use-case determines your CPU and memory 185 | * requirements. For example, a database operation might need less memory 186 | * compared to an image processing function. The default value is 1024 MB. 187 | * The value must be a multiple of 64 MB. 188 | *

189 | */ 190 | @Parameter(property = "memorySize", defaultValue = "1024") 191 | public int memorySize; 192 | /** 193 | *

A list of one or more security groups IDs in your VPC.

194 | */ 195 | @Parameter(property = "vpcSecurityGroupIds", defaultValue = "${vpcSecurityGroupIds}") 196 | public List vpcSecurityGroupIds; 197 | /** 198 | *

A list of one or more subnet IDs in your VPC.

199 | */ 200 | @Parameter(property = "vpcSubnetIds", defaultValue = "${vpcSubnetIds}") 201 | public List vpcSubnetIds; 202 | /** 203 | *

This boolean parameter can be used to request AWS Lambda to update the 204 | * Lambda function and publish a version as an atomic operation.

205 | */ 206 | @Parameter(property = "publish", defaultValue = "true") 207 | public boolean publish; 208 | /** 209 | *

The suffix for the lambda function.

210 | */ 211 | @Parameter(property = "functionNameSuffix") 212 | public String functionNameSuffix; 213 | /** 214 | *

This boolean parameter can be used to force update of existing configuration. Use it when you don't publish a function and want to replece code in your Lambda function. 215 | * The default value is {@code true} iff the version contains {@code SNAPSHOT} (case insensitive).

216 | */ 217 | @Parameter(property = "forceUpdate") 218 | public Boolean forceUpdate; 219 | /** 220 | *

This map parameter can be used to define environment variables for Lambda functions enable you to dynamically pass settings to your function code and libraries, without making changes to your code. Deployment functionality merges those variables with the one provided in json configuration.

221 | */ 222 | @Parameter(property = "environmentVariables", defaultValue = "${environmentVariables}") 223 | public Map environmentVariables; 224 | 225 | @Parameter(property = "passThrough") 226 | public String passThrough; 227 | 228 | @Parameter(property = "kmsEncryptionKeyArn") 229 | public String kmsEncryptionKeyArn; 230 | 231 | @Parameter(property = "encryptedPassThrough") 232 | public String encryptedPassThrough; 233 | 234 | /** 235 | * Allows for proxy settings to passed to the lambda client. 236 | */ 237 | @Parameter(property = "clientConfiguration") 238 | public Map clientConfiguration; 239 | 240 | public String fileName; 241 | public AWSCredentials credentials; 242 | public AmazonS3 s3Client; 243 | public AWSLambda lambdaClient; 244 | public AmazonSNS snsClient; 245 | public AmazonCloudWatchEvents eventsClient; 246 | public AmazonDynamoDBStreams dynamoDBStreamsClient; 247 | public AmazonKinesis kinesisClient; 248 | public AmazonCloudWatchEvents cloudWatchEventsClient; 249 | public AmazonSQS sqsClient; 250 | 251 | protected boolean checkSkip() { 252 | if(skip) { 253 | getLog().info("Execution skipped."); 254 | } 255 | return skip; 256 | } 257 | 258 | @Override 259 | public void execute() throws MojoExecutionException { 260 | initAWSCredentials(); 261 | initAWSClients(); 262 | try { 263 | initFileName(); 264 | initVersion(); 265 | initLambdaFunctionsConfiguration(); 266 | 267 | lambdaFunctions.forEach(lambdaFunction -> getLog().debug(lambdaFunction.toString())); 268 | } catch (Exception e) { 269 | getLog().error("Initialization of configuration failed", e); 270 | throw new MojoExecutionException(e.getMessage()); 271 | } 272 | } 273 | 274 | void uploadJarToS3() throws Exception { 275 | String bucket = getBucket(); 276 | File file = new File(functionCode); 277 | String localmd5 = DigestUtils.md5Hex(new FileInputStream(file)); 278 | getLog().debug(String.format("Local file's MD5 hash is %s.", localmd5)); 279 | 280 | ofNullable(getObjectMetadata(bucket)) 281 | .map(ObjectMetadata::getETag) 282 | .map(remoteMD5 -> { 283 | getLog().info(fileName + " exists in S3 with MD5 hash " + remoteMD5); 284 | // This comparison will no longer work if we ever go to multipart uploads. Etags are not 285 | // computed as MD5 sums for multipart uploads in s3. 286 | return localmd5.equals(remoteMD5); 287 | }) 288 | .map(isTheSame -> { 289 | if (isTheSame) { 290 | getLog().info(fileName + " is up to date in AWS S3 bucket " + s3Bucket + ". Not uploading..."); 291 | return true; 292 | } 293 | return null; // file should be imported 294 | }) 295 | .orElseGet(() -> { 296 | upload(file); 297 | return true; 298 | }); 299 | } 300 | 301 | Function updateFunctionCode = (LambdaFunction lambdaFunction) -> { 302 | getLog().info("About to update functionCode for " + lambdaFunction.getFunctionName()); 303 | UpdateFunctionCodeRequest updateFunctionRequest = new UpdateFunctionCodeRequest() 304 | .withFunctionName(lambdaFunction.getFunctionName()) 305 | .withS3Bucket(s3Bucket) 306 | .withS3Key(fileName) 307 | .withPublish(lambdaFunction.isPublish()); 308 | UpdateFunctionCodeResult updateFunctionCodeResult = lambdaClient.updateFunctionCode(updateFunctionRequest); 309 | 310 | // wait until the UpdateFunctionCode finishes processing to avoid com.amazonaws.services.lambda.model.ResourceConflictException. See: https://docs.aws.amazon.com/lambda/latest/dg/functions-states.html 311 | GetFunctionRequest getFunctionRequest = new GetFunctionRequest() 312 | .withFunctionName(lambdaFunction.getFunctionName()); 313 | GetFunctionResult getFunctionResult = lambdaClient.getFunction(getFunctionRequest); 314 | 315 | while (!getFunctionResult.getConfiguration().getState().equals("Active") 316 | || !getFunctionResult.getConfiguration().getLastUpdateStatus().equals("Successful")) { 317 | try { 318 | getLog().info(String.format("UpdateFunctionCode for %s is still processing , waiting... ", lambdaFunction.getFunctionName(), getFunctionResult.getConfiguration().getState(), getFunctionResult.getConfiguration().getLastUpdateStatus())); 319 | Thread.sleep(3000); 320 | getFunctionResult = lambdaClient.getFunction(getFunctionRequest); 321 | } catch (InterruptedException e) { 322 | e.printStackTrace(); 323 | } 324 | } 325 | getLog().info("UpdateFunctionCode finished successfully for " + lambdaFunction.getFunctionName()); 326 | 327 | return lambdaFunction 328 | .withVersion(updateFunctionCodeResult.getVersion()) 329 | .withFunctionArn(updateFunctionCodeResult.getFunctionArn()); 330 | }; 331 | 332 | private ObjectMetadata getObjectMetadata(String bucket) { 333 | try { 334 | return s3Client.getObjectMetadata(bucket, fileName); 335 | } catch (AmazonS3Exception ignored) { 336 | return null; 337 | } 338 | } 339 | 340 | private String getBucket() { 341 | if (s3Client.listBuckets().stream().noneMatch(p -> Objects.equals(p.getName(), s3Bucket))) { 342 | getLog().info("Created bucket s3://" + s3Client.createBucket(s3Bucket).getName()); 343 | } 344 | return s3Bucket; 345 | } 346 | 347 | private PutObjectResult upload(File file) { 348 | getLog().info("Uploading " + functionCode + " to AWS S3 bucket " + s3Bucket); 349 | PutObjectRequest putObjectRequest = new PutObjectRequest(s3Bucket, fileName, file); 350 | if (sse) { 351 | if (sseKmsEncryptionKeyArn != null && sseKmsEncryptionKeyArn.length() > 0) { 352 | putObjectRequest.setSSEAwsKeyManagementParams(new SSEAwsKeyManagementParams(sseKmsEncryptionKeyArn)); 353 | } else { 354 | ObjectMetadata objectMetadata = new ObjectMetadata(); 355 | objectMetadata.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); 356 | putObjectRequest.setMetadata(objectMetadata); 357 | } 358 | } 359 | PutObjectResult putObjectResult = s3Client.putObject(putObjectRequest); 360 | getLog().info("Upload complete..."); 361 | return putObjectResult; 362 | } 363 | 364 | private void initAWSCredentials() throws MojoExecutionException { 365 | DefaultAWSCredentialsProviderChain defaultChain = new DefaultAWSCredentialsProviderChain(); 366 | if (accessKey != null && secretKey != null) { 367 | credentials = new BasicAWSCredentials(accessKey, secretKey); 368 | } else if (defaultChain.getCredentials() != null) { 369 | credentials = defaultChain.getCredentials(); 370 | } 371 | 372 | if (credentials == null) { 373 | getLog().error("Unable to initialize AWS Credentials. Set BasicAWSCredentials with accessKey and secretKey or configure DefaultAWSCredentialsProviderChain"); 374 | throw new MojoExecutionException("AWS Credentials config error"); 375 | } 376 | } 377 | 378 | private void initFileName() { 379 | String pattern = Pattern.quote(File.separator); 380 | String[] pieces = functionCode.split(pattern); 381 | if (!ofNullable(keyPrefix).orElse("/").endsWith("/")) { 382 | keyPrefix += "/"; 383 | } 384 | fileName = keyPrefix + pieces[pieces.length - 1]; 385 | } 386 | 387 | private void initVersion() { 388 | version = version.replace(".", "-"); 389 | } 390 | 391 | @SuppressWarnings("rawtypes") 392 | BiFunction clientFactory = (builder, clientConfig) -> { 393 | Regions region = Regions.fromName(regionName); 394 | 395 | return (AmazonWebServiceClient) of(credentials) 396 | .map(credentials -> builder.withCredentials(new AWSStaticCredentialsProvider(credentials)) 397 | .withClientConfiguration(clientConfig) 398 | .withRegion(region).build()) 399 | .orElse(builder.withRegion(region).withCredentials(new DefaultAWSCredentialsProviderChain()).build()); 400 | }; 401 | 402 | private void initAWSClients() { 403 | ClientConfiguration clientConfig = clientConfiguration(); 404 | s3Client = (AmazonS3) clientFactory.apply(AmazonS3ClientBuilder.standard(), clientConfig); 405 | lambdaClient = (AWSLambda) clientFactory.apply(AWSLambdaClientBuilder.standard(), clientConfig); 406 | snsClient = (AmazonSNS) clientFactory.apply(AmazonSNSClientBuilder.standard(), clientConfig); 407 | eventsClient = (AmazonCloudWatchEvents) clientFactory.apply(AmazonCloudWatchEventsClientBuilder.standard(), clientConfig); 408 | dynamoDBStreamsClient = (AmazonDynamoDBStreams) clientFactory.apply(AmazonDynamoDBStreamsClientBuilder.standard(), clientConfig); 409 | kinesisClient = (AmazonKinesis) clientFactory.apply(AmazonKinesisClientBuilder.standard(), clientConfig); 410 | cloudWatchEventsClient = (AmazonCloudWatchEvents) clientFactory.apply(AmazonCloudWatchEventsClientBuilder.standard(), clientConfig); 411 | sqsClient = (AmazonSQS) clientFactory.apply(AmazonSQSClientBuilder.standard(), clientConfig); 412 | } 413 | 414 | private void initLambdaFunctionsConfiguration() throws MojoExecutionException, IOException { 415 | if (lambdaFunctionsJSON != null) { 416 | this.lambdaFunctions = JsonUtil.fromJson(lambdaFunctionsJSON); 417 | } 418 | validate(lambdaFunctions); 419 | 420 | lambdaFunctions = lambdaFunctions.stream().map(lambdaFunction -> { 421 | String functionName = ofNullable(lambdaFunction.getFunctionName()).orElseThrow(() -> new IllegalArgumentException("Configuration error. LambdaFunction -> 'functionName' is required")); 422 | 423 | lambdaFunction.withFunctionName(addSuffix(functionName)) 424 | .withHandler(ofNullable(lambdaFunction.getHandler()).orElseThrow(() -> new IllegalArgumentException("Configuration error. LambdaFunction -> 'handler' is required"))) 425 | .withDescription(ofNullable(lambdaFunction.getDescription()).orElse("")) 426 | .withTimeout(ofNullable(lambdaFunction.getTimeout()).orElse(timeout)) 427 | .withMemorySize(ofNullable(lambdaFunction.getMemorySize()).orElse(memorySize)) 428 | .withSubnetIds(ofNullable(vpcSubnetIds).orElse(new ArrayList<>())) 429 | .withSecurityGroupsIds(ofNullable(vpcSecurityGroupIds).orElse(new ArrayList<>())) 430 | .withVersion(version) 431 | .withPublish(ofNullable(lambdaFunction.isPublish()).orElse(publish)) 432 | .withLambdaRoleArn(ofNullable(lambdaFunction.getLambdaRoleArn()).orElse(lambdaRoleArn)) 433 | .withAliases(aliases(lambdaFunction.isPublish())) 434 | .withTriggers(ofNullable(lambdaFunction.getTriggers()).map(triggers -> triggers.stream() 435 | .map(trigger -> { 436 | trigger.withRuleName(addSuffix(trigger.getRuleName())); 437 | trigger.withSNSTopic(addSuffix(trigger.getSNSTopic())); 438 | trigger.withDynamoDBTable(addSuffix(trigger.getDynamoDBTable())); 439 | trigger.withLexBotName(addSuffix(trigger.getLexBotName())); 440 | trigger.withStandardQueue(addSuffix(trigger.getStandardQueue())); 441 | return trigger; 442 | }) 443 | .collect(toList())) 444 | .orElse(new ArrayList<>())) 445 | .withEnvironmentVariables(environmentVariables(lambdaFunction)); 446 | 447 | return lambdaFunction; 448 | }).collect(toList()); 449 | } 450 | 451 | @SuppressWarnings("unchecked") 452 | private Map environmentVariables(LambdaFunction lambdaFunction) { 453 | // Get existing environment variables to interleave them with the new ones or replacements. 454 | Map awsDefinedEnvVars = new HashMap(); 455 | 456 | try { 457 | awsDefinedEnvVars = ofNullable(lambdaClient.getFunctionConfiguration(new GetFunctionConfigurationRequest() 458 | .withFunctionName(lambdaFunction.getFunctionName()) 459 | .withQualifier(lambdaFunction.getQualifier())).getEnvironment()).flatMap(x -> { 460 | return of(x.getVariables());}).orElse(new HashMap<>()); 461 | } catch(ResourceNotFoundException rnfe) { 462 | getLog().debug("Lambda function doesn't exist yet, no existing environment variables retrieved."); 463 | } catch(Exception e) { 464 | getLog().error("Could not retrieve existing environment variables " + e.getMessage()); 465 | } 466 | 467 | Map configurationEnvVars = ofNullable(environmentVariables).orElse(new HashMap<>()); 468 | Map functionEnvVars = ofNullable(lambdaFunction.getEnvironmentVariables()).orElse(new HashMap<>()); 469 | Type type = new TypeToken>(){}.getType(); 470 | 471 | Map passThroughEnvVars = 472 | new GsonBuilder().create().fromJson(ofNullable(passThrough).orElse("{}"), type); 473 | 474 | passThroughEnvVars.putAll(ofNullable(kmsEncryptionKeyArn).flatMap(arn -> { 475 | AWSEncryption awsEncryptor = new AWSEncryption(arn); 476 | Map encryptedVariables = 477 | new GsonBuilder().create().fromJson(ofNullable(encryptedPassThrough).orElse("{}"), type); 478 | encryptedVariables.replaceAll((k, v) -> { 479 | return awsEncryptor.encryptString(v); 480 | }); 481 | return of(encryptedVariables); 482 | }).orElse(new HashMap())); 483 | 484 | // There may be a smarter way of doing this, but we have a hierarchy of environment variables. Those at the top 485 | // may be overridden by variables below them. 486 | // 1. Variables defined manually in the AWS Lambda Console 487 | // 2. Variables defined at the Configuration Level of the pom.xml 488 | // 3. Variables defined at the Function Level within the Configuration Level of the pom.xml. 489 | // 4. Pass through variables defined at the command line. 490 | awsDefinedEnvVars.putAll(configurationEnvVars); 491 | awsDefinedEnvVars.putAll(functionEnvVars); 492 | awsDefinedEnvVars.putAll(passThroughEnvVars); 493 | 494 | return awsDefinedEnvVars; 495 | } 496 | 497 | private ClientConfiguration clientConfiguration() { 498 | return ofNullable(clientConfiguration).flatMap(clientConfigObject -> { 499 | return of(new ClientConfiguration() 500 | .withProtocol(Protocol.valueOf( 501 | clientConfigObject.getOrDefault("protocol", Protocol.HTTPS.toString()).toUpperCase())) 502 | .withProxyHost(clientConfigObject.get("proxyHost")) 503 | .withProxyPort(Integer.getInteger(clientConfigObject.get("proxyPort"), -1)) 504 | .withProxyDomain(clientConfigObject.get("proxyDomain")) 505 | .withProxyUsername(clientConfigObject.get("proxyUsername")) 506 | .withProxyPassword(clientConfigObject.get("proxyPassword")) 507 | .withProxyWorkstation(clientConfigObject.get("proxyWorkstation"))); 508 | }).orElse(new ClientConfiguration()); 509 | } 510 | 511 | private String addSuffix(String functionName) { 512 | return ofNullable(functionNameSuffix).map(suffix -> Stream.of(functionName, suffix).collect(Collectors.joining())) 513 | .orElse(functionName); 514 | } 515 | 516 | private List aliases(boolean publish) { 517 | if (publish) { 518 | return new ArrayList() {{ add(version); ofNullable(alias).ifPresent(a -> add(a)); }}; 519 | } 520 | return emptyList(); 521 | } 522 | 523 | private void validate(List lambdaFunctions) throws MojoExecutionException { 524 | if (isNullOrEmpty(lambdaFunctions)) { 525 | getLog().error("At least one function has to be provided in configuration"); 526 | throw new MojoExecutionException("Illegal configuration. Configuration for at least one Lambda function has to be provided"); 527 | } 528 | } 529 | } 530 | -------------------------------------------------------------------------------- /src/main/java/com/github/seanroy/plugins/DeployLambdaMojo.java: -------------------------------------------------------------------------------- 1 | package com.github.seanroy.plugins; 2 | 3 | import static com.amazonaws.services.lambda.model.EventSourcePosition.LATEST; 4 | import static java.util.Optional.empty; 5 | import static java.util.Optional.of; 6 | import static java.util.Optional.ofNullable; 7 | import static java.util.stream.Collectors.toList; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | import java.util.Objects; 12 | import java.util.Optional; 13 | import java.util.UUID; 14 | import java.util.function.BiFunction; 15 | import java.util.function.BiPredicate; 16 | import java.util.function.Function; 17 | import java.util.stream.Collectors; 18 | 19 | import org.apache.commons.lang3.ObjectUtils; 20 | import org.apache.commons.lang3.StringUtils; 21 | import org.apache.maven.plugin.MojoExecutionException; 22 | import org.apache.maven.plugins.annotations.Mojo; 23 | 24 | import com.amazonaws.auth.policy.Policy; 25 | import com.amazonaws.auth.policy.Statement; 26 | import com.amazonaws.services.cloudwatchevents.model.DeleteRuleRequest; 27 | import com.amazonaws.services.cloudwatchevents.model.DescribeRuleRequest; 28 | import com.amazonaws.services.cloudwatchevents.model.DescribeRuleResult; 29 | import com.amazonaws.services.cloudwatchevents.model.ListRuleNamesByTargetRequest; 30 | import com.amazonaws.services.cloudwatchevents.model.PutRuleRequest; 31 | import com.amazonaws.services.cloudwatchevents.model.PutRuleResult; 32 | import com.amazonaws.services.cloudwatchevents.model.PutTargetsRequest; 33 | import com.amazonaws.services.cloudwatchevents.model.RemoveTargetsRequest; 34 | import com.amazonaws.services.cloudwatchevents.model.Target; 35 | import com.amazonaws.services.dynamodbv2.model.DescribeStreamRequest; 36 | import com.amazonaws.services.dynamodbv2.model.ListStreamsRequest; 37 | import com.amazonaws.services.dynamodbv2.model.ListStreamsResult; 38 | import com.amazonaws.services.dynamodbv2.model.Stream; 39 | import com.amazonaws.services.dynamodbv2.model.StreamDescription; 40 | import com.amazonaws.services.lambda.model.AddPermissionRequest; 41 | import com.amazonaws.services.lambda.model.AddPermissionResult; 42 | import com.amazonaws.services.lambda.model.AliasConfiguration; 43 | import com.amazonaws.services.lambda.model.CreateAliasRequest; 44 | import com.amazonaws.services.lambda.model.CreateEventSourceMappingRequest; 45 | import com.amazonaws.services.lambda.model.CreateEventSourceMappingResult; 46 | import com.amazonaws.services.lambda.model.CreateFunctionRequest; 47 | import com.amazonaws.services.lambda.model.CreateFunctionResult; 48 | import com.amazonaws.services.lambda.model.DeleteEventSourceMappingRequest; 49 | import com.amazonaws.services.lambda.model.Environment; 50 | import com.amazonaws.services.lambda.model.EventSourceMappingConfiguration; 51 | import com.amazonaws.services.lambda.model.EventSourcePosition; 52 | import com.amazonaws.services.lambda.model.FunctionCode; 53 | import com.amazonaws.services.lambda.model.GetFunctionRequest; 54 | import com.amazonaws.services.lambda.model.GetFunctionResult; 55 | import com.amazonaws.services.lambda.model.GetPolicyRequest; 56 | import com.amazonaws.services.lambda.model.GetPolicyResult; 57 | import com.amazonaws.services.lambda.model.ListAliasesRequest; 58 | import com.amazonaws.services.lambda.model.ListAliasesResult; 59 | import com.amazonaws.services.lambda.model.ListEventSourceMappingsRequest; 60 | import com.amazonaws.services.lambda.model.ListEventSourceMappingsResult; 61 | import com.amazonaws.services.lambda.model.RemovePermissionRequest; 62 | import com.amazonaws.services.lambda.model.ResourceNotFoundException; 63 | import com.amazonaws.services.lambda.model.UpdateAliasRequest; 64 | import com.amazonaws.services.lambda.model.UpdateEventSourceMappingRequest; 65 | import com.amazonaws.services.lambda.model.UpdateEventSourceMappingResult; 66 | import com.amazonaws.services.lambda.model.UpdateFunctionConfigurationRequest; 67 | import com.amazonaws.services.lambda.model.VpcConfig; 68 | import com.amazonaws.services.lambda.model.VpcConfigResponse; 69 | import com.amazonaws.services.sns.model.CreateTopicRequest; 70 | import com.amazonaws.services.sns.model.CreateTopicResult; 71 | import com.amazonaws.services.sns.model.ListSubscriptionsResult; 72 | import com.amazonaws.services.sns.model.SubscribeRequest; 73 | import com.amazonaws.services.sns.model.SubscribeResult; 74 | import com.amazonaws.services.sns.model.Subscription; 75 | import com.amazonaws.services.sns.model.UnsubscribeRequest; 76 | import com.amazonaws.services.sqs.model.GetQueueAttributesRequest; 77 | import com.amazonaws.services.sqs.model.GetQueueAttributesResult; 78 | import com.amazonaws.services.sqs.model.GetQueueUrlRequest; 79 | import com.amazonaws.services.sqs.model.GetQueueUrlResult; 80 | import com.amazonaws.services.sqs.model.QueueAttributeName; 81 | 82 | 83 | /** 84 | * I am a deploy mojo responsible to upload and create or update lambda function in AWS. 85 | * 86 | * @author Sean N. Roy, Sean Roy 11/08/16. 87 | */ 88 | @Mojo(name = "deploy-lambda") 89 | public class DeployLambdaMojo extends AbstractLambdaMojo { 90 | 91 | @Override 92 | public void execute() throws MojoExecutionException { 93 | if(checkSkip()) return; 94 | super.execute(); 95 | try { 96 | uploadJarToS3(); 97 | lambdaFunctions.stream().map(f -> { 98 | getLog().info("---- Create or update " + f.getFunctionName() + " -----"); 99 | return f; 100 | }).forEach(lf -> 101 | getFunctionPolicy 102 | .andThen(cleanUpOrphans) 103 | .andThen(createOrUpdate) 104 | .apply(lf)); 105 | } catch (Exception e) { 106 | getLog().error("Error during processing", e); 107 | throw new MojoExecutionException(e.getMessage()); 108 | } 109 | } 110 | 111 | private boolean shouldUpdate(LambdaFunction lambdaFunction, GetFunctionResult getFunctionResult) { 112 | if (ObjectUtils.defaultIfNull(forceUpdate, StringUtils.containsIgnoreCase(version, "SNAPSHOT"))) { 113 | getLog().info("Forcing update for " + lambdaFunction.getFunctionName()); 114 | return true; 115 | } 116 | if (isConfigurationChanged(lambdaFunction, getFunctionResult)) { 117 | return true; 118 | } 119 | getLog().info("Config hasn't changed for " + lambdaFunction.getFunctionName()); 120 | return false; 121 | } 122 | 123 | /* 124 | * Get the existing policy function (on updates) and assign it to the lambdaFunction. 125 | */ 126 | private Function getFunctionPolicy = (LambdaFunction lambdaFunction) -> { 127 | try { 128 | lambdaFunction.setExistingPolicy(Policy.fromJson(lambdaClient.getPolicy(new GetPolicyRequest() 129 | .withFunctionName(lambdaFunction.getFunctionName()) 130 | .withQualifier(lambdaFunction.getQualifier())).getPolicy())); 131 | } catch (ResourceNotFoundException rnfe3) { 132 | getLog().debug("Probably creating a new function, policy doesn't exist yet: " + rnfe3.getMessage()); 133 | } 134 | 135 | return lambdaFunction; 136 | }; 137 | 138 | private Function updateFunctionConfig = (LambdaFunction lambdaFunction) -> { 139 | getLog().info("About to update functionConfig for " + lambdaFunction.getFunctionName()); 140 | UpdateFunctionConfigurationRequest updateFunctionRequest = new UpdateFunctionConfigurationRequest() 141 | .withFunctionName(lambdaFunction.getFunctionName()) 142 | .withDescription(lambdaFunction.getDescription()) 143 | .withHandler(lambdaFunction.getHandler()) 144 | .withRole(lambdaFunction.getLambdaRoleArn()) 145 | .withTimeout(lambdaFunction.getTimeout()) 146 | .withMemorySize(lambdaFunction.getMemorySize()) 147 | .withRuntime(runtime) 148 | .withVpcConfig(getVpcConfig(lambdaFunction)) 149 | .withEnvironment(new Environment().withVariables(lambdaFunction.getEnvironmentVariables())); 150 | lambdaClient.updateFunctionConfiguration(updateFunctionRequest); 151 | return lambdaFunction; 152 | }; 153 | 154 | 155 | private Function createOrUpdateAliases = (LambdaFunction lambdaFunction) -> { 156 | lambdaFunction.getAliases().forEach(alias -> { 157 | UpdateAliasRequest updateAliasRequest = new UpdateAliasRequest() 158 | .withFunctionName(lambdaFunction.getFunctionName()) 159 | .withFunctionVersion(lambdaFunction.getVersion()) 160 | .withName(alias); 161 | try { 162 | lambdaClient.updateAlias(updateAliasRequest 163 | ); 164 | getLog().info("Alias " + alias + " updated for " + lambdaFunction.getFunctionName() + " with version " + lambdaFunction.getVersion()); 165 | } catch (ResourceNotFoundException ignored) { 166 | CreateAliasRequest createAliasRequest = new CreateAliasRequest() 167 | .withFunctionName(lambdaFunction.getFunctionName()) 168 | .withFunctionVersion(lambdaFunction.getVersion()) 169 | .withName(alias); 170 | lambdaClient.createAlias(createAliasRequest); 171 | getLog().info("Alias " + alias + " created for " + lambdaFunction.getFunctionName() + " with version " + lambdaFunction.getVersion()); 172 | } 173 | }); 174 | return lambdaFunction; 175 | }; 176 | 177 | private BiFunction createOrUpdateSNSTopicSubscription = (Trigger trigger, LambdaFunction lambdaFunction) -> { 178 | getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getSNSTopic()); 179 | CreateTopicRequest createTopicRequest = new CreateTopicRequest() 180 | .withName(trigger.getSNSTopic()); 181 | CreateTopicResult createTopicResult = snsClient.createTopic(createTopicRequest); 182 | getLog().info("Topic " + createTopicResult.getTopicArn() + " created"); 183 | 184 | SubscribeRequest subscribeRequest = new SubscribeRequest() 185 | .withTopicArn(createTopicResult.getTopicArn()) 186 | .withEndpoint(lambdaFunction.getUnqualifiedFunctionArn()) 187 | .withProtocol("lambda"); 188 | SubscribeResult subscribeResult = snsClient.subscribe(subscribeRequest); 189 | getLog().info("Lambda function " + lambdaFunction.getFunctionName() + " subscribed to " + createTopicResult.getTopicArn()); 190 | getLog().info("Created " + trigger.getIntegration() + " trigger " + subscribeResult.getSubscriptionArn()); 191 | 192 | 193 | Optional statementOpt; 194 | try { 195 | GetPolicyRequest getPolicyRequest = new GetPolicyRequest() 196 | .withFunctionName(lambdaFunction.getFunctionName()); 197 | GetPolicyResult GetPolicyResult = lambdaClient.getPolicy(getPolicyRequest); 198 | statementOpt = Policy.fromJson(GetPolicyResult.getPolicy()).getStatements().stream() 199 | .filter(statement -> statement.getActions().stream().anyMatch(e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) && 200 | statement.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_SNS.equals(principal.getId())) && 201 | statement.getConditions().stream().anyMatch(condition -> condition.getValues().stream().anyMatch(s -> Objects.equals(createTopicResult.getTopicArn(), s))) 202 | ).findAny(); 203 | } catch (ResourceNotFoundException ignored) { 204 | // no policy found 205 | statementOpt = empty(); 206 | } 207 | 208 | if (!statementOpt.isPresent()) { 209 | AddPermissionRequest addPermissionRequest = new AddPermissionRequest() 210 | .withAction(PERM_LAMBDA_INVOKE) 211 | .withPrincipal(PRINCIPAL_SNS) 212 | .withSourceArn(createTopicResult.getTopicArn()) 213 | .withFunctionName(lambdaFunction.getFunctionName()) 214 | .withStatementId(UUID.randomUUID().toString()); 215 | AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest); 216 | getLog().debug("Added permission to lambda function " + addPermissionResult.toString()); 217 | } 218 | return trigger; 219 | }; 220 | 221 | /** 222 | * TODO: Much of this code can be factored out into an addPermission function. 223 | */ 224 | private BiFunction addAlexaSkillsKitPermission = (Trigger trigger, LambdaFunction lambdaFunction) -> { 225 | if (!ofNullable(lambdaFunction.getExistingPolicy()).orElse(new Policy()).getStatements().stream().anyMatch(s -> 226 | s.getId().equals(getAlexaPermissionStatementId()))) { 227 | getLog().info("Granting invoke permission to " + trigger.getIntegration()); 228 | AddPermissionRequest addPermissionRequest = new AddPermissionRequest() 229 | .withAction(PERM_LAMBDA_INVOKE) 230 | .withPrincipal(PRINCIPAL_ALEXA) 231 | .withFunctionName(lambdaFunction.getFunctionName()) 232 | .withQualifier(lambdaFunction.getQualifier()) 233 | .withStatementId(getAlexaPermissionStatementId()) 234 | .withEventSourceToken(trigger.getAlexaSkillId()); 235 | 236 | AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest); 237 | } 238 | 239 | return trigger; 240 | }; 241 | private String getAlexaPermissionStatementId() { 242 | return "lambda-maven-plugin-alexa-" + regionName + "-permission"; 243 | } 244 | 245 | /** 246 | * TODO: Much of this code can be factored out into an addPermission function. 247 | */ 248 | private BiFunction addLexPermission = (Trigger trigger, LambdaFunction lambdaFunction) -> { 249 | if (!ofNullable(lambdaFunction.getExistingPolicy()).orElse(new Policy()).getStatements().stream().anyMatch(s -> 250 | s.getId().equals(getLexPermissionStatementId(trigger.getLexBotName())))) { 251 | getLog().info("Granting invoke permission to Lex bot " + trigger.getLexBotName()); 252 | AddPermissionRequest addPermissionRequest = new AddPermissionRequest() 253 | .withAction(PERM_LAMBDA_INVOKE) 254 | .withPrincipal(PRINCIPAL_LEX) 255 | .withFunctionName(lambdaFunction.getFunctionName()) 256 | .withQualifier(lambdaFunction.getQualifier()) 257 | .withStatementId(getLexPermissionStatementId(trigger.getLexBotName())); 258 | 259 | AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest); 260 | } 261 | return trigger; 262 | }; 263 | private String getLexPermissionStatementId(String botName) { 264 | return "lambda-maven-plugin-lex-" + regionName + "-permission-" + botName; 265 | } 266 | 267 | private BiFunction createOrUpdateScheduledRule = (Trigger trigger, LambdaFunction lambdaFunction) -> { 268 | // TODO: I hate that these checks are done twice, but for the time being it beats updates that just didn't work. 269 | if ( isScheduleRuleChanged(lambdaFunction) || isKeepAliveChanged(lambdaFunction)) { 270 | getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getRuleName()); 271 | PutRuleRequest putRuleRequest = new PutRuleRequest() 272 | .withName(trigger.getRuleName()) 273 | .withDescription(trigger.getRuleDescription()) 274 | .withScheduleExpression(trigger.getScheduleExpression()); 275 | PutRuleResult putRuleResult = eventsClient.putRule(putRuleRequest); 276 | getLog().info("Created " + trigger.getIntegration() + " trigger " + putRuleResult.getRuleArn()); 277 | 278 | AddPermissionRequest addPermissionRequest = new AddPermissionRequest() 279 | .withAction(PERM_LAMBDA_INVOKE) 280 | .withPrincipal(PRINCIPAL_EVENTS) 281 | .withSourceArn(putRuleResult.getRuleArn()) 282 | .withFunctionName(lambdaFunction.getFunctionName()) 283 | .withStatementId(UUID.randomUUID().toString()); 284 | AddPermissionResult addPermissionResult = lambdaClient.addPermission(addPermissionRequest); 285 | getLog().debug("Added permission to lambda function " + addPermissionResult.toString()); 286 | 287 | PutTargetsRequest putTargetsRequest = new PutTargetsRequest() 288 | .withRule(trigger.getRuleName()) 289 | .withTargets(new Target().withId("1").withArn(lambdaFunction.getUnqualifiedFunctionArn())); 290 | eventsClient.putTargets(putTargetsRequest); 291 | } 292 | return trigger; 293 | }; 294 | 295 | 296 | private Function createOrUpdateKeepAlive = (LambdaFunction lambdaFunction) -> { 297 | if (isKeepAliveChanged(lambdaFunction)) { 298 | ofNullable(lambdaFunction.getKeepAlive()).flatMap(f -> { 299 | if ( f > 0 ) { 300 | getLog().info("Setting keepAlive to " + f + " minutes."); 301 | 302 | createOrUpdateScheduledRule.apply(new Trigger() 303 | .withIntegration("Function Keep Alive") 304 | .withDescription(String.format("This feature pings function %s every %d %s.", 305 | lambdaFunction.getFunctionName(), f, 306 | f > 1 ? "minutes" : "minute")) 307 | .withRuleName(lambdaFunction.getKeepAliveRuleName()) 308 | .withScheduleExpression(lambdaFunction.getKeepAliveScheduleExpression()), 309 | lambdaFunction); 310 | } 311 | 312 | return Optional.of(f); 313 | }); 314 | } 315 | return lambdaFunction; 316 | }; 317 | 318 | private BiFunction createOrUpdateDynamoDBTrigger = (Trigger trigger, LambdaFunction lambdaFunction) -> { 319 | getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getDynamoDBTable()); 320 | ListStreamsRequest listStreamsRequest = new ListStreamsRequest().withTableName(trigger.getDynamoDBTable()); 321 | ListStreamsResult listStreamsResult = dynamoDBStreamsClient.listStreams(listStreamsRequest); 322 | 323 | String streamArn = listStreamsResult.getStreams().stream() 324 | .filter(s -> Objects.equals(trigger.getDynamoDBTable(), s.getTableName())) 325 | .findFirst() 326 | .map(Stream::getStreamArn) 327 | .orElseThrow(() -> new IllegalArgumentException("Unable to find stream for table " + trigger.getDynamoDBTable())); 328 | 329 | return findorUpdateMappingConfiguration(trigger, lambdaFunction, streamArn); 330 | }; 331 | 332 | 333 | private BiFunction createOrUpdateSQSTrigger = (Trigger trigger, LambdaFunction lambdaFunction) -> { 334 | getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getStandardQueue()); 335 | String queueArn = null; 336 | 337 | Optional getQueueUrlOptionalResult = ofNullable(sqsClient.getQueueUrl(new GetQueueUrlRequest() 338 | .withQueueName(trigger.getStandardQueue()))); 339 | 340 | if (getQueueUrlOptionalResult.isPresent()) { 341 | String queueUrl = getQueueUrlOptionalResult.get().getQueueUrl(); 342 | GetQueueAttributesResult getQueueAttributesResult = sqsClient.getQueueAttributes( new GetQueueAttributesRequest() 343 | .withQueueUrl(queueUrl).withAttributeNames(QueueAttributeName.QueueArn)); 344 | 345 | queueArn = getQueueAttributesResult.getAttributes().get(QueueAttributeName.QueueArn.name()); 346 | 347 | } else { 348 | throw new IllegalArgumentException("Unable to find queue " + trigger.getStandardQueue()); 349 | } 350 | 351 | 352 | return findorUpdateMappingConfiguration(trigger, lambdaFunction, queueArn); 353 | }; 354 | 355 | private BiFunction createOrUpdateKinesisStream = (Trigger trigger, LambdaFunction lambdaFunction) -> { 356 | getLog().info("About to create or update " + trigger.getIntegration() + " trigger for " + trigger.getKinesisStream()); 357 | 358 | try { 359 | return findorUpdateMappingConfiguration(trigger, lambdaFunction, 360 | kinesisClient.describeStream(trigger.getKinesisStream()).getStreamDescription().getStreamARN()); 361 | } catch (Exception rnfe) { 362 | getLog().info(rnfe.getMessage()); 363 | throw new IllegalArgumentException("Unable to find stream with name " + trigger.getKinesisStream()); 364 | } 365 | }; 366 | 367 | private Trigger findorUpdateMappingConfiguration(Trigger trigger, LambdaFunction lambdaFunction, String streamArn) { 368 | ListEventSourceMappingsRequest listEventSourceMappingsRequest = new ListEventSourceMappingsRequest() 369 | .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn()); 370 | ListEventSourceMappingsResult listEventSourceMappingsResult = lambdaClient.listEventSourceMappings(listEventSourceMappingsRequest); 371 | 372 | Optional eventSourceMappingConfiguration = listEventSourceMappingsResult.getEventSourceMappings().stream() 373 | .filter(stream -> { 374 | boolean isSameFunctionArn = Objects.equals(stream.getFunctionArn(), lambdaFunction.getUnqualifiedFunctionArn()); 375 | boolean isSameSourceArn = Objects.equals(stream.getEventSourceArn(), streamArn); 376 | return isSameFunctionArn && isSameSourceArn; 377 | }) 378 | .findFirst(); 379 | 380 | if (eventSourceMappingConfiguration.isPresent()) { 381 | UpdateEventSourceMappingRequest updateEventSourceMappingRequest = new UpdateEventSourceMappingRequest() 382 | .withUUID(eventSourceMappingConfiguration.get().getUUID()) 383 | .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn()) 384 | .withBatchSize(ofNullable(trigger.getBatchSize()).orElse(10)) 385 | .withEnabled(ofNullable(trigger.getEnabled()).orElse(true)); 386 | UpdateEventSourceMappingResult updateEventSourceMappingResult = lambdaClient.updateEventSourceMapping(updateEventSourceMappingRequest); 387 | trigger.withTriggerArn(updateEventSourceMappingResult.getEventSourceArn()); 388 | getLog().info("Updated " + trigger.getIntegration() + " trigger " + trigger.getTriggerArn()); 389 | } else { 390 | 391 | CreateEventSourceMappingRequest createEventSourceMappingRequest = new CreateEventSourceMappingRequest() 392 | .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn()) 393 | .withEventSourceArn(streamArn) 394 | .withBatchSize(ofNullable(trigger.getBatchSize()).orElse(10)) 395 | .withEnabled(ofNullable(trigger.getEnabled()).orElse(true)); 396 | // For SQS starting position is not valid 397 | if (!streamArn.contains(":sqs:")) { 398 | createEventSourceMappingRequest.setStartingPosition(EventSourcePosition.fromValue(ofNullable(trigger.getStartingPosition()).orElse(LATEST.toString()))); 399 | } 400 | 401 | CreateEventSourceMappingResult createEventSourceMappingResult = lambdaClient.createEventSourceMapping(createEventSourceMappingRequest); 402 | trigger.withTriggerArn(createEventSourceMappingResult.getEventSourceArn()); 403 | getLog().info("Created " + trigger.getIntegration() + " trigger " + trigger.getTriggerArn()); 404 | } 405 | 406 | return trigger; 407 | } 408 | 409 | private Function createOrUpdateTriggers = (LambdaFunction lambdaFunction) -> { 410 | lambdaFunction.getTriggers().forEach(trigger -> { 411 | if (TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(trigger.getIntegration())) { 412 | createOrUpdateScheduledRule.apply(trigger, lambdaFunction); 413 | } else if (TRIG_INT_LABEL_DYNAMO_DB.equals(trigger.getIntegration())) { 414 | createOrUpdateDynamoDBTrigger.apply(trigger, lambdaFunction); 415 | } else if (TRIG_INT_LABEL_KINESIS.equals(trigger.getIntegration())) { 416 | createOrUpdateKinesisStream.apply(trigger, lambdaFunction); 417 | } else if (TRIG_INT_LABEL_SNS.equals(trigger.getIntegration())) { 418 | createOrUpdateSNSTopicSubscription.apply(trigger, lambdaFunction); 419 | } else if (TRIG_INT_LABEL_ALEXA_SK.equals(trigger.getIntegration())) { 420 | addAlexaSkillsKitPermission.apply(trigger, lambdaFunction); 421 | } else if (TRIG_INT_LABEL_LEX.equals(trigger.getIntegration())) { 422 | addLexPermission.apply(trigger, lambdaFunction); 423 | } else if (TRIG_INT_LABEL_SQS.equals(trigger.getIntegration())) { 424 | createOrUpdateSQSTrigger.apply(trigger, lambdaFunction); 425 | } else { 426 | throw new IllegalArgumentException("Unknown integration for trigger " + trigger.getIntegration() + ". Correct your configuration"); 427 | } 428 | }); 429 | return lambdaFunction; 430 | }; 431 | 432 | private GetFunctionResult getFunction(LambdaFunction lambdaFunction) { 433 | return lambdaClient.getFunction(new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName())); 434 | } 435 | 436 | private boolean isConfigurationChanged(LambdaFunction lambdaFunction, GetFunctionResult function) { 437 | BiPredicate isChangeStr = (s0, s1) -> !Objects.equals(s0, s1); 438 | BiPredicate isChangeInt = (i0, i1) -> !Objects.equals(i0, i1); 439 | BiPredicate, List> isChangeList = (l0, l1) -> !(l0.containsAll(l1) && l1.containsAll(l0)); 440 | return of(function.getConfiguration()) 441 | .map(config -> { 442 | VpcConfigResponse vpcConfig = config.getVpcConfig(); 443 | if (vpcConfig == null) { 444 | vpcConfig = new VpcConfigResponse(); 445 | } 446 | boolean isDescriptionChanged = isChangeStr.test(config.getDescription(), lambdaFunction.getDescription()); 447 | boolean isHandlerChanged = isChangeStr.test(config.getHandler(), lambdaFunction.getHandler()); 448 | boolean isRoleChanged = isChangeStr.test(config.getRole(), lambdaFunction.getLambdaRoleArn()); 449 | boolean isTimeoutChanged = isChangeInt.test(config.getTimeout(), lambdaFunction.getTimeout()); 450 | boolean isMemoryChanged = isChangeInt.test(config.getMemorySize(), lambdaFunction.getMemorySize()); 451 | boolean isSecurityGroupIdsChanged = isChangeList.test(vpcConfig.getSecurityGroupIds(), lambdaFunction.getSecurityGroupIds()); 452 | boolean isVpcSubnetIdsChanged = isChangeList.test(vpcConfig.getSubnetIds(), lambdaFunction.getSubnetIds()); 453 | return isDescriptionChanged || isHandlerChanged || isRoleChanged || isTimeoutChanged || isMemoryChanged || 454 | isSecurityGroupIdsChanged || isVpcSubnetIdsChanged || isAliasesChanged(lambdaFunction) || isKeepAliveChanged(lambdaFunction) || 455 | isScheduleRuleChanged(lambdaFunction); 456 | }) 457 | .orElse(true); 458 | } 459 | 460 | private boolean isKeepAliveChanged(LambdaFunction lambdaFunction) { 461 | try { 462 | return ofNullable(lambdaFunction.getKeepAlive()).map( ka -> { 463 | DescribeRuleResult res = eventsClient.describeRule(new DescribeRuleRequest().withName(lambdaFunction.getKeepAliveRuleName())); 464 | return !Objects.equals(res.getScheduleExpression(), lambdaFunction.getKeepAliveScheduleExpression()); 465 | }).orElse(false); 466 | 467 | } catch( com.amazonaws.services.cloudwatchevents.model.ResourceNotFoundException ignored ) { 468 | return true; 469 | } 470 | } 471 | 472 | private boolean isScheduleRuleChanged(LambdaFunction lambdaFunction) { 473 | try { 474 | return lambdaFunction.getTriggers().stream().filter(t -> TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(t.getIntegration())).anyMatch(trigger -> { 475 | DescribeRuleResult res = eventsClient.describeRule(new DescribeRuleRequest().withName(trigger.getRuleName())); 476 | return !(Objects.equals(res.getName(), trigger.getRuleName()) && 477 | Objects.equals(res.getDescription(), trigger.getRuleDescription()) && 478 | Objects.equals(res.getScheduleExpression(), trigger.getScheduleExpression())); 479 | }); 480 | } catch( com.amazonaws.services.cloudwatchevents.model.ResourceNotFoundException ignored ) { 481 | return true; 482 | } 483 | } 484 | 485 | private boolean isAliasesChanged(LambdaFunction lambdaFunction) { 486 | try { 487 | ListAliasesResult listAliasesResult = lambdaClient.listAliases(new ListAliasesRequest() 488 | .withFunctionName(lambdaFunction.getFunctionName())); 489 | List configuredAliases = listAliasesResult.getAliases().stream() 490 | .map(AliasConfiguration::getName) 491 | .collect(toList()); 492 | return !configuredAliases.containsAll(lambdaFunction.getAliases()); 493 | } catch (ResourceNotFoundException ignored) { 494 | return true; 495 | } 496 | } 497 | 498 | private Function createFunction = (LambdaFunction lambdaFunction) -> { 499 | getLog().info("About to create function " + lambdaFunction.getFunctionName()); 500 | CreateFunctionRequest createFunctionRequest = new CreateFunctionRequest() 501 | .withDescription(lambdaFunction.getDescription()) 502 | .withRole(lambdaFunction.getLambdaRoleArn()) 503 | .withFunctionName(lambdaFunction.getFunctionName()) 504 | .withHandler(lambdaFunction.getHandler()) 505 | .withRuntime(runtime) 506 | .withTimeout(ofNullable(lambdaFunction.getTimeout()).orElse(timeout)) 507 | .withMemorySize(ofNullable(lambdaFunction.getMemorySize()).orElse(memorySize)) 508 | .withVpcConfig(getVpcConfig(lambdaFunction)) 509 | .withCode(new FunctionCode() 510 | .withS3Bucket(s3Bucket) 511 | .withS3Key(fileName)) 512 | .withEnvironment(new Environment().withVariables(lambdaFunction.getEnvironmentVariables())); 513 | 514 | CreateFunctionResult createFunctionResult = lambdaClient.createFunction(createFunctionRequest); 515 | lambdaFunction.withVersion(createFunctionResult.getVersion()) 516 | .withFunctionArn(createFunctionResult.getFunctionArn()); 517 | getLog().info("Function " + createFunctionResult.getFunctionName() + " created. Function Arn: " + createFunctionResult.getFunctionArn()); 518 | 519 | 520 | return lambdaFunction; 521 | }; 522 | 523 | private VpcConfig getVpcConfig(LambdaFunction lambdaFunction) { 524 | return new VpcConfig() 525 | .withSecurityGroupIds(lambdaFunction.getSecurityGroupIds()) 526 | .withSubnetIds(lambdaFunction.getSubnetIds()); 527 | } 528 | 529 | /** 530 | * Remove orphaned kinesis stream triggers. 531 | * TODO: Combine with cleanUpOrphanedDynamoDBTriggers. 532 | */ 533 | Function cleanUpOrphanedKinesisTriggers = lambdaFunction -> { 534 | ListEventSourceMappingsResult listEventSourceMappingsResult = 535 | lambdaClient.listEventSourceMappings(new ListEventSourceMappingsRequest() 536 | .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn())); 537 | 538 | 539 | List streamNames = new ArrayList(); 540 | 541 | // This nonsense is to prevent cleanupOrphanedDynamoDBTriggers from removing DynamoDB triggers 542 | // and vice versa. Unfortunately this assumes that stream names won't be the same as table names. 543 | lambdaFunction.getTriggers().stream().forEach(t -> { 544 | ofNullable(t.getKinesisStream()).ifPresent(x -> streamNames.add(x)); 545 | ofNullable(t.getDynamoDBTable()).ifPresent(x -> streamNames.add(x)); 546 | }); 547 | 548 | listEventSourceMappingsResult.getEventSourceMappings().stream().forEach(s -> { 549 | if ( s.getEventSourceArn().contains(":kinesis:") ) { 550 | if ( ! streamNames.contains(kinesisClient.describeStream(new com.amazonaws.services.kinesis.model.DescribeStreamRequest() 551 | .withStreamName(s.getEventSourceArn().substring(s.getEventSourceArn().lastIndexOf('/')+1))) 552 | .getStreamDescription() 553 | .getStreamName()) ){ 554 | getLog().info(" Removing orphaned Kinesis trigger for stream " + s.getEventSourceArn()); 555 | try { 556 | lambdaClient.deleteEventSourceMapping(new DeleteEventSourceMappingRequest().withUUID(s.getUUID())); 557 | } catch(Exception e8) { 558 | getLog().error(" Error removing orphaned Kinesis trigger for stream " + s.getEventSourceArn()); 559 | } 560 | } 561 | } 562 | }); 563 | 564 | return lambdaFunction; 565 | }; 566 | 567 | /** 568 | * Removes orphaned sns triggers. 569 | */ 570 | Function cleanUpOrphanedSNSTriggers = lambdaFunction -> { 571 | 572 | List subscriptions = new ArrayList(); 573 | ListSubscriptionsResult result = snsClient.listSubscriptions(); 574 | 575 | do { 576 | subscriptions.addAll(result.getSubscriptions().stream().filter( sub -> { 577 | return sub.getEndpoint().equals(lambdaFunction.getFunctionArn()); 578 | }).collect(Collectors.toList())); 579 | 580 | result = snsClient.listSubscriptions(result.getNextToken()); 581 | } while( result.getNextToken() != null ); 582 | 583 | if (subscriptions.size() > 0 ) { 584 | List snsTopicNames = lambdaFunction.getTriggers().stream().map(t -> { 585 | return ofNullable(t.getSNSTopic()).orElse(""); 586 | }).collect(Collectors.toList()); 587 | 588 | subscriptions.stream().forEach(s -> { 589 | String topicName = s.getTopicArn().substring(s.getTopicArn().lastIndexOf(":")+1); 590 | if (!snsTopicNames.contains(topicName)) { 591 | getLog().info(" Removing orphaned SNS trigger for topic " + topicName); 592 | try { 593 | snsClient.unsubscribe(new UnsubscribeRequest().withSubscriptionArn(s.getSubscriptionArn())); 594 | 595 | ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> { 596 | policy.getStatements().stream() 597 | .filter( 598 | stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) && 599 | stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_SNS.equals(principal.getId())) && 600 | stmt.getResources().stream().anyMatch(r -> r.getId().equals(lambdaFunction.getFunctionArn())) 601 | ).forEach( st -> { 602 | if( st.getConditions().stream().anyMatch(condition -> condition.getValues().contains(s.getTopicArn())) ) { 603 | getLog().info(" Removing invoke permission for SNS trigger"); 604 | try { 605 | lambdaClient.removePermission(new RemovePermissionRequest() 606 | .withFunctionName(lambdaFunction.getFunctionName()) 607 | .withQualifier(lambdaFunction.getQualifier()) 608 | .withStatementId(st.getId())); 609 | } catch (Exception e7) { 610 | getLog().error(" Error removing invoke permission for SNS trigger"); 611 | } 612 | } 613 | }); 614 | return of(policy); 615 | }); 616 | 617 | } catch(Exception e5) { 618 | getLog().error(" Error removing SNS trigger for topic " + topicName); 619 | } 620 | } 621 | }); 622 | } 623 | 624 | return lambdaFunction; 625 | }; 626 | 627 | 628 | /** 629 | * Removes orphaned SQS triggers. 630 | */ 631 | Function cleanUpOrphanedSQSTriggers = lambdaFunction -> { 632 | ListEventSourceMappingsResult listEventSourceMappingsResult = 633 | lambdaClient.listEventSourceMappings(new ListEventSourceMappingsRequest() 634 | .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn())); 635 | 636 | 637 | List standardQueues = new ArrayList(); 638 | 639 | lambdaFunction.getTriggers().stream().forEach(t -> { 640 | ofNullable(t.getStandardQueue()).ifPresent(x -> standardQueues.add(x)); 641 | }); 642 | 643 | listEventSourceMappingsResult.getEventSourceMappings().stream().forEach(s -> { 644 | if ( s.getEventSourceArn().contains(":sqs:")) { 645 | // This API hit may not required, added here only for double check or cross verification 646 | Optional getQueueUrlOptionalResult = ofNullable(sqsClient.getQueueUrl(new GetQueueUrlRequest() 647 | .withQueueName(s.getEventSourceArn().substring(s.getEventSourceArn().lastIndexOf(':')+1)))); 648 | 649 | getQueueUrlOptionalResult.ifPresent(queue -> { 650 | String queueName = queue.getQueueUrl().substring(queue.getQueueUrl().lastIndexOf('/')+1); 651 | if ( ! standardQueues.contains(queueName) ) { 652 | getLog().info(" Removing orphaned SQS trigger for queue " + queueName); 653 | try { 654 | lambdaClient.deleteEventSourceMapping(new DeleteEventSourceMappingRequest().withUUID(s.getUUID())); 655 | } catch (Exception exp) { 656 | getLog().error(" Error removing SQS trigger for queue " + queueName + ", Error Message :" + exp.getMessage()); 657 | } 658 | } 659 | } 660 | 661 | ); 662 | } 663 | }); 664 | 665 | return lambdaFunction; 666 | }; 667 | 668 | /** 669 | * Removes orphaned dynamo db triggers. 670 | * TODO: Combine with cleanUpOrphanedKinesisTriggers 671 | */ 672 | Function cleanUpOrphanedDynamoDBTriggers = lambdaFunction -> { 673 | ListEventSourceMappingsResult listEventSourceMappingsResult = 674 | lambdaClient.listEventSourceMappings(new ListEventSourceMappingsRequest() 675 | .withFunctionName(lambdaFunction.getUnqualifiedFunctionArn())); 676 | 677 | 678 | List tableNames = new ArrayList(); 679 | 680 | // This nonsense is to prevent cleanupOrphanedDynamoDBTriggers from removing DynamoDB triggers 681 | // and vice versa. Unfortunately this assumes that stream names won't be the same as table names. 682 | lambdaFunction.getTriggers().stream().forEach(t -> { 683 | ofNullable(t.getKinesisStream()).ifPresent(x -> tableNames.add(x)); 684 | ofNullable(t.getDynamoDBTable()).ifPresent(x -> tableNames.add(x)); 685 | }); 686 | 687 | listEventSourceMappingsResult.getEventSourceMappings().stream().forEach(s -> { 688 | if ( s.getEventSourceArn().contains(":dynamodb:")) { 689 | StreamDescription sd = dynamoDBStreamsClient.describeStream(new DescribeStreamRequest() 690 | .withStreamArn(s.getEventSourceArn())).getStreamDescription(); 691 | 692 | if ( ! tableNames.contains(sd.getTableName()) ) { 693 | getLog().info(" Removing orphaned DynamoDB trigger for table " + sd.getTableName()); 694 | try { 695 | lambdaClient.deleteEventSourceMapping(new DeleteEventSourceMappingRequest().withUUID(s.getUUID())); 696 | } catch (Exception e4) { 697 | getLog().error(" Error removing DynamoDB trigger for table " + sd.getTableName()); 698 | } 699 | } 700 | } 701 | }); 702 | 703 | return lambdaFunction; 704 | }; 705 | 706 | 707 | /** 708 | * Removes the Alexa permission if it isn't found in the current configuration. 709 | * TODO: Factor out code common with other orphan clean up functions. 710 | */ 711 | Function cleanUpOrphanedAlexaSkillsTriggers = lambdaFunction -> { 712 | ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> { 713 | policy.getStatements().stream() 714 | .filter( 715 | stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) && 716 | stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_ALEXA.equals(principal.getId())) && 717 | !lambdaFunction.getTriggers().stream().anyMatch( t -> t.getIntegration().equals(TRIG_INT_LABEL_ALEXA_SK))) 718 | .forEach( s -> { 719 | try { 720 | getLog().info(" Removing orphaned Alexa permission " + s.getId()); 721 | lambdaClient.removePermission(new RemovePermissionRequest() 722 | .withFunctionName(lambdaFunction.getFunctionName()) 723 | .withQualifier(lambdaFunction.getQualifier()) 724 | .withStatementId(s.getId())); 725 | } catch (ResourceNotFoundException rnfe1) { 726 | getLog().error(" Error removing permission for " + s.getId() + ": " + rnfe1.getMessage()); 727 | } 728 | }); 729 | return of(policy); 730 | }); 731 | 732 | return lambdaFunction; 733 | }; 734 | 735 | /** 736 | * Removes any Lex permissions that aren't found in the current configuration. 737 | * TODO: Factor out code common with other orphan clean up functions. 738 | */ 739 | Function cleanUpOrphanedLexSkillsTriggers = lambdaFunction -> { 740 | ofNullable(lambdaFunction.getExistingPolicy()).flatMap( policy -> { 741 | policy.getStatements().stream() 742 | .filter(stmt -> stmt.getActions().stream().anyMatch( e -> PERM_LAMBDA_INVOKE.equals(e.getActionName())) && 743 | stmt.getPrincipals().stream().anyMatch(principal -> PRINCIPAL_LEX.equals(principal.getId())) && 744 | !lambdaFunction.getTriggers().stream().anyMatch( t -> stmt.getId().contains(ofNullable(t.getLexBotName()).orElse("")))) 745 | .forEach( s -> { 746 | try { 747 | getLog().info(" Removing orphaned Lex permission " + s.getId()); 748 | lambdaClient.removePermission(new RemovePermissionRequest() 749 | .withFunctionName(lambdaFunction.getFunctionName()) 750 | .withQualifier(lambdaFunction.getQualifier()) 751 | .withStatementId(s.getId())); 752 | } catch (Exception ign2) { 753 | getLog().error(" Error removing permission for " + s.getId() + ign2.getMessage() ); 754 | } 755 | }); 756 | return of(policy); 757 | }); 758 | 759 | return lambdaFunction; 760 | }; 761 | 762 | Function cleanUpOrphanedCloudWatchEventRules = lambdaFunction -> { 763 | // Get the list of cloudwatch event rules defined for this function (if any). 764 | List existingRuleNames = cloudWatchEventsClient.listRuleNamesByTarget(new ListRuleNamesByTargetRequest() 765 | .withTargetArn(lambdaFunction.getFunctionArn())).getRuleNames(); 766 | 767 | // Get the list of cloudwatch event rules to be defined for this function (if any). 768 | List definedRuleNames = lambdaFunction.getTriggers().stream().filter( 769 | t -> TRIG_INT_LABEL_CLOUDWATCH_EVENTS.equals(t.getIntegration())).map(t -> { 770 | return t.getRuleName(); 771 | }).collect(toList()); 772 | 773 | // Add the keep alive rule name if the user has disabled keep alive for the function. 774 | ofNullable(lambdaFunction.getKeepAlive()).ifPresent(ka -> { 775 | if ( ka > 0 ) { 776 | definedRuleNames.add(lambdaFunction.getKeepAliveRuleName()); 777 | } 778 | }); 779 | 780 | // Remove all of the rules that will be defined from the list of existing rules. 781 | // The remainder is a set of event rules which should no longer be associated to this 782 | // function. 783 | existingRuleNames.removeAll(definedRuleNames); 784 | 785 | // For each remaining rule, remove the function as a target and attempt to delete 786 | // the rule. 787 | existingRuleNames.stream().forEach(ern -> { 788 | getLog().info(" Removing CloudWatch Event Rule: " + ern); 789 | cloudWatchEventsClient.removeTargets(new RemoveTargetsRequest() 790 | .withIds("1") 791 | .withRule(ern)); 792 | try { 793 | cloudWatchEventsClient.deleteRule(new DeleteRuleRequest().withName(ern)); 794 | } catch (Exception e) { 795 | getLog().error(" Error removing orphaned rule: " + e.getMessage()); 796 | } 797 | }); 798 | 799 | return lambdaFunction; 800 | }; 801 | 802 | Function cleanUpOrphans = lambdaFunction -> { 803 | try { 804 | lambdaFunction.setFunctionArn(lambdaClient.getFunction( 805 | new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName())).getConfiguration().getFunctionArn()); 806 | 807 | getLog().info("Cleaning up orphaned triggers."); 808 | 809 | // Add clean up orphaned trigger functions for each integration here: 810 | cleanUpOrphanedCloudWatchEventRules 811 | .andThen(cleanUpOrphanedDynamoDBTriggers) 812 | .andThen(cleanUpOrphanedKinesisTriggers) 813 | .andThen(cleanUpOrphanedSNSTriggers) 814 | .andThen(cleanUpOrphanedAlexaSkillsTriggers) 815 | .andThen(cleanUpOrphanedLexSkillsTriggers) 816 | .andThen(cleanUpOrphanedSQSTriggers) 817 | .apply(lambdaFunction); 818 | 819 | } catch (ResourceNotFoundException ign1) { 820 | getLog().debug("Assuming function has no orphan triggers to clean up since it doesn't exist yet."); 821 | } 822 | 823 | return lambdaFunction; 824 | }; 825 | 826 | Function createOrUpdate = lambdaFunction -> { 827 | try { 828 | lambdaFunction.setFunctionArn(lambdaClient.getFunction( 829 | new GetFunctionRequest().withFunctionName(lambdaFunction.getFunctionName())).getConfiguration().getFunctionArn()); 830 | of(getFunction(lambdaFunction)) 831 | .filter(getFunctionResult -> shouldUpdate(lambdaFunction, getFunctionResult)) 832 | .map(getFujnctionResult -> 833 | updateFunctionCode 834 | .andThen(updateFunctionConfig) 835 | .andThen(createOrUpdateAliases) 836 | .andThen(createOrUpdateTriggers) 837 | .andThen(createOrUpdateKeepAlive) 838 | .apply(lambdaFunction)); 839 | } catch (ResourceNotFoundException ign) { 840 | createFunction.andThen(createOrUpdateAliases) 841 | .andThen(createOrUpdateTriggers) 842 | .apply(lambdaFunction); 843 | } 844 | 845 | return lambdaFunction; 846 | }; 847 | } 848 | --------------------------------------------------------------------------------