4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LinuxのSystemログをAWS CLI+RubyでS3にアップロードするスクリプトを書いた

Last updated at Posted at 2015-12-04

はじめに

td-agentなんかが流行りの今、systemログをそのまんまバックアップしたいなんてのは誰もが"それほんとに後で使うのかよ?"と言いたくなると思うのですが、まぁ業務命令なのでやってみた次第。

AWS CLI + Ruby

S3へファイルをアップロードさせるツールは、s3syncやs3cmdなどありますが、
純正のものを使っておいたほうが後々のAPIの変更にも強かろうと思い、AWS CLIをRubyからコールすることにした。
(AWS Ruby SDKもありますが、こちらもバージョンによってAPIの仕様がガラッと変わったこともあったので。あと、AWS CLIのほうが直感的に使える気が個人的にはしてます)

使い方など

実行サーバーはScientificLinux6.5。

AWS CLIのインストール&設定

こちらを参考に。

CentOS6.5にaws-cliをインストール

実行

git clone git@bitbucket.org:FOURIER_INC/fanatic.git
cd fanatic
bundle install
bundle exec app.rb

コード

特に説明するようなこともないかな。。
Rubyで書いているけど、Kernel#systemでシェルを実行しているだけ。

複数のサーバーで実行することを想定しているので、s3://#{バケット名}/#{ホスト名} 以下にログが保存されるようにしてる。

app.rb
# 保存するログを格納しているディレクトリへのパス
target_dir_path = [
  "/var/log/httpd",
  "/var/log/mysql",
  "/var/log/messages"
]
target_file_path = [
  "/var/log/lastlog",
  "/var/log/maillog","
  ""/var/log/yum-log",
  "/var/log/secure"
]

# 保存するバケット名
target_bucket = "log-transfer"
# プレフィクス(サーバー名)
target_prefix = `hostname`.strip

# upload directories
target_dir_path.each do |path|
  next unless Dir.exist? path

  # "./test_dir" => "test_dir"
  dirname = path.split("/").last
  [
    "aws s3 sync #{path} s3://#{target_bucket}/#{target_prefix}/#{dirname}",
    "aws s3 ls s3://#{target_bucket}"
  ].each do |command|
    system command
  end
end

# upload files
target_file_path.each do |path|
  next unless File.exist? path

  filename = path.split("/").last
  [
    "aws s3 cp #{path} s3://#{target_bucket}/#{target_prefix}/#{filename}",
    "aws s3 ls s3://#{target_bucket}"
  ].each do |command|
    system command
  end
end

まとめ

こういう実装が良いのかはわからないけど、シェルスクリプトをゴリゴリ書くの嫌だなぁと思う僕のような人にはRubyでサクッと書けるのはいいなぁと。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?