It won't hurt to try

ServiceNow - Lambda 본문

카테고리 없음

ServiceNow - Lambda

yongki.doki 2024. 11. 7. 15:44

AWS Lambda를 사용하여 ServiceNow에 인시던트를 작성하는 API를 작성하려면 몇 가지 단계를 거쳐야 합니다. 기본적으로, Lambda에서 ServiceNow API와 통신하기 위해 node.js에서 HTTP 요청을 보내는 방법을 사용할 것입니다. 아래는 필요한 절차와 예시 코드입니다.

1. ServiceNow API 설정

먼저, ServiceNow에서 REST API를 사용할 수 있도록 설정을 해야 합니다. 이를 위해 ServiceNow의 Incident 테이블에 대한 API를 사용합니다. 이를 위한 기본 설정은 다음과 같습니다:

  • ServiceNow 인스턴스 URL: 예를 들어, https://your-instance.service-now.com
  • 인증 정보: ServiceNow의 사용자 이름과 비밀번호 혹은 OAuth 토큰을 사용하여 인증을 해야 합니다.
  • REST API 엔드포인트: incident 테이블에 대한 REST API 엔드포인트는 대개 https://your-instance.service-now.com/api/now/table/incident 입니다.

2. Lambda에서 ServiceNow에 인시던트 생성하기

Lambda 함수는 ServiceNow의 REST API 엔드포인트에 POST 요청을 보내어 인시던트를 생성합니다. 이를 위해 axios 또는 node-fetch와 같은 HTTP 클라이언트를 사용할 수 있습니다.

3. Lambda 함수 구현

const axios = require('axios');

exports.handler = async (event) => {
    const serviceNowUrl = 'https://your-instance.service-now.com/api/now/table/incident';
    const userName = 'your-username';
    const password = 'your-password';

    const incidentData = {
        short_description: 'Example Incident',
        description: 'This is a description of the incident.',
        priority: 2,  // 예시로, 우선순위를 2로 설정
        // 추가적인 필드를 여기에 추가할 수 있습니다.
    };

    try {
        // ServiceNow REST API에 POST 요청 보내기
        const response = await axios.post(serviceNowUrl, incidentData, {
            auth: {
                username: userName,
                password: password,
            },
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            },
        });

        // 성공적인 응답을 받았을 때의 처리
        console.log('Incident created successfully', response.data);
        return {
            statusCode: 200,
            body: JSON.stringify({ message: 'Incident created successfully', data: response.data }),
        };
    } catch (error) {
        // 오류 처리
        console.error('Error creating incident', error);
        return {
            statusCode: 500,
            body: JSON.stringify({ message: 'Failed to create incident', error: error.message }),
        };
    }
};

4. 의존성 설치 및 배포

AWS Lambda에서 axios 라이브러리를 사용하려면, 로컬에서 의존성을 설치하고 패키징한 후 Lambda에 배포해야 합니다.

4.1. 의존성 설치

로컬에서 Lambda에 필요한 의존성을 설치합니다.

mkdir lambda-function
cd lambda-function
npm init -y
npm install axios

4.2. Lambda 함수 배포

이제 Lambda 함수 코드와 node_modules를 포함하여 ZIP 파일로 패키징한 후, AWS Lambda 콘솔에서 업로드하거나 AWS CLI를 통해 배포할 수 있습니다.

zip -r function.zip .

배포 후, Lambda 함수는 서비스가 호출될 때마다 ServiceNow API에 인시던트를 생성할 수 있습니다.

5. Lambda 트리거 설정

Lambda가 호출될 때 인시던트를 생성하도록 트리거를 설정해야 합니다. 예를 들어, 다른 AWS 서비스 (S3, API Gateway 등)에서 이벤트를 트리거로 설정하거나, HTTP 요청을 받아 인시던트를 생성하도록 할 수 있습니다.

6. 인증 방법 변경 (옵션)

위 예시에서는 기본 사용자 인증 방법을 사용했습니다. 보다 안전한 인증 방법을 원한다면 ServiceNow에서 OAuth 2.0을 사용하는 방법도 고려할 수 있습니다.

OAuth 2.0을 사용하는 경우, axiosAuthorization 헤더를 수정하여 토큰을 전송할 수 있습니다.

headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': `Bearer ${yourAccessToken}`,
}

결론

위의 코드와 절차를 따르면 AWS Lambda를 통해 ServiceNow에서 인시던트를 생성하는 API를 작성할 수 있습니다. 실제 환경에서는 보안 및 예외 처리를 강화하고, 서비스 계정이나 API 키 등을 사용하여 인증 정보를 관리하는 것이 좋습니다.

300x250
300x250
Comments