😊

lambda × SNS クロスアカウント設定

2021/07/16に公開

SNSアクセスポリシー

Image from Gyazo

lambda IAMロール

Image from Gyazo

lambda作成

Image from Gyazo

lambdaコード

Image from Gyazo

var aws = require('aws-sdk');

var sns = new aws.SNS({
   apiVersion: '2010-03-31',
   region: 'ap-northeast-1'
});

function timer(ms, name) {
  console.log(`name: ${name} start!`)
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(name), ms)
  })
}

exports.handler = async function(event, context) {
    console.log('publish start')
    await timer(1000, publish(event, context));

    function publish(event, context) {
        sns.publish({
            Message: 'Message',
            Subject: 'Message title ' ,
            TargetArn: 'arn:aws:sns:region:accountId:別アカウント' // 別アカウントSNSのArn
            }, function(err, data) {
                if (err) {
                    console.log(err.stack);
                    return "failed publish".err.stack;
                }
                console.log('publish sent');
                console.log(data);
        });
    }
};

参考文献

Discussion