<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Igor Anic on Medium]]></title>
        <description><![CDATA[Stories by Igor Anic on Medium]]></description>
        <link>https://medium.com/@ianic?source=rss-175876a6211f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*e_mPO-yHycdC6dQm.jpg</url>
            <title>Stories by Igor Anic on Medium</title>
            <link>https://medium.com/@ianic?source=rss-175876a6211f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 17:35:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ianic/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[101 AWS Lambda tutorial for Go developers — API Gateway (Part 2)]]></title>
            <link>https://blog.mantil.com/101-aws-lambda-tutorial-for-go-developers-api-gateway-part-2-7008d2b64a4e?source=rss-175876a6211f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7008d2b64a4e</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Igor Anic]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 15:08:30 GMT</pubDate>
            <atom:updated>2022-03-17T07:21:47.094Z</atom:updated>
            <content:encoded><![CDATA[<h4>STEP-BY-STEP GUIDE</h4><h3>101 AWS Lambda tutorial for Go developers — API Gateway (Part 2)</h3><h4>Simple showcase with Terraform</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*yiejA9EWZ9NHmVJNjdVBAA.png" /><figcaption>Image Source: <a href="https://github.com/egonelbre/gophers">Egon Elbre</a></figcaption></figure><p>In the <a href="https://blog.mantil.com/dummy-guide-to-aws-lambda-for-go-developers-63192b684898">first part</a> of this guide, we saw how to create a simple Lambda function in Go. Here we will expand on that and make our function callable from the internet. We will integrate API Gateway with a Lambda function on the backend. When a client calls our function URL, API Gateway sends the request to the Lambda function and returns the function’s response to the client.</p><p>In order to run this example, you will need access to an AWS account. You are all set if you have already walked through the first part. If not, take a look into the AWS credentials chapter in <a href="https://blog.mantil.com/dummy-guide-to-aws-lambda-for-go-developers-63192b684898">part 1</a>.</p><h3>Running the example</h3><p>Let’s get something working. Then we will explore the accompanying Go code and terraform configuration available on <a href="https://github.com/mantil-io/go-lambda-examples/tree/master/pt2">GitHub</a>.</p><p>Step into the <em>handler</em> folder from the folder where this readme file is located. It contains a simple Go Lambda function prepared for HTTP API Gateway integration. The <em>build.sh</em> script will create a Lambda function deployment package. For a more detailed description of what it does check out the first part.</p><pre>cd handler<br>../../scripts/build.sh</pre><p>After this, we will have <em>function.zip</em> in the <em>handler</em> folder.</p><p>For Terraform, I suggest that you set a global <a href="https://www.terraform.io/cli/config/config-file#provider-plugin-cache">plugin-cache</a> folder. This will reuse plugins between projects, saving you time and disk space if you work with multiple different Terraform projects.</p><pre>echo &#39;plugin_cache_dir=&quot;$HOME/.terraform.d/plugin-cache&quot;&#39; &gt; $HOME/.terraformrc<br>mkdir -p $HOME/.terraform.d/plugin-cache</pre><p>Now move to the terraform folder, where we will spend the rest of the time. <em>terraform init</em> will prepare plugins and download them into the <em>plugin-cache</em>.</p><pre>cd ../terraform<br>terraform init</pre><p>Execute the Terraform configuration and create our infrastructure:</p><pre>terraform apply --auto-approve</pre><p>after ~20 seconds the expected output looks something like:</p><pre>Apply complete! Resources: 10 added, 0 changed, 0 destroyed.</pre><pre>Outputs:</pre><pre>endpoint = &quot;https://in2keb62qf.execute-api.eu-central-1.amazonaws.com&quot;<br>function_arn = &quot;arn:aws:lambda:eu-central-1:052548195718:function:api-example-handler&quot;<br>function_name = &quot;api-example-handler&quot;<br>url = &quot;https://in2keb62qf.execute-api.eu-central-1.amazonaws.com/handler&quot;</pre><p><em>endpoint</em> is the location of our API Gateway, <em>url</em> is the location on which you can reach our Lambda function. We can use the <em>terraform output</em> command to list some of these outputs whenever needed. For example, this will show the URL of the Lambda function:</p><pre>echo $(terraform output -raw url)</pre><p>we can use that URL to execute the function:</p><pre>curl $(terraform output -raw url)</pre><p>the expected output is something like:</p><pre>Hello from arn:aws:lambda:eu-central-1:052548195718:function:api-example-handler</pre><p>Now we can play with changing the Go code and sending input and building response of the function. To deploy your code changes, run the <em>build.sh</em> script again and then <em>terraform apply</em> to update the infrastructure.</p><p>When you want to remove all created resources, run:</p><pre>terraform destroy --auto-approve</pre><p>You can, of course, return to the apply step and create them again.</p><h3>Go handler code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLexqpQOyle7hcNQMEiV9A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@arifriyanto?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Arif Riyanto</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The handler code shows how to extract useful information from various available sources and return a response to the caller. The caller makes an HTTP request to the API Gateway endpoint. API Gateway packs that request and pushes a payload for the function invocation.</p><p>We are using the HTTP API Gateway <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html">proxy payload</a> format 2.0 integration type. When we make an HTTP request to our endpoint, for example:</p><pre>curl <a href="https://in2keb62qf.execute-api.eu-central-1.amazonaws.com/handler">https://in2keb62qf.execute-api.eu-central-1.amazonaws.com/handler</a> -d &quot;request body&quot;</pre><p>the payload which API Gateway passes to our function looks like this:</p><pre>{<br>    &quot;version&quot;: &quot;2.0&quot;,<br>    &quot;routeKey&quot;: &quot;ANY /handler&quot;,<br>    &quot;requestContext&quot;: {<br>        &quot;timeEpoch&quot;: 1644265482216,<br>        &quot;time&quot;: &quot;07/Feb/2022:20:24:42 +0000&quot;,<br>        &quot;stage&quot;: &quot;$default&quot;,<br>        &quot;routeKey&quot;: &quot;ANY /handler&quot;,<br>        &quot;requestId&quot;: &quot;NMDxogOhliAEJTg=&quot;,<br>        &quot;http&quot;: {<br>            &quot;userAgent&quot;: &quot;curl/7.77.0&quot;,<br>            &quot;sourceIp&quot;: &quot;93.140.84.169&quot;,<br>            &quot;protocol&quot;: &quot;HTTP/1.1&quot;,<br>            &quot;path&quot;: &quot;/handler&quot;,<br>            &quot;method&quot;: &quot;POST&quot;<br>        },<br>        &quot;domainPrefix&quot;: &quot;in2keb62qf&quot;,<br>        &quot;domainName&quot;: &quot;in2keb62qf.execute-api.eu-central-1.amazonaws.com&quot;,<br>        &quot;apiId&quot;: &quot;in2keb62qf&quot;,<br>        &quot;accountId&quot;: &quot;123456789012&quot;<br>    },<br>    &quot;rawQueryString&quot;: &quot;&quot;,<br>    &quot;rawPath&quot;: &quot;/handler&quot;,<br>    &quot;isBase64Encoded&quot;: true,<br>    &quot;headers&quot;: {<br>        &quot;x-forwarded-proto&quot;: &quot;https&quot;,<br>        &quot;x-forwarded-port&quot;: &quot;443&quot;,<br>        &quot;x-forwarded-for&quot;: &quot;93.140.84.169&quot;,<br>        &quot;x-amzn-trace-id&quot;: &quot;Root=1-6201800a-351c97731d1f143b5094ee4c&quot;,<br>        &quot;user-agent&quot;: &quot;curl/7.77.0&quot;,<br>        &quot;host&quot;: &quot;in2keb62qf.execute-api.eu-central-1.amazonaws.com&quot;,<br>        &quot;content-type&quot;: &quot;application/x-www-form-urlencoded&quot;,<br>        &quot;content-length&quot;: &quot;12&quot;,<br>        &quot;accept&quot;: &quot;*/*&quot;<br>    },<br>    &quot;body&quot;: &quot;cmVxdWVzdCBib2R5&quot;<br>}</pre><p>The <em>aws/aws-lambda-go</em> package provides Go structs for unpacking this payload. For the request, that is <a href="https://github.com/aws/aws-lambda-go/blob/main/events/apigw.go#L51-L64">APIGatewayV2HTTPRequest</a> and the response that API Gateway expects is defined in <a href="https://github.com/aws/aws-lambda-go/blob/main/events/apigw.go#L123-L130">APIGatewayV2HTTPResponse</a>. We are using these two types in the signature of our <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/handler/main.go#L27">handler</a> function, and the <em>lambda</em> package will handle the unmarshaling of the request and marshaling of the response.</p><p>The code in the handler shows how to get the request body. But first, we need to <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/handler/main.go#L64-L73">decode</a> it from base64.</p><p>Then we show how to get information from the Lambda <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/handler/main.go#L36">environment</a>. A full list of AWS Lambda environment variables can be found <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime">here</a>.</p><p>The context provided to the function has an execution <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/handler/main.go#L42">deadline</a>. The function should complete before this deadline.</p><p>The runtime request information can be found in the <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/handler/main.go#L47">lambdacontext</a>.</p><p>In the end, we show how to create a <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/handler/main.go#L53">response</a> for the API Gateway. The status code, body and headers will be returned to the caller who made the HTTP request to the API Gateway.</p><h3>Terraform configuration</h3><p>The terraform configuration consists of three files:</p><ul><li><em>main.tf</em> defines input and output variables</li><li><em>function.tf</em> defines the lambda function with the supporting resources</li><li><em>api.tf</em> defines the API Gateway</li></ul><h4>function.tf</h4><p>In <em>function.tf</em>, we first create an IAM role for our function and attach the <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/terraform/function.tf#L24">AWSLambdaBasicExecutionRole</a> policy, which gives the function permission to upload logs to CloudWatch. Other common Lambda roles can be found <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html">here</a>.</p><p>After that, we define the Cloudwatch <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/terraform/function.tf#L30-L33">log group</a> for the function. The function can create a log group on its own if it doesn’t exist. We create it upfront to make it part of the terraform-managed resources, which means it will be deleted by terraform on infrastructure destroy.</p><p>We use the deployment package we prepared in the <em>handler</em> folder for the building <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/terraform/function.tf#L36-L48">function</a>. The <a href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function#source_code_hash">source_code_hash</a> directive will trigger a function code update whenever file hash changes.</p><h4>api.tf</h4><p>Here we create an API Gateway. Then we define a mapping between the API Gateway and our function, a route on which function will be exposed. With all that in place, the function will be reachable on the internet.</p><p>We start with the definition of the <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/terraform/api.tf#L3-L9">API Gateway resource</a>.</p><p>There are three flavors of API Gateway. The first one was REST API; it still has the most features. HTTP API overlaps with REST in many segments. It is a more ‘modern’ implementation. AWS <a href="https://aws.amazon.com/about-aws/whats-new/2019/12/amazon-api-gateway-offers-faster-cheaper-simpler-apis-using-http-apis-preview/">claims</a> that “HTTP APIs are up to 71% cheaper compared to REST APIs”. It is also a little simpler than REST API. The last API Gateway flavor is WebSocket, enabling bidirectional client to backend communication. I’ll save that for some future example.</p><p>Here we are using HTTP API Gateway. The terraform resource type <em>aws_apigatewayv2_api</em> will create an HTTP API Gateway if the <em>protocol_type</em> argument is set to HTTP. The other option for <em>protocol_type</em> is WEBSOCKET for creating WebSocket API Gateways. The <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html">CORS</a> configuration enables browsers to access API while served from different domains.</p><p>The Gateway access logs will be stored in a <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/terraform/api.tf#L13-L16">CloudWatch log group</a>. <em>/aws/vendedlogs</em> is a required prefix for services that create a vast number of <a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AWS-logs-and-resource-policy.html">log groups</a>.</p><p>API Gateway can have multiple <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-stages.html">stages</a> with different configurations (for example, dev beta prod…). Here we will only use the <em>$default</em> stage. It is a reserved name for the stage which is served from the base of our API’s URL. API Gateway stages and stage deployments can be powerful concepts but you should reserve them for more complicated scenarios. Until then, stick to the <em>$default</em> stage and <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/terraform/api.tf#L23">automatic API Gateway deployment</a>.</p><p>In <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/terraform/api.tf#L24-L38"><em>access_log_settings</em></a> we are configuring where to send access logs and how they will look.</p><p>The <em>integration</em> resource, <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/terraform/api.tf#L43-L49"><em>aws_apigatewayv2_integration</em></a>, is the place where we connect our function with the API Gateway. <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/terraform/api.tf#L53-L57"><em>aws_apigatewayv2_route</em></a> sets the path in HTTP request where function will be exposed. The route key “ANY /${var.route}” when the route <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/terraform/main.tf#L16">variable</a> is set to “handler” exposes the function on the /handler path for all types of HTTP requests (GET, POST, …).</p><p>In the end, we need to allow our API Gateway to <a href="https://github.com/mantil-io/go-lambda-examples/blob/master/pt2/terraform/api.tf#L61-L66">invoke the function</a>. By default, in AWS, every resource is created without explicit permissions, so we need to set them for each resource to resource access.</p><h3>Conclusion</h3><p>Congratulations! Now you know how to add API Gateway to your AWS Lambda function in Go via Terraform. Thanks for following this tutorial.</p><h3>Thanks for reading!</h3><p>Have you got any questions regarding this tutorial or building serverless backends in Go? Feel free to reach us anytime at <a href="https://twitter.com/MantilDev">@MantilDev</a>.</p><blockquote><strong>👉 Build faster with Mantil. </strong>It is excellent to get profound knowledge of how something works, but there’s no fun in doing it manually repeatedly. Install an open-source development framework <a href="https://www.mantil.com/">Mantil</a> and API Gateways will be created automatically for all your Lambda projects.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7008d2b64a4e" width="1" height="1" alt=""><hr><p><a href="https://blog.mantil.com/101-aws-lambda-tutorial-for-go-developers-api-gateway-part-2-7008d2b64a4e">101 AWS Lambda tutorial for Go developers — API Gateway (Part 2)</a> was originally published in <a href="https://blog.mantil.com/">Mantil Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[101 AWS Lambda tutorial for Go developers]]></title>
            <link>https://blog.mantil.com/dummy-guide-to-aws-lambda-for-go-developers-63192b684898?source=rss-175876a6211f------2</link>
            <guid isPermaLink="false">https://medium.com/p/63192b684898</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Igor Anic]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 20:52:37 GMT</pubDate>
            <atom:updated>2022-03-17T07:22:26.503Z</atom:updated>
            <content:encoded><![CDATA[<h4>STEP-BY-STEP GUIDE</h4><h3>101 AWS Lambda tutorial for Go developers — Part 1</h3><h4>Simple showcase with AWS CLI and Terraform</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*NYKMS9fJ5Cu3JQb3KaFYcA.png" /><figcaption>Image Source: <a href="https://github.com/egonelbre/gophers">Egon Elbre</a></figcaption></figure><p>This multi-part blog series aims to give you a feeling of Lambda function programming in Go. It assumes that you don’t have previous knowledge of AWS or Lambda.</p><p>This is the first part where we will make the few small steps to start you in this new world. For the difference of many other examples, we will not use AWS Console or a higher-level serverless tool. We will create one dummy Lambda function and then execute it. We will do that in two ways: one using AWS command-line interface, and in the other, we will use Terraform to create AWS resources. It’s interesting to see two different approaches. One is imperative (AWS CLI), where we specify each step, and the other is declarative (Terraform), where we define the desired end state of the infrastructure.</p><h3>Toolset</h3><p>First thing you need to do is clone repo example: <a href="https://github.com/mantil-io/go-lambda-examples">https://github.com/mantil-io/go-lambda-examples</a>. This example is located in the <em>guide</em> folder.</p><p>For those who are on macOS and are using Homebrew getting started required tools is a one-liner:</p><pre>brew bundle</pre><p>in the root of this repo. For other OS-es, you will need to install <a href="https://go.dev/doc/install">Go</a>, <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI</a>, <a href="https://stedolan.github.io/jq/">jq</a> and <a href="https://learn.hashicorp.com/tutorials/terraform/install-cli">Terraform</a>.</p><h3>AWS Credentials</h3><p>You will need an <a href="https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/">AWS account</a> and <a href="https://aws.amazon.com/premiumsupport/knowledge-center/create-access-key/">access keys</a> for a user in that account.</p><p>After you have the access key, set it as <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html">environment variables</a> in the shell:</p><pre>export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE<br>export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY<br>export AWS_DEFAULT_REGION=us-east-1</pre><p>Change these demo values with your access key, secret key, and AWS region closest to you. We will use Graviton2 (ARM) powered Lambda functions, so you need to choose one of the regions where it is <a href="https://aws.amazon.com/blogs/aws/aws-lambda-functions-powered-by-aws-graviton2-processor-run-your-functions-on-arm-and-get-up-to-34-better-price-performance/">supported</a>:</p><blockquote><em>US East (N. Virginia), US East (Ohio), US West (Oregon), Europe (Frankfurt), Europe (Ireland), EU (London), Asia Pacific (Mumbai), Asia Pacific (Singapore), Asia Pacific (Sydney), Asia Pacific (Tokyo).</em></blockquote><p>To test connectivity to the AWS account with CLI run:</p><pre>aws sts get-caller-identity --output table --no-cli-pager</pre><p>This should return the Account, Arn and, UserId of the AWS user for which you set access credentials. If this command succeeds, you are ready to go.</p><h3>About Go code</h3><p>In the handler folder is a dummy Lambda function handler. That is an unmodified copy of the code from AWS <a href="https://docs.aws.amazon.com/lambda/latest/dg/golang-handler.html">docs</a>. Lambda package provides all the plumbing with Lambda execution runtime. It uses <a href="https://github.com/aws/aws-lambda-go/blob/2e104a66b60ac51aa6d7e494981203da7628426f/lambda/handler.go#L87">reflection</a> to analyze provided handler, performs JSON <a href="https://github.com/aws/aws-lambda-go/blob/2e104a66b60ac51aa6d7e494981203da7628426f/lambda/handler.go#L115">deserialization</a> of the payload and <a href="https://github.com/aws/aws-lambda-go/blob/2e104a66b60ac51aa6d7e494981203da7628426f/lambda/handler.go#L29">serialization</a> of the response.</p><p>Implemented handler (HandleRequest function in the example) must satisfy these <a href="https://github.com/aws/aws-lambda-go/blob/0462b0000e7468bdc8a9c456273c1551fab284aa/lambda/entry.go#L16">rules</a>.</p><h3>AWS CLI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*O5H_uWG53Ho784fLSWEq6Q.png" /><figcaption>Image source: <a href="https://medium.com/fullstack-with-react-native-aws-serverless-and/install-aws-cli-6dbd916159b4">Bharat Tiwari</a></figcaption></figure><h3>Create Lambda function</h3><p>Let’s first create a lambda function, and then we will look into the process. Position yourself into the <em>handler</em> folder and there run <em>publish.sh</em> from the scripts folder:</p><pre>cd handler<br>../../scripts/publish.sh</pre><p>The expected output is something like this:</p><pre>=&gt; build<br>=&gt; create deployment package<br>  adding: bootstrap (deflated 49%)<br>=&gt; create new role<br>{<br>    &quot;Role&quot;: {<br>        &quot;Path&quot;: &quot;/&quot;,<br>        &quot;RoleName&quot;: &quot;go-handler-example-role&quot;,<br>        &quot;RoleId&quot;: &quot;AROAQYPA52WDGY247IQCE&quot;,<br>        &quot;Arn&quot;: &quot;arn:aws:iam::052548195718:role/go-handler-example-role&quot;,<br>        &quot;CreateDate&quot;: &quot;2022-01-19T14:43:33+00:00&quot;,<br>        &quot;AssumeRolePolicyDocument&quot;: {<br>            &quot;Version&quot;: &quot;2012-10-17&quot;,<br>            &quot;Statement&quot;: [<br>                {<br>                    &quot;Effect&quot;: &quot;Allow&quot;,<br>                    &quot;Principal&quot;: {<br>                        &quot;Service&quot;: &quot;lambda.amazonaws.com&quot;<br>                    },<br>                    &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>                }<br>            ]<br>        }<br>    }<br>}<br>=&gt; create Lambda function<br>{<br>    &quot;FunctionName&quot;: &quot;go-handler-example&quot;,<br>    &quot;FunctionArn&quot;: &quot;arn:aws:lambda:eu-central-1:052548195718:function:go-handler-example&quot;,<br>    &quot;Runtime&quot;: &quot;provided.al2&quot;,<br>    &quot;Role&quot;: &quot;arn:aws:iam::052548195718:role/go-handler-example-role&quot;,<br>    &quot;Handler&quot;: &quot;provided&quot;,<br>    &quot;CodeSize&quot;: 4087476,<br>    &quot;Description&quot;: &quot;&quot;,<br>    &quot;Timeout&quot;: 3,<br>    &quot;MemorySize&quot;: 128,<br>    &quot;LastModified&quot;: &quot;2022-01-19T14:43:43.568+0000&quot;,<br>    &quot;CodeSha256&quot;: &quot;PRgB5sSH1C+B9YrsAquFvpyWgSfHvwBaOK33564ZZ6k=&quot;,<br>    &quot;Version&quot;: &quot;$LATEST&quot;,<br>    &quot;TracingConfig&quot;: {<br>        &quot;Mode&quot;: &quot;PassThrough&quot;<br>    },<br>    &quot;RevisionId&quot;: &quot;d7e38f6b-ff8a-4873-a259-b6350b149b3d&quot;,<br>    &quot;State&quot;: &quot;Pending&quot;,<br>    &quot;StateReason&quot;: &quot;The function is being created.&quot;,<br>    &quot;StateReasonCode&quot;: &quot;Creating&quot;,<br>    &quot;PackageType&quot;: &quot;Zip&quot;,<br>    &quot;Architectures&quot;: [<br>        &quot;arm64&quot;<br>    ]<br>}</pre><p>Let’s look inside the script and explain what is happening. This is <em>publish.sh</em> script:</p><pre>1 #!/usr/bin/env bash -e<br> 2 <br> 3 # read function name from first argument or use default<br> 4 function_name=&quot;${1:-go-handler-example}&quot;<br> 5 <br> 6 # get folder of the this script<br> 7 scripts=$(dirname &quot;$0&quot;)<br> 8 <br> 9 # run build script<br>10 $scripts/build.sh ${@:2}<br>11 <br>12 # check if the function already exists<br>13 if $(aws lambda get-function --function-name $function_name &gt; /dev/null 2&gt;&amp;1); then<br>14     echo &quot;=&gt; update existing function&quot;<br>15     aws lambda update-function-code \<br>16         --no-cli-pager \<br>17         --function-name &quot;$function_name&quot; \<br>18         --zip-file fileb://function.zip<br>19 else<br>20     # create new function<br>21     $scripts/create_function.sh $function_name<br>22 fi<br>23 <br>24 # delete artifacts<br>25 rm function.zip bootstrap</pre><p>I don’t assume any previous knowledge of shell scripting, so we will look into this script line by line. The script accepts the Lambda function name as the first parameter; if not supplied, <em>go-handler-example</em> will be used as default. Line 4 is where this happens; it uses the first argument or default for setting variable <em>function_name</em>. If you don’t want default function name run the script like ../../scripts/publish.sh my-lambda-function-name.</p><p>Line 7 gets the folder where <em>publish.sh</em> is located. We will call the other scripts (deploy.sh, create_function.sh) from this one so we grab that path and store it into <em>the scripts</em> variable.</p><p>In line 10, we call <em>build.sh</em>, which will prepare the Lambda function deployment package. First, let’s look into <em>build.sh</em>:</p><pre>1 #!/usr/bin/env bash -e<br>2 <br>3 echo &quot;=&gt; build&quot;<br>4 GOOS=linux GOARCH=arm64 go build -o bootstrap<br>5 <br>6 echo &quot;=&gt; create deployment package&quot;<br>7 zip function.zip bootstrap $@</pre><p>Line 4 is go build command. We are building for Linux arm64 platform. Lambda functions can be run on either Intel on AWS Graviton2 processors. Use Graviton to get <a href="https://aws.amazon.com/blogs/aws/aws-lambda-functions-powered-by-aws-graviton2-processor-run-your-functions-on-arm-and-get-up-to-34-better-price-performance/">a lower price and better performance</a> unless some requirements pull you back.</p><p>The resulting binary is named bootstrap. That is a requirement of the Lambda runtime provided.al2, which we will use for building the Lambda function. That runtime is a tiny Linux instance based on Amazon Linux 2; it will execute the bootstrap binary when started. Again, that bootstrap name is a requirement of the provided.al2 runtime.</p><p>Line 7 creates <em>a function.zip</em> file with a bootstrap file in it. That zip file is the Lambda deployment package accepted by CLI commands, AWS Console, or any other tool from which you can create the Lambda function. $@ at the end of the zip command is here to enable you to add any other files to the package. So you can, for example, with ../../scripts/build.sh config.yml add a config file to the package. That file will be available when running the Lambda function in the same folder as the binary.</p><p>After the build phase, we have <em>the function.zip</em> file in the <em>handler</em> folder. So let’s return to the published script.</p><p>Line 13 checks whether the Lambda function with the name from variable <em>function_name</em> already exists. aws lambda get-function — function-name $function_name returns function configuration, but here we are checking only the result. Whether it was successful or not. If it was successful, that function already exists, and we will just update the function code. If not, we will call another script <em>create_function.sh</em>. Let’s examine the process of creating a new Lambda function:</p><pre>1 #!/usr/bin/env bash -e<br> 2 <br> 3 function_name=&quot;${1:-go-handler-example}&quot;<br> 4 <br> 5 echo &quot;=&gt; create new role&quot;<br> 6 role_name=&quot;$function_name-role&quot;<br> 7 aws iam create-role \<br> 8     --role-name &quot;$role_name&quot; \<br> 9     --no-cli-pager \<br>10     --assume-role-policy-document &#39;{&quot;Version&quot;: &quot;2012-10-17&quot;,&quot;Statement&quot;: [{ &quot;Effect&quot;: &quot;Allow&quot;, &quot;Principal&quot;: {&quot;Service&quot;: &quot;lambda.amazonaws.com&quot;}, &quot;Action&quot;: &quot;sts:AssumeRole&quot;}]}&#39;<br>11 <br>12 # read role arn<br>13 role_arn=$(aws iam get-role --role-name &quot;$role_name&quot; | jq .Role.Arn -r)<br>14 aws iam attach-role-policy \<br>15     --no-cli-pager \<br>16     --role-name &quot;$role_name&quot; \<br>17     --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole<br>18 <br>19 aws iam wait role-exists --role-name &quot;$role_name&quot;<br>20 <br>21 echo &quot;=&gt; create Lambda function&quot;<br>22 # run with retries of few seconds to give time role to become visible<br>23 for i in 5 1 1 1 1 1; do<br>24     sleep &quot;$i&quot; # waiting for role to be available<br>25     aws lambda create-function \<br>26         --function-name &quot;$function_name&quot; \<br>27         --runtime provided.al2 \<br>28         --zip-file fileb://function.zip \<br>29         --role &quot;$role_arn&quot; \<br>30         --handler provided \<br>31         --architectures &quot;arm64&quot; \<br>32         --no-cli-pager &amp;&amp; break<br>33 done</pre><p>From line 5 to line 19 is the process of creating <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html">the Lambda execution role</a>. We need that role in line 29 for actually creating the Lambda function. I will skip details of the IAM, policy, role story… It is necessary to give your function permission on other AWS resources, but that is a separate topic. Just note that in line 17, we give our Lambda function AWSLambdaBasicExecutionRole, which provides that function with permission to upload logs to Cloudwatch and nothing more.</p><p>Loop in lines 23, 24, and &amp;&amp; break part at the end of the create-function command (line 25) gives us a few retries for <em>create-function</em> command. When we create a new role, it is not immediately visible by new Lambda functions, so <em>create-function</em> command can fail with an error: An error occurred (InvalidParameterValueException) when calling the CreateFunction operation: The role defined for the function cannot be assumed by Lambda. The script waits 5 seconds before the first try and then makes a few more tries each after 1 second.</p><p>Line 25 is the actual <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/create-function.html">create-function</a> AWS CLI command. We provide the function name (line 26) runtime on which the Lambda function will be built (line 27). This is a Go application, so we use provided.al2 runtime. There are <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html">runtimes</a> for other languages. In line 28, we give our <em>function.zip</em> as content for the new Lambda. Another useful option is to instead of using local file to specify S3 location where the package is located. In line 31, we define the architecture for the function (arm64 or x86_64).</p><h3>Invoke Lambda function</h3><p>Run the <em>invoke.sh</em> script from the <em>scripts</em> folder:</p><pre>../../scripts/invoke.sh</pre><p>The expected output is:</p><pre>{<br>    &quot;StatusCode&quot;: 200,<br>    &quot;ExecutedVersion&quot;: &quot;$LATEST&quot;<br>}<br>&quot;Hello Foo!&quot;</pre><p>And the <em>invoke.sh</em> is:</p><pre>1 #!/usr/bin/env bash -e<br> 2 <br> 3 function_name=&quot;${1:-go-handler-example}&quot;<br> 4 <br> 5 aws lambda invoke \<br> 6   --function-name &quot;$function_name&quot; \<br> 7   --no-cli-pager \<br> 8   --cli-binary-format raw-in-base64-out \<br> 9   --payload &#39;{&quot;name&quot;:&quot;Foo&quot;}&#39; \<br>10   response.json &amp;&amp; cat response.json<br>11 <br>12 rm response.json</pre><p>Script uses <a href="https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/invoke.html">lambda invoke</a> CLI command. Line 6 specifies a function and line 9 JSON payload. In this case we are sending {&quot;name&quot;:&quot;Foo&quot;}JSON. This command writes a response to the file. So we provide a file, show response content cat response.json and remove that file at the end of the script.</p><p>You can play by changing the payload attribute to get different results.</p><h3>View Lambda function logs</h3><p>Run:</p><pre>../../scripts/logs.sh</pre><p>The expected output is something like:</p><pre>last stream name: 2022/01/20/[$LATEST]7b576140275c4b4d9aee7288717766c3<br>1642696161536   START RequestId: 65da5fff-aea9-4d67-8366-499d3942adf7 Version: $LATEST\n<br>1642696161537   END RequestId: 65da5fff-aea9-4d67-8366-499d3942adf7\n<br>1642696161537   REPORT RequestId: 65da5fff-aea9-4d67-8366-499d3942adf7\tDuration: 1.14 ms\tBilled Duration: 46 ms\tMemory Size: 128 MB\tMax Memory Used: 17 MB\tInit Duration: 44.06 ms\t\n</pre><p><em>logs.sh</em> script:</p><pre>1 #!/usr/bin/env bash -e<br> 2 <br> 3 function_name=&quot;${1:-go-handler-example}&quot;<br> 4 <br> 5 # get the name of the last log stream<br> 6 stream_name=$(aws logs describe-log-streams --log-group-name /aws/lambda/$function_name | jq &quot;.logStreams[].logStreamName&quot; -r | tail -n 1)<br> 7 <br> 8 echo &quot;last stream name: $stream_name&quot;<br> 9 # show logs as table<br>10 aws logs get-log-events \<br>11     --log-group-name /aws/lambda/$function_name \<br>12     --log-stream-name &quot;$stream_name&quot; \<br>13     | jq &quot;.events[] | [.timestamp, .message] | @tsv&quot; -r</pre><p>Here we are showing lambda function logs from the AWS Cloudwatch service. By default, the Lambda function sends logs to the Cloudwatch service. Cloudwatch is organized into log groups and log streams. Each lambda function gets a log group named/aws/lambda/[function-name]. Into that group, each Lambda initialization creates a new log stream. Function initialization happens on first invoke after that execution environment lives for some time.</p><p>This script finds the last stream name for our function log group and then lists logs in that stream. Line 6 executes <em>describe-log-streams</em> which list all log streams in the log group in JSON array. We use jq tool here to select only <em>logStreamName</em> attribute, tail -n 1 returns last line from the list of all streams. Now when we have <em>stream_name</em>, we can call get-log-events for that stream in line 10. Again we use jq to reformat JSON into the table.</p><p>These logs show only Lambda execution environment stats. Put some log.Printf(...) lines into the handler Go code, and you will find them in the logs. Any output from the handler binary will be available in Cloudwatch logs.</p><h3>Cleanup</h3><p>To remove Lambda function and other created resources (role and logs) in the AWS account, run the cleanup script:</p><pre>../../scripts/cleanup.sh</pre><h3>Terraform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrXy7ya8mOAqyQhSPjLsCw.png" /><figcaption>Image source: <a href="https://www.terraform.io/">Terraform</a></figcaption></figure><h3>Create infrastructure</h3><p>Again position yourself into the <em>handler</em> folder. Use <em>build.sh</em> to create Lambda deployment package <em>function.zip</em> there:</p><pre>../../scripts/build.sh</pre><p>Then switch to the <em>terraform</em> folder:</p><pre>cd ..<br>cd terraform</pre><p>Be sure to have set AWS_DEFAULT_REGION environment variable before running terraform. For example:</p><pre>export AWS_REGION=eu-central-1</pre><p>Then execute terrafrom init and apply commands:</p><pre>terraform init<br>terraform apply --auto-approve</pre><h3>Execute function</h3><pre>../../scripts/invoke.sh $(terraform output --raw function_name)</pre><p>Here, the $(terraform output --raw function_name)part is to read <em>function_name</em> from the terraform state.</p><h3>Explore terraform configuration</h3><p>This guide is not intended to be a terraform manual. We will just explore terraform configuration to get a sense of this declarative approach to building infrastructure.</p><pre>1 terraform {<br> 2   backend &quot;local&quot; {<br> 3     path = &quot;./.state/terraform.tfstate&quot;<br> 4   }<br> 5 }<br> 6 <br> 7 variable &quot;function_name&quot; {<br> 8   type    = string<br> 9   default = &quot;go-tf-handler-example&quot;<br>10 }<br>11 <br>12 provider &quot;aws&quot; {}<br>13 <br>14 resource &quot;aws_iam_role&quot; &quot;fn&quot; {<br>15   name = &quot;${var.function_name}-role&quot;<br>16 <br>17   assume_role_policy = jsonencode({<br>18     Version = &quot;2012-10-17&quot;<br>19     Statement = [<br>20       {<br>21         Effect = &quot;Allow&quot;<br>22         Action = &quot;sts:AssumeRole&quot;<br>23         Principal = {<br>24           Service = &quot;lambda.amazonaws.com&quot;<br>25         }<br>26       }<br>27     ]<br>28   })<br>29 }<br>30 <br>31 resource &quot;aws_lambda_function&quot; &quot;fn&quot; {<br>32   role          = aws_iam_role.fn.arn<br>33   function_name = var.function_name<br>34   filename      = &quot;../handler/function.zip&quot;<br>35   runtime       = &quot;provided.al2&quot;<br>36   handler       = &quot;bootstrap&quot;<br>37   architectures = [&quot;arm64&quot;]<br>38 }<br>39 <br>40 output &quot;function_name&quot; {<br>41   value = var.function_name<br>42 }<br>43 <br>44 output &quot;function_arn&quot; {<br>45   value = aws_lambda_function.fn.arn<br>46 }</pre><p>The first five lines define where terraform will save its state. The simplest method is to use a local filesystem. State will be saved into the <em>.state</em>folder into <em>terraform</em> folder (where main.tf is located).<br>In 7–10 we define function name as variable. You can <a href="https://www.terraform.io/language/values/variables#variables-on-the-command-line">change that</a> in apply for example: terraform apply --var=&quot;function_name=my-function-name&quot; --auto-approve.<br>Lines 14-29 will create IAM role for the Lambda function. It is referenced in line 32 when creating the Lambda function. With this reference terraform knows that it first needs to create role resource because lambda function resource depends on the role.<br>Lines 31-38 are actual function creation. Again we provide the same information as in CLI; function_name, a zip file with Lambda deployment package (filename), runtime on which function is based (runtime) and architecture. Handler is fixed to the <em>bootstrap</em> for provided.al2 runtime.<br>Lines 40-46 define output variables. We can view them with terraform output command.</p><h3>Cleanup</h3><p>To remove all resources created in apply run:</p><pre>terraform destroy --auto-approve</pre><h3>Conclusion</h3><p>Congratulations! Now you know how to build the AWS Lambda function in Go, both via AWS CLI and Terraform. Thanks for following this tutorial.</p><p>In the <a href="https://blog.mantil.com/101-aws-lambda-tutorial-for-go-developers-api-gateway-part-2-7008d2b64a4e">next part of this serverless series</a>, I break down how to set up an API Gateway and enable public access to created Lambda function.</p><h3>Thanks for reading!</h3><p>Have you got any questions regarding this tutorial or building serverless backends in Go? Feel free to reach us anytime at <a href="https://twitter.com/MantilDev">@MantilDev</a>.</p><blockquote><strong>👉 Build faster with Mantil. </strong>If you find the steps described in this tutorial interesting but don’t want to repeat them every time manually, install open-source development kit <a href="https://www.mantil.com/">Mantil </a>and start building your AWS Lambda-based Go backends quicker than ever.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63192b684898" width="1" height="1" alt=""><hr><p><a href="https://blog.mantil.com/dummy-guide-to-aws-lambda-for-go-developers-63192b684898">101 AWS Lambda tutorial for Go developers</a> was originally published in <a href="https://blog.mantil.com/">Mantil Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local development is not the right choice for the cloud-based serverless world]]></title>
            <link>https://blog.mantil.com/local-development-is-not-the-right-choice-for-the-cloud-serverless-world-29fe5bd27d52?source=rss-175876a6211f------2</link>
            <guid isPermaLink="false">https://medium.com/p/29fe5bd27d52</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Igor Anic]]></dc:creator>
            <pubDate>Wed, 12 Jan 2022 13:53:27 GMT</pubDate>
            <atom:updated>2022-03-17T07:24:18.668Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqyn-qdTP_05FLCVnXihaw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@altumcode?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">AltumCode</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Since the introduction of serverless computing, developers were complaining about the frustrating build experience and broken development workflow so much that they were asking if the benefits of serverless are worth it. Part of the problem lies in the fact they are trying to keep the same workflow they are used to, including the local development environment. However, I believe that working with serverless requires a change in mindset.</p><h3>You don’t need a local development environment</h3><p>At Mantil, we chose to both develop and run production using cloud services. Instead of trying to make a copy of the cloud services for local development, we are making an effort to get the feeling of local development while using real services in the cloud.</p><p>In my experience, having a local development setup while using cloud services for production leads to supporting two environments. It is easy for trivial cases. But as the number of services or complexity of their interactions rises, like they always do in the real world, supporting two different environments becomes more and more painful.</p><p>Questions that I ask myself about team development environments:</p><ul><li>What is the maintenance cost? How much of their time do developers spend building environments instead of working on business features?</li><li>How complex is it? How many developers from the team are actually capable of extending the development environment? What happens when the initial developer leaves?</li><li>How much time is needed to bootstrap a new developer? What if that developer is part-time? What if someone else needs to jump into the project (a product manager who will edit texts or a designer who jumps into the project to make it usable)?</li></ul><h3>Cloud environments are the way to go</h3><p>Developers like to have their own sandbox. With Mantil they have that private sandbox but instead of running locally, it is using cloud resources. In this serverless world, that means that development and production are essentially the same environments. It is not that one is using less capable servers, a simplified network, or anything like that. All environments are the same!</p><p>In Mantil we have a concept of stages which are deployments of a project into a cloud environment. By supporting an infinite number of stages for each project, other than having a private enviroment for each developer, development can be organized into as many stages as needed: integration, staging, showcase and so on. We make creating and deploying to the new stage a trivial step.</p><p>With Mantil you get the speed of the local development with the power of the cloud spiced with additional benefits:</p><ul><li>No need to maintain two different environments</li><li>Development, production and all the stages in between using exactly the same resources</li><li>Mantil handles everything, no need to set up anything locally.</li></ul><h3>Thanks for reading!</h3><p>Have you got any questions, or are you building serverless backends in Go? Feel free to reach us anytime at <a href="https://twitter.com/MantilDev">@MantilDev</a>.</p><blockquote><strong>👉 Build faster with Mantil. </strong>If you want to use cloud environments but still preserve excellent development experience, install the open-source development kit <a href="https://www.mantil.com/">Mantil</a> and start building your AWS Lambda-based Go backends quicker than ever.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29fe5bd27d52" width="1" height="1" alt=""><hr><p><a href="https://blog.mantil.com/local-development-is-not-the-right-choice-for-the-cloud-serverless-world-29fe5bd27d52">Local development is not the right choice for the cloud-based serverless world</a> was originally published in <a href="https://blog.mantil.com/">Mantil Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>