반응형

1. slack에서 app을 생성한다.

 1) slack에 접속하여 메뉴 중 앱 > 앱 디렉터리를 클릭하면 된다.

https://api.slack.com/apps?new_app=1

 

 

2) 그럼 아래 창이 나오는데, 오른쪽 상단의 '구축'을 누르면 된다.

 

 

3) Create an app을 클릭한다.

 

 

4) From scratch 후 이름 및 workspace 생성

 

5) 기능추가: Incoming Webhooks 클릭.

 

6) Activate Incoming Webhooks을 On 설정한 후, 아래에 있는 Webhook URI에 워크스페이스 추가를 클릭한다.

 

 

7) 이 app이 동작될 채널을 선택한다.

 

8) 그럼 이렇게 webhook URL이 생겼고, 이건 이따가 index.js에서 사용한다.

 

9) jane_bot2가 #clone-prision에 초대되었다.

 

 

2. 자 다음, AWS로 이동한다.

1) Amazon SNS > 주제 > 주제생성

설정에서는 표준선택 및 이름 외 별도 설정할 게 없고, lambda에서 설정한다.

 

 

2) blueprint로 sns를 검색해서 lambda를 생성한다.

 

3) 아까 생성한 sns를 여기서 선택해준다. (jane-test-sns2) 

그리고 함수 생성.

 

4) 함수를 생성하면 이와 같이 출력되는데, 코드는 로컬에서 작성 후 zip파일으로 압축 해 업로드 해준다. 

코드 수정 전

 

 

5) 로컬에서 생성한 코드를 zip으로 압축해 업로드 했다.

slack-node를 설치해야하기 때문에 node_modules까지 가져와야 한다.

webhookUri는 아까 1 -> 8)에 있었던 Webhook URI를 그대로 복붙해주면 된다.

 

6) Test를 클릭하면 아까 설정한 워크스페이스 > 채널로 jane_bot2가 동작한다 :)

반응형
반응형

배경 설명

lambda에 S3를 연동시켜 두고, 해당 S3에 이벤트가 있을 때마다 람다를 실행시키는 코드를 해석해본다.

 

코드

const aws = require('aws-sdk');
const fs = require('fs');
var s3 = new aws.S3({ apiVersion: '2006-03-01' });


exports.handler = async(event, context,  callback) => {
    const bucket = event.Records[0].s3.bucket.name;

    console.log(event);   // 실행결과 테스트 1번
    console.log(event.Records);  // 실행결과 테스트 2번
    console.log(event.Records[0]);  // 실행결과 테스트 3번

    console.log(bucket); // 그럼 이건 .s3.bucket.name인 jane-bkt만 출력됨.
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); // 여기부턴 실행결과 2로 이동
    const params = {
        Bucket: bucket,
        Key: key,
    };
    var theObject = await s3.getObject(params).promise();
    const data = JSON.parse(theObject.Body);
    console.log(data);
    // console.log(theObject.Body.toString('utf8'));  // 위와 결과값이 같지만, 보기 좋은 형태로
        try {
        const { ContentType } = await s3.getObject(params).promise();
        console.log('CONTENT TYPE:', ContentType);
        console.log('********** Event generated by S3 ************* ');
        return ContentType;
        
    } catch (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
        console.log(message);
        throw new Error(message);
    }
};

 

 

실행 결과 1

1) console.log(event)

Function Logs
START RequestId: a4ff7ef5-b647-40b7-9e6d-8eb2fb95360f Version: $LATEST
2022-05-22T02:23:56.937Z a4ff7ef5-b647-40b7-9e6d-8eb2fb95360f INFO {
  Records: [
    {
      eventVersion: '2.0',
      eventSource: 'aws:s3',
      awsRegion: 'us-east-1',
      eventTime: '1970-01-01T00:00:00.000Z',
      eventName: 'ObjectCreated:Put',
      userIdentity: [Object],
      requestParameters: [Object],
      responseElements: [Object],
      s3: [Object]
    }
  ]
}

 2) console.log(event.Records);  // 실행결과 테스트 2번. 좀 더 자세히 나온다.

Function Logs
START RequestId: 35e8439b-4ac0-44fa-a006-85a3fdd6d4aa Version: $LATEST
2022-05-22T02:27:20.107Z 35e8439b-4ac0-44fa-a006-85a3fdd6d4aa INFO [
  {
    eventVersion: '2.0',
    eventSource: 'aws:s3',
    awsRegion: 'us-east-1',
    eventTime: '1970-01-01T00:00:00.000Z',
    eventName: 'ObjectCreated:Put',
    userIdentity: { principalId: 'EXAMPLE' },
    requestParameters: { sourceIPAddress: '127.0.0.1' },
    responseElements: {
      'x-amz-request-id': 'EXAMPLE123456789',
      'x-amz-id-2': 'EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH'
    },
    s3: {
      s3SchemaVersion: '1.0',
      configurationId: 'testConfigRule',
      bucket: [Object],
      object: [Object]
    }
  }
]


 3) console.log(event.Records[0]);  // 테스트 3번. 테스팅 json에서 언급한 jane-bkt, s3test.json을 포함한 결과값이 나온다.

Function Logs
START RequestId: cda13909-6eab-410a-9582-dc00d25732f2 Version: $LATEST
2022-05-22T02:28:47.364Z cda13909-6eab-410a-9582-dc00d25732f2 INFO {
  eventVersion: '2.0',
  eventSource: 'aws:s3',
  awsRegion: 'us-east-1',
  eventTime: '1970-01-01T00:00:00.000Z',
  eventName: 'ObjectCreated:Put',
  userIdentity: { principalId: 'EXAMPLE' },
  requestParameters: { sourceIPAddress: '127.0.0.1' },
  responseElements: {
    'x-amz-request-id': 'EXAMPLE123456789',
    'x-amz-id-2': 'EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH'
  },
  s3: {
    s3SchemaVersion: '1.0',
    configurationId: 'testConfigRule',
    bucket: {
      name: 'jane-bkt',
      ownerIdentity: [Object],
      arn: 'arn:aws:s3:::jane-bkt'
    },
    object: {
      key: 's3test.json',
      size: 1024,
      eTag: '0123456789abcdef0123456789abcdef',
      sequencer: '0A1B2C3D4E5F678901'
    }
  }
}

 

 

 

다시 코드

   const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); // 여기부턴 실행결과 2로 이동
   console.log(event.Records[0].s3.object.key.replace(/\+/g.''));  //  object.key에 +제거(/+) 및 전역으로 확장(/g) 

    const params = {
        Bucket: bucket,
        Key: key,
    };
    var theObject = await s3.getObject(params).promise();
    console.log(theObject);  // 결과 1)
    const data = JSON.parse(theObject.Body);
    console.log(data);
    // console.log(theObject.Body.toString('utf8'));  // 위와 결과값이 같지만 보기 좋은 형태로
        try {
        const { ContentType } = await s3.getObject(params).promise();
        console.log('CONTENT TYPE:', ContentType);
        console.log('********** Event generated by S3 ************* ');
        return ContentType;
        
    } catch (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
        console.log(message);
        throw new Error(message);
    }
};

 

실행결과 2

1)  console.log(theObject);  // 결과 1)

Function Logs
START RequestId: ed9a9525-9994-48da-8834-16ec0ab5c2d6 Version: $LATEST
2022-05-22T02:41:07.808Z ed9a9525-9994-48da-8834-16ec0ab5c2d6 INFO {
  AcceptRanges: 'bytes',
  LastModified: 2022-05-20T02:49:10.000Z,
  ContentLength: 80,
  ETag: '"5704c18c8279716da4b82c028dddb5d4"',
  ContentType: 'application/json',
  Metadata: {},
  Body: <Buffer 7b 0a 20 20 22 6e 61 6d 65 22 3a 20 22 4a 61 6e 65 22 2c 0a 20 20 22 61 67 65 22 3a 20 22 32 38 22 2c 0a 20 20 22 63 6f 6d 70 61 6e 79 22 3a 20 22 53 ... 30 more bytes> 
// 이 body를 아래 코드에서 JSON으로 파싱 후 출력함.
 const data = JSON.parse(theObject.Body);

}

 

Note

1) try - catch: 에러 핸들링 코드 (출처:https://ko.javascript.info/try-catch)

  1. try { } 안의 코드가 먼저 실행된다.
  2. 에러가 없다면, try 안의 마지막 줄까지 실행, catch 블록은 건너뜀
  3. 에러가 있다면, try 안 코드의 실행이 중단, catch(err) 블록으로 제어 흐름이 넘어감. 변수 err(아무 이름이나 사용 가능)는 무슨 일이 일어났는지에 대한 설명이 담긴 에러 객체를 포함. 
  try {
        const { ContentType } = await s3.getObject(params).promise();
        console.log('CONTENT TYPE:', ContentType);
        console.log('********** Event generated by S3 ************* ');
        return ContentType;
        
    } catch (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
        console.log(message);
        throw new Error(message);  // 에러 던지기.
    }
};

 

- event: 호출상황에 대한 정보.

- context: 실행되는 함수 환경에 대한 정보 

- callback: 응답을 전송하기 위한 함수. (Error 및 응답을 사용)

      -> 이벤트 루프가 비워질 때까지 기다린 다음, 응답이나 오류를 호출자에게 반환. 

- async: 비동기 핸들러를 sync 맞춰주기 위함. 

반응형
반응형

1. Trigger를 S3로 설정한 lambda를 만든다.

   (S3는 미리 만들어놔야 함)

   

1) Lambda > 함수생성 > 블루프린트 사용(aws에서 제공하는 템플릿) > s3 검색 > nodejs의 경우 s3-get-object

 

 2) 구성 누른 후 나머지 설정은 기존 사용하던 값으로 설정,

     S3 트리거에서 버킷을 만들어놓은 버킷으로 설정 + 이벤트 유형: 모든 객체 생성 이벤트

     // 이렇게 하면, 모든 객체 생성 이벤트(생성삭제수정 등)가 일어날 때마다 lambda 함수가 호출된다.

 

3) 만들어진 람다

 

2. index.js 코드

const aws = require('aws-sdk');
const fs = require('fs');
var s3 = new aws.S3({ apiVersion: '2006-03-01' });

exports.handler = async(event, context,  callback) => {
    const bucket = event.Records[0].s3.bucket.name;
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
        Bucket: bucket,
        Key: key,
    };

// json 파일을 읽어와서 json 형태로 출력
    var theObject = await s3.getObject(params).promise();
    const data = JSON.parse(theObject.Body);
    console.log(data);
   // console.log(theObject.Body.toString('utf8'));  // 보기 예쁜 형태로
        

 

 // S3에서 이벤트가 발생할 때마다 로그에 찍어줄 값.

  try {
        const { ContentType } = await s3.getObject(params).promise();
        console.log('CONTENT TYPE:', ContentType);
        console.log('********** Event generated by S3 ************* ');
        return ContentType;
        
    } catch (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
        console.log(message);
        throw new Error(message);
    }
};

 

3. 람다의 테스트에서 awsRegion, bucket-name, arn, key를 바꾸어주어야 정상 테스팅됨.

람다 테스트

      "awsRegion": “ap-northeast-2",

      "s3": {

        "s3SchemaVersion": "1.0",

        "configurationId": "testConfigRule",

        "bucket": {

          "name": "jane-bkt”,

          "ownerIdentity": {

            "principalId": "EXAMPLE"

          },

          "arn": "arn:aws:s3:::jane-bkt"

        },

        "object": {

          "key": "s3test.json",

          "size": 1024,

          "eTag": "0123456789abcdef0123456789abcdef",

          "sequencer": "0A1B2C3D4E5F678901"

        }

 

 

4. 테스팅 결과

1) json 파일이 예쁘게 나온다.

2) S3의 해당 버킷에 새로운 파일을 업로드할 경우, 람다가 실행되어 Cloudwatch에서 로그를 확인할 수도 있다.

 

반응형

+ Recent posts