티스토리 뷰

AWS Lambda : zip 명령어 미지원 

AWS Lambda에서는 파일 압축을 하는 zip 명령어(unzip package)에 대한 지원을 하지 않습니다.

그렇다보니 Zip 명령어를 쓰고싶을 경우 Rails에서 zip을 지원하는 Gem을 활용해야 합니다.

 

1.  Gemfile  에 다음 두 줄의 코드를 입력합니다.

gem 'rubyzip', '>= 1.0.0'
gem 'zip-zip'

그리고 Gem 설치를 진행합니다.

bundle install

 

2. 간단하게 저는 AWS Cloud9 환경에서 사전에 Jets 환경이 준비된 상태에서 파일압축을 진행해보겠습니다.

우선 Job 파일을 생성해주세요.

## jets g job [Job 이름]

jets g job compression_test

 

3. 생성된 Job 파일을 열람 후, 모듈(Gem)을 정의하는 require을 아래와 같이 입력해주세요.

## app/jobs/compression_test_job.rb

class CompressionTestJob < ApplicationJob
  require "rubygems"
  require "zip"
  
  def job_test
  end
end

 참고  저는 부가적으로 기존의 cron 규칙 제거 및 method 이름을 변경(dig→job_test) 했습니다.

이 작업은 선택적입니다.

 

4. 간단하게  /tmp  폴더속에 파일 압축을 위한 더미파일 및 생성된 파일에 Text가 작성되게 해보겠습니다.

job_test 메소드 안에 아래와같이 더미파일&Text Write를 하는 코드를 추가해주세요.

## app/jobs/compression_test_job.rb

class CompressionTestJob < ApplicationJob
  require "rubygems"
  require "zip"
  
  def job_test
    system "cd /tmp; touch hello; touch world;"
    system "echo 'nice to see U ! :D' >> /tmp/hello"
    system "echo 'We are the one.' >> /tmp/world"
  end
end

 참고  AWS Lambda에서는  /tmp  폴더를 통해서만이 파일 Write가 가능합니다.

 부록  Ruby on Jets : 임시파일 저장/보관

 

레일즈 콘솔을 통해 3줄의 system 속 내용이 실행되면 아래와 같은 파일생성 및 파일 속에 Text가 쓰여지는 결과가 나옵니다.

 

5. 이제  /tmp  폴더에 생성된 hello, world 파일을 압축하는 코드를 짜보겠습니다.

아래와 같이 입력해주세요.

## app/jobs/compression_test_job.rb


def job_test
  system "cd /tmp; touch hello; touch world;"
  system "echo 'nice to see U ! :D' >> /tmp/hello"
  system "echo 'We are the one.' >> /tmp/world"

  zipFileName = "fileCompression-#{Time.now.in_time_zone("Asia/Seoul").strftime('%Y-%m-%d_%H%M%S')}.zip" # 생성될 zip 파일에 대한 이름
  zipFileNameWithPath = "/tmp/#{zipFileName}" # zip 파일이 저장될 경로

  compressionList = ["hello", "world"] # (Array) 압축될 파일 이름들
  toCompressionFolderPath = "/tmp" # 압축될 파일들이 존재하는 Path

  Zip::File.open(zipFileNameWithPath, Zip::File::CREATE) do |zipfile|
    compressionList.each do |filename|
      # Two arguments:
      # - The name of the file as it will appear in the archive
      # - The original file, including the path to find it
      zipfile.add(filename, File.join(toCompressionFolderPath, filename))
    end
    zipfile.get_output_stream("README.md") { |f| f.write "File Compression End! : #{Time.now.in_time_zone("Asia/Seoul").strftime('%Y-%m-%d_%H%M%S')} (UTC+9)" } # 작업 완료 후 추가적인 파일생성 및 메세지 내용
  end
end

 

6. 위 상태까지 입력해낸 후, Jets로 배포 전, Jets Console에서 한번 Job을 실행해보겠습니다.

CompressionTestJob.perform_now(:job_test)

1) 실행에 성공할 경우,  /tmp  폴더에서 zip 파일이 생성된게 확인됩니다.

 

2) Cloud9에서 제 PC로 파일을 다운로드 후, 압축파일 내부를 보면 아래와같이 hello, world 파일들이 잘 넘어왔습니다.

그리고 5번과정에 의해 추가적으로 생성되는 README.md 파일도 추가적으로 생겨났습니다.

 

3) 압축 해제 후 hello, world 파일을 열람 시 4번과정 때 system 명령어를 통해 입력됐던 Text가 잘 보입니다.

이를 통해 파일에 손상이 없다는 것을 확인할 수 있습니다.

 

7. AWS Lambda에 배포 후 파일이 잘 압축되는지 확인을 하기 위해, 파일 목록을 확인하는 Debug 코드를 한 줄 추가합니다. (job_test 메소드 내 맨 아랫줄의 내용만 추가하면 됩니다.)

## app/jobs/compression_test_job.rb

def job_test
  ... (코드 생략) ...

  Zip::File.open(zipFileNameWithPath, Zip::File::CREATE) do |zipfile|
    compressionList.each do |filename|
      # Two arguments:
      # - The name of the file as it will appear in the archive
      # - The original file, including the path to find it
      zipfile.add(filename, File.join(toCompressionFolderPath, filename))
    end
    zipfile.get_output_stream("README.md") { |f| f.write "File Compression End! : #{Time.now.in_time_zone("Asia/Seoul").strftime('%Y-%m-%d_%H%M%S')} (UTC+9)" } # 작업 완료 후 추가적인 파일생성 및 메세지 내용
  end

  p system "cd /tmp; ls"
end

 

8. Jets 프로젝트를 아래 터미널 명령어를 통해 AWS Lambda에 배포합니다.

## jets deploy [Environment]

jets deploy production

 

9. 배포 완료 후, AWS Console 페이지로 이동합니다.

 

10. AWS Lambda 서비스 페이지에서 compression_test_job#job_test 함수를 찾아냅니다.

 

11. compression_test_job#job_test 함수를 실행 후, 결과를 확인합니다!

함수 실행 성공 및,  /tmp  폴더에 zip 파일이 잘 담겨진게 확인됩니다.

 

12. 이후에는  /tmp  디렉터리에 있는 zip 파일을 SSH 서버로 전송, AWS S3 서버로 전송 등으로 여러분들의 목적에 맞게 활용하시면 됩니다.

 

13. 마지막으로, 임시파일에 있는 압축파일을 삭제하는 코드로 마무리 합니다.

## app/jobs/compression_test_job.rb

class CompressionTestJob < ApplicationJob
  require "rubygems"
  require "zip"

  def job_test
  	begin
      system "cd /tmp; touch hello; touch world;"
      system "echo 'nice to see U ! :D' >> /tmp/hello"
      system "echo 'We are the one.' >> /tmp/world"

      zipFileName = "fileCompression-#{Time.now.in_time_zone("Asia/Seoul").strftime('%Y-%m-%d_%H%M%S')}.zip" # 생성될 zip 파일에 대한 이름
      zipFileNameWithPath = "/tmp/#{zipFileName}" # zip 파일이 저장될 경로

      compressionList = ["hello", "world"] # (Array) 압축될 파일 이름들
      toCompressionFolderPath = "/tmp" # 압축될 파일들이 존재하는 Path

      Zip::File.open(zipFileNameWithPath, Zip::File::CREATE) do |zipfile|
        compressionList.each do |filename|
          # Two arguments:
          # - The name of the file as it will appear in the archive
          # - The original file, including the path to find it
          zipfile.add(filename, File.join(toCompressionFolderPath, filename))
        end
        zipfile.get_output_stream("README.md") { |f| f.write "File Compression End! : #{Time.now.in_time_zone("Asia/Seoul").strftime('%Y-%m-%d_%H%M%S')} (UTC+9)" } # 작업 완료 후 추가적인 파일생성 및 메세지 내용
      end

      system "cd /tmp; rm -rf #{zipFileName}.zip"
    rescue
      system "cd /tmp; rm -rf #{zipFileName}.zip"
    end
  end
end

 

 

  • 자료 참고

1. Github : Official Rubyzip repository

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함