How to rename the aws lambda function without changing anything in it - aws-lambda

Earlier my function in serverless was:
functions:
fun:
handler: file.handler
name: ${opt:stage, self:provider.stage}-lambda-fun
environment: ${file(env.yml):${self:provider.stage}.lambda-fun}
timeout : 180
memorySize : 1024
I want to change fun with some meaningful name, So I changes it as:
Earlier my function in serverless was:
functions:
my-fun:
handler: file.handler
name: ${opt:stage, self:provider.stage}-lambda-fun
environment: ${file(env.yml):${self:provider.stage}.lambda-fun}
timeout : 180
memorySize : 1024
Now When I deployed this function through serverless, Got the below error:
An error occurred while provisioning your stack: my-funLogGroup
- /aws/lambda/lambda-fun already exists
Please help me What I can do more to do this.

Try removing the stack first using serverless remove and then redeploy.

It's not the exact same issue but this github issue gives an alternative soulution: Cannot rename Lambda functions #108
I commented the function definition I wanted to rename and the resources with references to it, then sls deploy , uncommented and sls deploy again.
The problem with this is that the first deploy will delete the function so you have to take into account this down time.

Related

Serverless framework - schedule rate "cron" not yet supported

I am using "serverless": "^2.43.1".
I am following official docs from:
https://www.serverless.com/examples/aws-node-scheduled-cron
but.. this does not seems to work at all..
All I get is:
schedule rate "cron" not yet supported!
scheduler: invalid, schedule syntax
Scheduling [my lambda name] cron: [undefined] input: undefined
Tried with official example:
functions:
myHandler:
handler: handler.run
events:
- schedule: cron(0/2 * ? * MON-FRI *)
Or even just to invoke it every minute:
functions:
myHandler:
handler: handler.run
events:
- schedule: cron(* * * * *)
but the error persist and lambda is not invoked both locally (serverless offline) and on AWS cloud
Can you help me with that?
use rate format !
- schedule: rate(1 minute)
1.install serverless-offline-scheduler npm package
And add the same plugin to your serverless.yml file
plugins:
serverless-webpack
serverless-offline
serverless-offline-scheduler

serverless - Type Error: Cannot read property 'Properties' of undefined

When issuing serverless deploy --region eu-central-1, I get the error
Type Error ---------------------------------------------
Cannot read property 'Properties' of undefined
For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
This error only started after including
plugins:
- serverless-iam-roles-per-function
and can be reverted by commenting the plugin out. But I would like to use it for giving my lambda access to a DynamoDB.
The internet is pretty void about this error besides this typo. The error is not solved by a recent update (yet) and the notice of serverless doesn't help much. set SLS_DEBUG=*" before deployment yields:
Type Error ----------------------------------------------
TypeError: Cannot read property 'Properties' of undefined
at ServerlessIamPerFunctionPlugin.createRoleForFunction (C:\Users\XXXXX\MyProject\node_modules\serverless-iam-roles-per-function\dist\lib\index.js:273:25)
at ServerlessIamPerFunctionPlugin.createRolesPerFunction (C:\Users\XXXXX\MyProject\node_modules\serverless-iam-roles-per-function\dist\lib\index.js:383:18)
at PluginManager.invoke (C:\snapshot\serverless\lib\classes\PluginManager.js:579:20)
at async PluginManager.spawn (C:\snapshot\serverless\lib\classes\PluginManager.js:601:5)
at async Object.before:deploy:deploy [as hook] (C:\snapshot\serverless\lib\plugins\deploy.js:60:11)
at async PluginManager.invoke (C:\snapshot\serverless\lib\classes\PluginManager.js:579:9)
at async PluginManager.run (C:\snapshot\serverless\lib\classes\PluginManager.js:639:7)
at async Serverless.run (C:\snapshot\serverless\lib\Serverless.js:452:5)
at async C:\snapshot\serverless\scripts\serverless.js:751:9
For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
Should I iunclude my serverless.yml in this post? It's quite large.
Using some different key words I retrieved a second (!) online search result, quoting:
The plugin doesn't support working with the role property. You have the following in your provider sections: role: arn-for-deployment-role'. Try removing this.
More info here
This basically solves the issue and serverless-iam-roles-per-function worked after commenting out this:
provider:
name: aws
runtime: python3.7
#iam:
# role: CallsTableQueryRole
The reason for this could be, that previos versions (serverless < v2.24.0) used a different syntax than current ones. Compare:
provider:
#previously:
iam:
role:
statements:
#≥ v2.24.0
iamRoleStatements:
If you're using Bref framework make sure to update bref in composer and serverless globally to the latest version

Unable to invoke aws lambda locally using sls

Im using sls framework to launch my code and it was working fine until today.
serverless.yml's configuration wasnt modified and ive tried reinstalling sls but nothing seems to work.
The following message occurs for all my repos after throwing the following command:
sls invoke local -f function_name --accountId $accountId
Error message:
TypeError: Cannot read property 'Fn::ImportValue' of undefined
at /usr/local/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/index.js:188:22
at Array.map (<anonymous>)
at /usr/local/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/index.js:187:53
at tryCatcher (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/util.js:16:23)
at Function.Promise.attempt.Promise.try (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/method.js:39:29)
at AwsInvokeLocal.loadEnvVars (/usr/local/lib/node_modules/serverless/lib/plugins/aws/invokeLocal/index.js:154:25)
at AwsInvokeLocal.tryCatcher (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/promise.js:547:31)
at Promise._settlePromise (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/promise.js:604:18)
at Promise._settlePromise0 (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/promise.js:649:10)
at Promise._settlePromises (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/promise.js:729:18)
at _drainQueueStep (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:93:12)
at _drainQueue (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:86:9)
at Async._drainQueues (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:102:5)
at Immediate.Async.drainQueues [as _onImmediate] (/usr/local/lib/node_modules/serverless/node_modules/bluebird/js/release/async.js:15:14)
at processImmediate (internal/timers.js:456:21)
at process.topLevelDomainCallback (domain.js:137:15)```
Fixed by specifying the stage
I encountered the same issue and resolved it by specifying the stage with -s <STAGE> when executing sls invoke local.
Why this worked for me
I'm using serverless-dotenv-plugin, which lets me split my .env files by stage like so:
.env.dev
.env.test
.env.prod
Adding the stage helps specify which .env file to use with your local invocation. Without it, Serverless was trying to import .env with no stage appended, which doesn't exist on my project.
I was experiencing the same issue as well. It turns out that the latest version of Serverless seems to have bug. Downgrading to a previous version of sls fixed mine. I downgraded to verion 1.80, and it works fine now.
I figured out what's wrong. There was a warning while the invocation was running:
Serverless Warning --------------------------------------
A valid environment variable to satisfy the declaration 'env:MY_API_KEY' could not be found.
Since it was a warning I just ignored it and it previously worked but apparently the framework doesnt like it now. Dealing with the warning either by removing the variable or defining it resolved my issue.
For me all the environment variables had to be initialized for resolving error.
Serverless Warning --------------------------------------
A valid environment variable to satisfy the declaration 'env:<variable>' could not be found.
So I did this -
export <variable>=""
I got stuck with this issue as well. The reason is the environment variables defined in serverless.yml was not in the local .env file.
name: ...
handler: ...
environment:
API_KEY: ${env:API_KEY}
STAGE: ${self:provider.stage}
Here, API_KEY and STAGE should exist in .env.

How to write a policy in .yaml for a python lambda to read from S3 using the aws sam cli

I am trying to deploy a python lambda to aws. This lambda just reads files from s3 buckets when given a bucket name and file path. It works correctly on the local machine if I run the following command:
sam build && sam local invoke --event testfile.json GetFileFromBucketFunction
The data from the file is printed to the console. Next, if I run the following command the lambda is packaged and send to my-bucket.
sam build && sam package --s3-bucket my-bucket --template-file .aws-sam\build\template.yaml --output-template-file packaged.yaml
The next step is to deploy in prod so I try the following command:
sam deploy --template-file packaged.yaml --stack-name getfilefrombucket --capabilities CAPABILITY_IAM --region my-region
The lambda can now be seen in the lambda console, I can run it but no contents are returned, if I change the service role manually to one which allows s3 get/put then the lambda works. However this undermines the whole point of using the aws sam cli.
I think I need to add a policy to the template.yaml file. This link here seems to say that I should add a policy such as one shown here. So, I added:
Policies: S3CrudPolicy
Under 'Resources:GetFileFromBucketFunction:Properties:', I then rebuild the app and re-deploy and the deployment fails with the following errors in cloudformation:
1 validation error detected: Value 'S3CrudPolicy' at 'policyArn' failed to satisfy constraint: Member must have length greater than or equal to 20 (Service: AmazonIdentityManagement; Status Code: 400; Error Code: ValidationError; Request ID: unique number
and
The following resource(s) failed to create: [GetFileFromBucketFunctionRole]. . Rollback requested by user.
I delete the stack to start again. My thoughts were that 'S3CrudPolicy' is not an off the shelf policy that I can just use but something I would have to define myself in the template.yaml file?
I'm not sure how to do this and the docs don't seem to show any very simple use case examples (from what I can see), if anyone knows how to do this could you post a solution?
I tried the following:
S3CrudPolicy:
PolicyDocument:
-
Action: "s3:GetObject"
Effect: Allow
Resource: !Sub arn:aws:s3:::${cloudtrailBucket}
Principal: "*"
But it failed with the following error:
Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Invalid template property or properties [S3CrudPolicy]
If anyone can help write a simple policy to read/write from s3 than that would be amazing? I'll need to write another one so get lambdas to invoke others lambdas as well so a solution here (I imagine something similar?) would be great? - Or a decent, easy to use guide of how to write these policy statements?
Many thanks for your help!
Found it!! In case anyone else struggles with this you need to add the following few lines to Resources:YourFunction:Properties in the template.yaml file:
Policies:
- S3CrudPolicy:
BucketName: "*"
The "*" will allow your lambda to talk to any bucket, you could switch for something specific if required. If you leave out 'BucketName' then it doesn't work and returns an error in CloudFormation syaing that S3CrudPolicy is invalid.

drone.io 0.5 slack no longer working

We had slack notification working in drone.io 0.4 just fine, but since we updated to 0.5 I can't get it working despite trying out the documentation.
Before, it was like this
build:
build and deploy stuff...
notify:
slack:
webhook_url: $$SLACK_WEBHOOK_URL
channel: continuous_integratio
username: drone
You can see here that I used the $$ to reference the special drone config file of old.
Now my latest attempt looks like this
pipeline:
build and deploy stuff...
slack:
image: plugins/slack
webhook: https://hooks.slack.com/services/...
channel: continuous_integratio
username: drone
According to the documentation slack is now indented within the pipeline (previously build) level.
I tried changing slack out for notify like it was before, used the SLACK_WEBHOOK secret only via the drone cli and there where other things I attempted as well.
Does anyone know what I might be doing wrong?
This is an (almost exact) yaml I am using with slack notification enabled with the exception that I've masked the credentials
pipeline:
build:
image: golang
commands:
- go build
- go test
slack:
image: plugins/slack
webhook: https://hooks.slack.com/services/XXXXXXXXX/YYYYYYYYY/ZZZZZZZZZZZZZZZZZZZZZZZZ
when:
status: [ success, failure ]
There is unfortunately nothing in your example that jumps out, perhaps with the exception of the channel name having a typo (although I'm not sure if that represents your real yaml configuration or not)
If you are attempting to use secrets (via the cli) you need to make sure you sign your yaml file and commit the signature file to your repository. You can then reference your secret in the yaml similar to 0.4 but with a slightly different syntax:
pipeline:
build:
image: golang
commands:
- go build
- go test
slack:
image: plugins/slack
webhook: ${SLACK_WEBHOOK}
when:
status: [ success, failure ]
You can read more about secrets at http://readme.drone.io/usage/secret-guide/
You can also invoke the plugin directly from the command line to help test different input values. This can help with debugging. See https://github.com/drone-plugins/drone-slack#usage
The issue was that in 0.4 the notify plugin was located outside the scope of the pipeline (then build) and now since 0.5 its located inside the pipeline. This combined with the fact that when a pipeline fails it quits the scope immediately, which means the slack (then notify) step never get's reached at all anymore.
The solution to this is to just explicitly tell it to execute the step on failure with the when command:
when:
status: [ success, failure ]
This is actually mentioned in the getting-started guide, though, but I didn't go through till the end as I was aiming to quickly get it up and running and didn't worry about what I considered to be edge cases.

Resources