Skip to main content
Soracom

Docs

Using Soracom Funk to Call AWS Lambda and Send a Slack Notification

Process device data using AWS Lambda and send a notification to Slack.

Last updated:

Introduction

Soracom Funk provides an easy way for a device to send data to a cloud function service for processing and receive the resulting output of the function, all without setting up custom servers or network environments. In this guide, we will set up a simple notification function with AWS Lambda, which will take data sent from our device using Funk, then call a Slack webhook to post the data as a channel notification, and return the result of the webhook call back to the device.

Prerequisites

This guide assumes that you are familiar with the basics of AWS, as well as how to send HTTP requests from your device. In addition, you will need the following:

  • An IoT SIM device which can send HTTP requests
  • An AWS account

Goal

Once we have completed this guide, our application should look something like this:

[Device] → [Soracom Funk] → [AWS Lambda] → [Slack Notification]

We will be using a simple HTTP POST request to send data from our device to the http://funk.soracom.io HTTP entry point. Funk will then call our AWS Lambda function, which will in turn take care of calling a Slack webhook, and return a response to our device based on the result of the Slack webhook.

Configure Slack

1. Create an Incoming WebHook

  1. Sign in to your Slack workspace using a web browser. Click your workspace menu and select Customize Slack.

  2. From the Customize Your Workspace screen, click the Configure apps section.

  3. From the Apps screen, click the Custom Integrations section, then click Incoming WebHooks.

  4. Click the Add Configuration button.

    Slack Incoming Webhook
  5. Select the Channel where notifications should be sent, then click the Add Incoming WebHooks integration button.

    Slack Incoming Webhook
  6. Make a note of the Webhook URL, as we will need this when setting up our Lambda function.

    Slack Incoming Webhook

Slack is now ready to receive data, which will be posted to our selected channel.

Configure AWS Lambda

Next, let's set up our AWS integration.

2. Create a Lambda Function

  1. Open the AWS Lambda dashboard. Make sure to switch to the AWS region you want to use for your application. Then click the Create function button.

    Lambda configuration
  2. Select the Author from scratch option, and give your AWS Lambda function a recognizable name, such as soracom-funk-to-slack. Here, we will use a Node.js application, so we will also set Runtime to a Node.js runtime (for example, the latest Node.js version available). Then click Create function.

  3. In the Code source section, open index.mjs and replace its contents with the following Node.js application. Then click Deploy.

    import https from "https";
    import url from "node:url";
    const slackUrl = process.env.SLACK_URL;
    
    export const handler = async function (event, context) {
      // AWS Lambda output
      console.log("event: %j", event);
      console.log("context: %j", context);
    
      // The message to post to Slack, using Slack's payload format
      const slackWebhookPayload = {
        text: "--- *Device called Lambda function with the following parameters* ---",
        attachments: [
          {
            title: "clientContext",
            color: "#34cdd7",
            text: "```\n" + JSON.stringify(context.clientContext, null, "  ") + "\n```",
            mrkdwn_in: ["text"],
          },
          {
            title: "event",
            color: "#e47911",
            text: "```\n" + JSON.stringify(event, null, "  ") + "\n```",
            mrkdwn_in: ["text"],
          },
        ],
      };
    
      const requestBody = JSON.stringify(slackWebhookPayload);
    
      const slackWebhookOptions = url.parse(slackUrl);
      slackWebhookOptions.method = "POST";
      slackWebhookOptions.headers = {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(requestBody),
      };
    
      try {
        const response = await new Promise((resolve, reject) => {
          const request = https.request(slackWebhookOptions, resolve);
          request.on("error", reject);
          request.write(requestBody);
          request.end();
        });
    
        if (response.statusCode === 200) {
          // AWS Lambda output
          console.log("Slack Incoming WebHook called successfully!");
    
          // Response returned to device
          return { result: "ok" };
        }
        // Response returned to device
        return { result: "ng", reason: "Slack Incoming WebHook returned status code " + response.statusCode };
      } catch (error) {
        console.error("Error calling Slack Incoming WebHook:", error);
        // Response returned to device
        return { result: "ng", reason: error.message };
      }
    };
  4. Our AWS Lambda function needs to know which Slack Incoming WebHook URL it should post to. Rather than embedding the URL in the function code, we will set it as an environment variable.

    Click the Configuration tab, then select Environment variables. Add an environment variable with the key SLACK_URL, set its value to the Slack Incoming WebHook URL generated earlier, and save it.

Before we finish our Lambda function, let's make a note of the Function ARN shown in the Function overview section.


3. Create an IAM Policy and an IAM Role

In order for Funk to be able to call the AWS Lambda function we just created, we need to create an AWS IAM role that Soracom's AWS account can assume, with permission to invoke the function.

  1. Open the AWS IAM dashboard.

  2. Click the Policies section, then click the Create policy button.

  3. In the policy editor, select JSON and copy and paste the following policy:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "lambda:InvokeFunction",
          "Resource": "arn:aws:lambda:us-east-1:900012345678:function:soracom-funk-to-slack"
        }
      ]
    }

    Make sure to change the Resource value to use the Function ARN of the Lambda function you created. This policy only allows the function you specify to be invoked. Then click Next.

  4. Enter a Policy name, such as soracom-funk-invoke-function, then click the Create policy button.

  5. Click the Roles section, then click the Create role button.

  6. Select AWS account > Another AWS account, and enter Soracom's AWS account ID in the Account ID field. Use the account ID that matches the coverage type of your IoT SIM:

    • Global Coverage: 950858143650
    • Japan Coverage: 762707677580
  7. Check the Require external ID option, and enter any string as the External ID, such as External-ID-N4gqVwJMp7ZTVEgY. Use a different string for each IAM role. Make a note of the external ID, as we will register it next.

    For more information on external IDs, see the AWS documentation: How to use an external ID when granting access to your AWS resources to a third party.

  8. Click Next. Search for the policy you just created, check it, then click Next.

  9. Enter a Role name, such as soracom-funk-invoke-function-role, then click the Create role button.

  10. Click the name of the IAM role you created, and make a note of its ARN.

Now we have an IAM role which Funk can use to access our AWS Lambda function.

Configure Soracom Funk

Now we can finish our integration by setting up Funk.

4. Register AWS IAM Role Credentials

  1. Sign in to the User Console. Click your account menu, then select Security.

    Register credentials
  2. Click the Credentials tab, then click Register credentials.

  3. Enter a Credential set ID for the credential set, such as aws-iam-soracom-funk. Then select AWS IAM Role credentials as the Type, and enter the IAM role ARN as the Role ARN and the external ID as the External ID.

    Click the Register button.


5. Enable Soracom Funk

Now all that's left is to enable Funk.

  1. From the Menu, open the Groups screen.

  2. From the list of groups, click the Name of the group you want to configure to open its settings page. If you don't have a group, simply create a new group, and remember to add your IoT SIM card to that group so that the Funk settings will be applied to the IoT SIM.

  3. Underneath the Basic Settings tab, click the SORACOM Funk panel to expand its settings.

  4. Enable Funk by switching the option to ON. Then configure Funk using the following parameters:

    Funk settings
    • Service - AWS Lambda
    • Content type - JSON
    • Credentials - The AWS IAM role credentials we registered earlier
    • Function ARN - The ARN of our AWS Lambda function

    Click the Save button.

All done!

Test the Connection

Now that everything is set up, let's test using a Raspberry Pi which has a 3G/LTE modem attached, with an IoT SIM card inserted.

curl -X POST \
  -H 'Content-Type: application/json' \
  -d '{"hello": "world"}' \
  http://funk.soracom.io

Once our Lambda function has processed the request, the response is sent back to our device:

{"result":"ok"}

And Slack will post the notification to our channel:

Slack notification

Wrap-Up

In this example, we created a relatively simple integration between our device and Slack in order to receive notifications when our device publishes messages.

Of course, as the Slack Incoming WebHook function takes standard HTTP requests, we could have simply programmed our device to call the Slack webhook directly.

However, by sending the data using Soracom Funk and creating an AWS Lambda function to call the Slack webhook, we have greatly simplified the logic required on our device: our device no longer needs to be concerned with the Slack webhook URL, and as the Slack-specific parameters are now controlled in the cloud within AWS Lambda's environment variables, we can easily update our Lambda function settings to switch to a different Slack webhook URL, quickly extend the functionality of our Lambda function, or even reconfigure Funk to call a different Lambda function, all without touching our device.

Search

Esc to close / Enter to view results