Bootstrap FreeKB - Amazon Web Services (AWS) - Create your first Serverless Application Model (SAM) Hello World app
Amazon Web Services (AWS) - Create your first Serverless Application Model (SAM) Hello World app

Updated:   |  Amazon Web Services (AWS) articles

This assumes you have already installed the AWS Serverless Application Model (SAM) CLI. If not, check out my article Download and Install the AWS Serverless Application Model (SAM) CLI on Linux.

Move into the /tmp directory.

cd /tmp

 

Run the sam init command. In the prompt, let's make the following selections.

  • Which template source would you like to use = 1 - AWS Quick Start Templates
  • Choose an AWS Quick Start application template = 1 - Hello World Example
  • Use the most popular runtime and package type? (Python and zip) [y/N] = y
  • Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N] = N
  • Would you like to enable monitoring using CloudWatch Application Insights? [y/N] = N
  • Project name [sam-app]: press enter to use sam-app

There should now be a directory named /tmp/sam-app and inside the sam-app directory should be some Python files, YAML files and directories.

]$ ll /tmp/sam-app/
total 20
drwxrwxr-x 2 ec2-user ec2-user   24 Nov 16 02:13 events
drwxrwxr-x 2 ec2-user ec2-user   63 Nov 16 02:13 hello_world
-rw-rw-r-- 1 ec2-user ec2-user    0 Nov 16 02:13 __init__.py
-rw-rw-r-- 1 ec2-user ec2-user 8329 Nov 16 02:13 README.md
-rw-rw-r-- 1 ec2-user ec2-user  679 Nov 16 02:13 samconfig.toml
-rw-rw-r-- 1 ec2-user ec2-user 1681 Nov 16 02:13 template.yaml
drwxrwxr-x 4 ec2-user ec2-user   80 Nov 16 02:13 tests

 

This example requires Python 3.9. Often, your default python3 installation will be some other version of Python.

]$ python3 --version
Python 3.7.15

 

If you do not have Python 3.9 installed on your system, check out my article Install Python on Linux. If you follow my article, you should end up with Python 3.9 at /usr/local/bin/python3.9.6/bin/python3.9.

~]$ /usr/local/bin/python3.9.6/bin/python3.9 --version
Python 3.9.6

 

Let's make sure /usr/local/bin is in your $PATH.

~]$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/ec2-user/.local/bin:/home/ec2-user/bin

 

If /usr/local/bin is not in your $PATH let's add /usr/local/bin to your $PATH.

export PATH=$PATH:/usr/local/bin/python3.9.6/bin/

 

Let's move into the sam-app directory.

cd /tmp/sam-app/

 

And run sam build.

]$ sam build
Starting Build use cache
Manifest file is changed (new hash: 3298f13049d19cffaa37ca931dd4d421) or dependency folder (.aws-sam/deps/61826041-56e6-405d-a032-fa521eb522af) is missing for (HelloWorldFunction), downloading dependencies and copying/building source
Building codeuri: /tmp/sam-hello-world/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
 Running PythonPipBuilder:CleanUp
 Running PythonPipBuilder:ResolveDependencies
 Running PythonPipBuilder:CopySource
 Running PythonPipBuilder:CopySource

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided

 

The sam build command will create the hidden .aws-sam directory, and there should be files and directories in the .aws-sam directory.

~]$ ls -lisa /tmp/sam-app/.aws-sam/
total 4
 5506085 0 drwxrwxr-x 5 ec2-user ec2-user  62 Nov 16 02:44 .
12596741 0 drwxrwxr-x 6 ec2-user ec2-user 165 Nov 16 02:44 ..
11067259 0 drwxr-xr-x 3 ec2-user ec2-user  53 Nov 16 02:45 build
 5506086 4 -rw-rw-r-- 1 ec2-user ec2-user 385 Nov 16 02:45 build.toml
14939178 0 drwxr-xr-x 2 ec2-user ec2-user   6 Nov 16 02:44 cache
  433415 0 drwxr-xr-x 3 ec2-user ec2-user  50 Nov 16 02:45 deps

 

Now let's run the sam deploy --guided command to deploy the app to AWS Cloud.

]$ sam deploy --guided

Configuring SAM deploy
======================

        Looking for config file [samconfig.toml] :  Found
        Reading default arguments  :  Success

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [sam-app]:
        AWS Region [us-east-1]:
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [Y/n]: n
        #SAM needs permission to be able to create roles to connect to the resources in your template
        Allow SAM CLI IAM role creation [Y/n]: Y
        #Preserves the state of previously provisioned resources when an operation fails
        Disable rollback [y/N]: y
        HelloWorldFunction has no authentication. Is this okay? [y/N]: y
        Save arguments to configuration file [Y/n]: Y
        SAM configuration file [samconfig.toml]:
        SAM configuration environment [default]:

 

If the deploy is successfully, the following should be at the end of the output.

Successfully created/updated stack - sam-app in us-east-1

 

And Outputs should contain something like this. Notice this has URL https://zulgntw90l.execute-api.us-east-1.amazonaws.com/Prod/hello/.

Key                 HelloWorldFunctionIamRole
Description         Implicit IAM Role created for Hello World function
Value               arn:aws:iam::123456789012:role/sam-app-HelloWorldFunctionRole-RiTFI3yH1db7

Key                 HelloWorldApi
Description         API Gateway endpoint URL for Prod stage for Hello World function
Value               https://zulgntw90l.execute-api.us-east-1.amazonaws.com/Prod/hello/

Key                 HelloWorldFunction
Description         Hello World Lambda Function ARN
Value               arn:aws:lambda:us-east-1:123456789012:function:sam-app-HelloWorldFunction-MgYCNMibayEZ

 

And you should see your app in the AWS API Gateway console.

 

The deploy will also create an S3 Bucket, which can be seen using the aws s3api list-buckets command.

{
    "Buckets": [
        {
            "Name": "aws-sam-cli-managed-default-samclisourcebucket-123456789",
            "CreationDate": "2023-11-16T02:50:50+00:00"
        }
    ]
}

 

Or in the AWS console.

 

The deploy will also create a Lambda Function which can be seen using the aws lambda list-functions command.

~]$ aws lambda list-functions
{
    "Functions": [
        {
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "$LATEST",
            "CodeSha256": "/ur2jHd199ldQbP+Y20sw3kIHhaWwnPY6CQvSwZ6Kco=",
            "FunctionName": "sam-app-HelloWorldFunction-MgYCNMibayEZ",
            "MemorySize": 128,
            "RevisionId": "741c094a-cff2-4cdb-a5b6-110a900e1a43",
            "CodeSize": 529507,
            "FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:sam-app-HelloWorldFunction-MgYCNMibayEZ",
            "Handler": "app.lambda_handler",
            "Role": "arn:aws:iam::123456789012:role/sam-app-HelloWorldFunctionRole-RiTFI3yH1db7",
            "Timeout": 3,
            "LastModified": "2023-11-16T02:52:04.978+0000",
            "Runtime": "python3.9",
            "Description": ""
        }
    ]
}

 

Or in the AWS console.

 

The deploy will also create an IAM (Identity and Access Management) role which can be seen using the aws iam list-roles command.

~]$ aws iam list-roles
[
    {
        "Path": "/",
        "RoleName": "sam-app-HelloWorldFunctionRole-RiTFI3yH1db7",
        "RoleId": "AROA2MITL76GAKGBEMHB3",
        "Arn": "arn:aws:iam::123456789012:role/sam-app-HelloWorldFunctionRole-RiTFI3yH1db7",
        "CreateDate": "2023-11-16T02:51:35+00:00",
        "AssumeRolePolicyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "lambda.amazonaws.com"
                    },
                    "Action": "sts:AssumeRole"
                }
            ]
        },
        "Description": "",
        "MaxSessionDuration": 3600
    }
]

 

Or in the AWS console.

 

Likewise, the sam list endpoints command should return both the /Prod and /Stage URLs.

]$ sam list endpoints --template /tmp/sam-app/template.yaml --output json
[
  {
    "LogicalResourceId": "HelloWorldFunction",
    "PhysicalResourceId": "sam-app-HelloWorldFunction-MgYCNMibayEZ",
    "CloudEndpoint": "-",
    "Methods": "-"
  },
  {
    "LogicalResourceId": "ServerlessRestApi",
    "PhysicalResourceId": "zulgntw90l",
    "CloudEndpoint": [
      "https://zulgntw90l.execute-api.us-east-1.amazonaws.com/Prod",
      "https://zulgntw90l.execute-api.us-east-1.amazonaws.com/Stage"
    ],
    "Methods": [
      "/hello['get']"
    ]
  }
]

 

curl can be used to submit a GET request to the /Prod and /Stage URLs and JSON "hello world" should be returned.

~]$ curl --request GET --url https://zulgntw90l.execute-api.us-east-1.amazonaws.com/Stage/hello
{"message": "hello world"}

~]$ curl --request GET --url https://zulgntw90l.execute-api.us-east-1.amazonaws.com/Prod/hello
{"message": "hello world"}

 

Or the sam remote invoke command can be used to invoke a Lambda function in your SAM app.  Since the output above has HelloWorldFunction and sam-app, the following command would be used.

Invoking Lambda Function HelloWorldFunction
START RequestId: e482f4e8-15c0-434f-86e7-7cc846b10fec Version: $LATEST
END RequestId: e482f4e8-15c0-434f-86e7-7cc846b10fec
REPORT RequestId: e482f4e8-15c0-434f-86e7-7cc846b10fec  Duration: 1.45 ms       Billed Duration: 2 ms   Memory Size: 128 MB     Max Memory Used: 36 MB  Init Duration: 109.89 ms
{"statusCode": 200, "body": "{\"message\": \"hello world\"}"}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter a5cb2b in the box below so that we can be sure you are a human.