kyangy
kyangy

Reputation: 65

AWS SNS publish only works locally, but not from lambda

This is the code that runs successfully on local to send sms

const snsParams = {
  Message: "Hello World",
  PhoneNumber: normalizedPhoneNumber,
};

const sms = messager.publish(snsParams).promise();

sms.then(data => {
  console.log('Success!', data);
}).catch(err => {
  console.log('Error!', err);
});

However, this does not fire from my deployed lambda.

My serverless.yml contains the necessary iamRoleStatements like this

iamRoleStatements:
- Effect: Allow
  Action:
    - dynamodb:DescribeTable
    - dynamodb:Query
    - dynamodb:Scan
    - dynamodb:BatchGetItem
    - dynamodb:BatchWriteItem
    - dynamodb:GetItem
    - dynamodb:PutItem
    - dynamodb:UpdateItem
    - dynamodb:DeleteItem
  Resource:
    - arn:aws:dynamodb:us-west-1:*:table/${app-name}-${self:custom.stage}
    - arn:aws:dynamodb:us-west-1:*:table/${app-name}-${self:custom.stage}/*
- Effect: Allow
  Action:
    - sns:*
  Resource: "*"

I've also checked from the IAM Management console to see that SNS is included in my lambda role

enter image description here

How can I make this work? What am I missing?

Upvotes: 1

Views: 478

Answers (1)

ttulka
ttulka

Reputation: 10882

I think the problem could be in promises, because the line messager.publish(snsParams).promise(); creates only a promise and there is no waiting when the promise is executed.

You can change your code so:

exports.handler = async function(event) {
  ...
  const snsParams = {
    Message: "Hello World",
    PhoneNumber: normalizedPhoneNumber,
  };
  try {
    const sms = await messager.publish(snsParams).promise();
    console.log('Success!', sms);
  } catch (err) {
    console.log('Error!', err);
  }
}

Upvotes: 1

Related Questions