jobs:
send_yaml_to_aws:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
with:
fetch-depth: 0 # 모든 커밋 히스토리를 가져옴
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18' # 원하는 Node.js 버전으로 설정
- name: Install dependencies
run: npm install # node_modules 설치
- name: Set up AWS CLI
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: {aws-access-key-id}
aws-secret-access-key: {aws-secret-access-key}
aws-region: ap-northeast-2 # 한국 리전
- name: Find modified YAML files
id: find_yaml
run: |
# 변경된 YAML 파일 경로를 찾습니다
CHANGED_YAML_FILES=$(git diff --name-only HEAD~1 HEAD | grep -E '\\.yaml$')
# 결과를 출력합니다
echo "Changed YAML files: $CHANGED_YAML_FILES"
# YAML 파일 경로를 GitHub Action 환경 변수로 설정합니다
echo "::set-output name=files::$CHANGED_YAML_FILES"
- name: Send YAML to API Gateway
if: steps.find_yaml.outputs.files != ''
run: |
for YAML_FILE in ${{ steps.find_yaml.outputs.files }}; do
echo "Processing YAML file: ${YAML_FILE}"
# Node.js 스크립트 실행하여 API Gateway로 파일 전송
node sendYamlToApiGateway.js "${YAML_FILE}"
done
참고로 sendYamlToApiGateway.js 소스코드는 아래와 같다. 단순 API를 호출해주는 역할만 한다.
💡postman으로 curl을 만들고 요청을 해보았지만 아래 오류를 잡을 수 없어서 js파일을 만들어서 요청하기로 결정했다.
curl --location $API_URL \\\\
--header 'x-api-key: {key}' \\\\
--header 'Content-Type: multipart/form-data;' \\\\
--form "file=@${YAML_FILE}"
{ "errorType": "TypeError", "errorMessage": "The first argument must be of type string
or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received
undefined", "trace": [ "TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be
of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like
Object. Received undefined", " at new NodeError (node:internal/errors:405:5)",
" at Function.from (node:buffer:325:9)", " at Runtime.handler (file:///var/task/index.mjs:13:31)", "
at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1173:29)" ] }
const fs = require('fs');
const axios = require('axios');
const FormData = require('form-data');
// 인자로 전달받은 YAML 파일 경로
const yamlFilePath = process.argv[2];
// API Gateway URL 및 API Key 설정
const apiUrl = "URL";
const apiKey = "KEY";
// 파일이 존재하는지 확인
if (!fs.existsSync(yamlFilePath)) {
console.log(`File not found: ${yamlFilePath}`);
process.exit(1);
}
// form-data로 파일 준비
const form = new FormData();
form.append('file', fs.createReadStream(yamlFilePath));
// axios로 POST 요청 보내기
axios.post(apiUrl, form, {
headers: {
...form.getHeaders(),
'x-api-key': apiKey,
},
})
.then(response => {
console.log('Successfully uploaded YAML file:', response.data);
})
.catch(error => {
console.error('Error uploading YAML file:', error.message);
});
3. Api Gateway는 배포를 담당하는 Lambda를 호출
git에서 해야될 작업은 완료했다. 이제는 aws에서 작업을 해야된다.
API를 생성
stage를 생성
리소스 생성
API 키생성
사용량 계획 생성 및 API 키, stage연결
3-1. API를 생성
Api Gateway에서 REST API를 생성한다.
3-2. stage를 생성
API에 들어가서 stage탭으로 이동 후 stage를 생성해서 dev인지prod인지 등 API의 배포 환경을 설정해 줄 수있다.
3-3. 리소스 생성
api를 생성하고 나는 upload를 하기위한 리소스를 생성했다.
이 리소스는 form-data를 받아서 Lambda에 넘겨주는 역할을 할 것이다.
3-4. API 키생성
보안을 위해서 API키가 있어야지 요청을 할 수있게 할 것이다.
3-5. 사용량 계획 생성 및 API 키, stage연결
사용량 계획 탭으로 들어가서 먼저 사용량 계획을 생성해준다. 생성해준 후에 key와 stage를 열결 할 것이다.
생성한 사용량계획에 들어가서 stage와 key를 연결만 시켜주면 API Gateway에서 작업이 완료 되었다.
4. Lambda는 전달된 yaml을 S3에 업로드
Api Gateway를 생성했으니 리소스에 연결될 Lambda를 생성해 줄 차례이다.
Lambda 생성
Lambda 계층 생성 및 Lambda에 연결
소스코드 Deploy
Api Gateway 연결
4-1. Lambda 생성
Lambda서비스로 들어가서 함수를 생성해주는데 Node를 사용할 것이라서 런타임을 Node로 해주었다. 생성하고 들어가보면 vscode web으로 작업할 수 있는 환경이다.
4-2. Lambda 계층 생성 및 Lambda에 연결
💡node_module은 s3에 올린다음에 Lambda Layers에 선언을 했다. Lambda Layers에서는 공통으로 사용되는 라이브러리나 패키지를 별도로 관리할 수 있다.