How to deploy environment variable using serverless deploy for AWS lambda - amazon-web-services

I am new to AWS lambda i have i am using serveless deploy to deploy my lambda function declared in serverless.yml file.
In that file i wrote a lambda function i deployed and it is working fine but problem is that whatever environment variable i gave is not available in console of that lambda function. I might be doing some minor mistake or for deploying environment variable there should be some other syntax.
I can go to lambda function in console and add environment variable manually.
But my doubt is can we do it while deploying it through serverless deploy

You can use versions and aliases provided by AWS Lambda
You can create different versions of the same lambda function and give them an alias. Like when you push your lambda code - create a version (say it's 5) - create an alias this (say TEST).
When you're sure that its ready for production, create a version(or choose an existing version and name that (say PROD).
Now whenever your lambda function executes, it gives lambda ARN
which contains alias, by that you can know which alias(in context.invokedFunctionArn) is
executed i.e. that can be used as the environment variable. While
invoking the function, you can mention which function to execute from
your invocation code.
let thisARN = context.invokedFunctionArn;
// Get the last string in ARN - It's either function name or the alias name
let thisAlias = thisARN.split(":").pop();
Now whenever you deploy a new code, just point the alias to that version.
You can use AWS console or CLI for that.
Take a look at this lambda versioning and aliases
For directly deploying to your alias(PROD), you can do this -
aws lambda update-alias \
--region region \
--function-name helloworld \
--function-version 2 \
--name PROD

serverless deploy
Serverless deploy works fine for deployment on any stage it also deploys environment variable in given stage, my case environment variable was not deployed of indentation problem in yaml file, and even serverless deploy command was not throwing error it was deploying function but environment variables were not deployed
In yaml file we can state the the stage where we want to deploy like this
provider:
name: aws
runtime: nodejs6.10
stage: dev
region: eu-west-2
Hope this will help if someone gets similar issue

Related

AWS CDK accessing parameters when deploying stacks on the pipeline via yaml, typescript and nodejs

I'm fairly new to AWS and using the CDK but have been working on a project which deploys to AWS via a pipeline using yaml for the cf-template and later a node script to run cdk deploy on a set of stack files that have been written in Typescript.
In the cf-template yaml where the cdk-toolkit is being defined there's a bucket resource with name X. After the toolkit has been created/updated in the pipeline, the cdk deploy command is executed to deploy some stacks and workers, which should live in bucket X. They aren't automatically being uploaded there however, so I've tried using the --parameters flag to specify X as below.
cdk deploy --toolkit-stack-name my-toolkit --parameters uploadBucketName=X --ci --require-approval never
When I do this I get the following error in the pipeline for the first stack that gets deployed:
Parameters: [uploadBucketName] do not exist in the template
I assumed this meant that in the MyFirstStack.ts file it was missing a parameter definition as suggested by the AWS documentation, but it's not clear to me why this is necessary or how it's supposed to be used when it's the cdk deploy command which provides a value for this parameter. I tried adding it per the docs
const uploadBucketName = new CfnParameter(this, "uploadBucketName", {
type: "String",
description: "The name of the Amazon S3 bucket where uploaded files will be stored."});
but not sure if this is really the right thing to do, and it doesn't work besides - I still get the same error.
Does anyone have any ideas where I'm going wrong?

Both SAM and cdk can make stack, SAM include cdk ? or cdk include SAM?

I want to make two bucket(x,y) in S3 and make a lambda.
My goal is uploading files to S3(x) and it triggers lambda then lambda create and put file in S3(y)
Currently, I am developing lambda function on SAM.
Deploying lambda function by SAM
And I made two S3 buckets by cdk.
Then manually adding trigger and Iam policy to lambda to access S3
However I want to do this all automatically.
So my idea is ,
SAM can make two S3 bucket as stack and I don't need cdk anymore ?
cdk can include SAM development environment?
Any other way??
What is the best practice for this purpose??
My `solution is
Local development with SAM
AWS deployment is carried out by cdk only, SAM doesn't work anything for deployment.
My folder structure is below
cdk / bin
lib
cdk.json
etc
samproj/helloworld/app.py
/samconfig.toml
/template.yaml
/etc
For local developing, in samproj directory, do something like this, tutorial.
sam local invoke "HelloWorldFunction" -e events/event.json
And for AWS deployment by cdk project .
Just make lambda directly from samproj/helloworld directory in Stack.
export class CdkVrBaseStack extends Stack {
const lambda_ = new lambda.Function(this, 'TestLambda', {
functionName: 'testLambda',
runtime: lambda.Runtime.PYTHON_3_9,
code: lambda.Code.fromAsset('samproj/helloworld'),
handler: 'index.handler',
timeout: cdk.Duration.seconds(300),

AWS CloudFormation pseudo parameters are incorrect locally

I am working on AWS Serverless application using SAM. My template.yaml has this line for defining an S3 bucket name:
BucketName: !Sub ${AWS::StackName}-visit-attachments-${AWS::AccountID}
When I deploy to AWS using sam deploy the variables are substituted correctly.
But when I execute the lambda function locally, the resulting string is local-visit-attachments-123456789012. I can't find where the local and 123456789012 are coming from since I don't have them anywhere in the configs.
How can I make it so it uses the same values locally as when I deploy to AWS?
sam local invoke takes --env-vars parameter. You should be able to overwrite these default values by setting AWS_REGION and AWS_ACCOUNT_ID.

AWS SAM update function code of lambda of an API Gateway

I am using CloudFormation with SAM to deploy a stack which contains:
S3 Bucket
Cognito
AWS::Serverless::Api
AWS::Serverless::Function (authorizers + microservices, Type: Api and endpoints of the API Gateway)
Log Groups
To deploy my stack, I first run aws cloudformation package to package the lambda and then run aws cloudformation deploy to deploy the generated stack. This is working.
My goal now is to be able to update a microservice without deploying the entire stack (not building authorizers and other microservices), similar to serverless deploy function in the Serverless framework. This should preferably be one reusable template that uses a macro or just replaces text in the file.
The problem I am facing with this:
Running aws lambda update-function-code requires the lambda to be redeployed
To redeploy the lambda I have to declare AWS::Serverless::Function. For the function to be part of the API Gateway, AWS::Serverless::Api must be declared as well.
Declaring AWS::Serverless::Api requires all the other functions to be defined or they will be removed from the API Gateway.
I feel like I am stuck here and have not found other options of achieving my goal.
Since you're using SAM, I'd recommend deploying and updating your application using the sam cli commands.
You can run
sam build
sam package
sam deploy
When you run sam deploy, it deploys your application, but all subsequent sam deploy commands will update your existing cloudformation stack with only the appropriate resources that need updating.
If you opt for keeping with the standard Cloudformation cli commands, you could use the aws cloudformation update-stack command so that you're not re-deploying an entire new stack.

CodeDeploy can't find my AWS Lambda Function

I have an Issue with CodeDeploy and AWS Lambda when they work inside AWS CodePipeline. This is my setup:
Source GitHub
AWS CodeBuild
AWS CodeDeploy
The Issue
Step 1. and 2. work without a problem, but when it comes to CodeDeploy I get the following error:
Action execution failed BundleType must be either YAML or JSON
If I unzip the Artifact generated by CodeBuild all the files are in place.
If I try to manually deploy to AWS Lambda from CodeDeploy I then get a different message...
Deployment Failed The deployment failed because either the target
Lambda function FUNCTION_NAME does not exist or the specified function
version or alias cannot be found
This is very confusion as to which Error message is valid, or if they are the same but have a different Error message.
The Setup
The ARN of the function is:
arn:aws:lambda:us-east-1:239748505547:function:email_submition
The ARN for the Alias is:
arn:aws:lambda:us-east-1:239748505547:function:email_submition:default
And my appspec.yml file has the following content
version: 0.0
Resources:
- email_submition:
Type: AWS::Lambda::Function
Properties:
Name: "email_submition"
Alias: "default"
CurrentVersion: "1"
TargetVersion: "2"
And the folder structure of the project is:
.gitignore
appspec.yml
buildspec.yml
index.js
README.md
Question
What am I missing in this configuration?
So really this should be a comment not an answer. I do not have 50 rep yet so it's here.
I am having the same issues as you. I'm not sure if you found a solution or not. I was able to successfully execute a deployment with the following appspec.yml:
version: 0.0
Resources:
- mylambdafunction:
Type: AWS::Lambda::Function
Properties:
Name: "mylambdafunction"
Alias: "staging"
CurrentVersion: "2"
TargetVersion: "3"
Both the current version and target version had to exist before CodeDeploy would work. Of course I've tested this by doing a manual deployment.
I think what is needed here is something that actually updates the code and creates a new version. Which is what I would have thought CodeDeploy would do.
Edit: Further research has yielded information about CodePipeline I hadn't realized.
Per here it looks like to run through the Pipeline you need your buildspec, appspec, and a cft. The reason the pipeline fails is because you need to include a CloudFormation Template for the lambda function, this is what deploys the actual code. The appspec.yml is there to migrate traffic from the old version to the new version but the cft is what does the deployment of new code.
Edit2: This example app got me squared away.
Use CodeBuild to build your app but also to generate your CFT for doing actual deployment. This means you build your CFT with the lambda resource.
This removes appspec completely from the resources and instead you use a CFT to define the Lambda function. Here is a link to the SAM docs.
I can not help you with the CodeBuild part as I use a 3rd party CI solution but maybe I can help with the rest.
I think there is a mistake in the AWS documentation as I've never been able to get this to work either. They say to call "aws deploy push" on the command line and give it your appspec.yml file instead of a zip for Lambda, but no matter what you do, you will always get the error:
Action execution failed BundleType must be either YAML or JSON
I think this is because push automatically calls "register-application-revision" after it uploads. If you split this into separate parts, this will work.
Your appspec.yml should look like the
version: 0.0
Resources:
- YourFunctionName:
Type: "AWS::Lambda::Function"
Properties:
Name: "YourFunctionName"
Alias: "YourFunctionNameAlias"
CurrentVersion: "CurrentAliasVersionGoesHere"
TargetVersion: "NewlyPublishedVersionGoesHere"
The version you use should be the version the current alias is attached to. The target version should be the new version you just published (see below) This part still confusing me a bit. I don't understand why it can't figure out what the current version the alias is pointing to by itself.
Also, note that you can always just upload new code for your Lambda code with update-function-code and it will overwrite the latest version. Or you can publish which will create a new version and always just call the latest version. CodeDeploy is only necessary if you want to do some fancy gradually deployment or have different versions for test and live code.
I'd try the following:
Publish your lambda function:
aws lambda update-function-code --function-name YourFunction --zip-file fileb://~/your-code.zip --publish
Take note of the version number it created
Upload your appspec.yml file to S3
aws s3 cp appspec.yml s3://your-deploy-bucket/your-deploy-dir/appspec.yml
Register your application revision:
aws deploy register-application-revision --application-name YourApplcationName --s3-location bucket=your-deploy-bucket,key=your-deploy-dir/appspec.yml,bundleType=YAML
From the CLI this won't appear to do anything, but it did.
Get the application revision to make sure it worked
aws deploy get-application-revision --application-name YourApplcationName --s3-location bucket=your-deploy-bucket,key=your-deploy-dir/appspec.yml,bundleType=YAML
Create a deployment to deploy your code
aws deploy create-deployment --s3-location bucket=your-deploy-bucket,key=your-deploy-dir/appspec.yml,bundleType=YAML