reload_tar_from_s3.rb 2.51 KB
#
# Author:: Earth U (<sysadmin @ chromedia.com>)
# Cookbook Name:: cfe-mariadb
# Recipe:: reload_tar_from_s3
#
# Copyright 2016, Chromedia Far East, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# This recipe is just here for backward-compatibility reasons.
# The previous backups scripts create .tar.gz files, instead of .gz, so
# this recipe is here to get .tar.gz backups.

# Download a tarball of a MySQL dump from an S3 bucket, 
# then load it up into a (preferably empty) database.

include_recipe 'awscli'

tmp_dir = ::File.join(Chef::Config[:file_cache_path], 'db_dumps')
manual_creds = node['cfe-mariadb'].has_key?('reload') &&
               node['cfe-mariadb']['reload'].has_key?('aws_access_key_id')

node['cfe-mariadb']['db_map'].each do |dbx|

  if dbx.is_a?(Array)
    dbx_name = dbx[0]
    dbx = dbx[1]
  else
    dbx_name = dbx[:db_name]
  end

  filesql = "#{tmp_dir}/#{dbx[:bak_filename]}"
  filetgz = "#{filesql}.tar.gz"

  awscli_s3_file filetgz do
    region   node['cfe-mariadb']['s3_region']
    bucket   node['cfe-mariadb']['s3_bucket']
    key      "#{dbx[:bak_filename]}.tar.gz"
    if manual_creds
      aws_access_key_id     node['cfe-mariadb']['reload']['aws_access_key_id']
      aws_secret_access_key node['cfe-mariadb']['reload']['aws_secret_access_key']
    end
    only_if  "test -d #{tmp_dir} || mkdir -p #{tmp_dir}"
    notifies :run, "execute[untar_#{filetgz}]", :immediately
  end

  execute "untar_#{filetgz}" do
    command "tar -xzf #{filetgz} -C #{tmp_dir}/"
    notifies :delete, "file[#{filetgz}]"
    notifies :run, "execute[reload_#{filesql}]", :immediately
    action  :nothing
  end

  execute "reload_#{filesql}" do
    command   "mysql -h #{node['mariadb']['mysqld']['bind_address']} "\
              "-P #{node['mariadb']['mysqld']['port']} -u #{dbx[:db_user]} "\
              "-p'#{dbx[:db_pass]}' -D #{dbx_name} < #{filesql}"
    notifies  :delete, "file[#{filesql}]"
    sensitive true
    action    :nothing
  end

  file filetgz do
    action :nothing
  end

  file filesql do
    action :nothing
  end
end