reload_from_s3.rb 2.75 KB
#
# Author:: Earth U (<sysadmin @ chromedia.com>)
# Cookbook Name:: cfe-mariadb
# Recipe:: reload_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.
#

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

package 'gzip'
include_recipe 'openssl::upgrade'
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')

priv_key_file = "#{tmp_dir}/priv.key"

file priv_key_file do
  content node['cfe-mariadb']['encrypt']['priv_key'] || ''
  mode      0600
  owner     'root'
  group     'root'
  sensitive true
  only_if   "test -d #{tmp_dir} || mkdir -p #{tmp_dir}"
end

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

  keyname  = "#{dbx[:bak_filename]}.gz#{dbx[:bak_encrypted] ? '.enc' : ''}"
  filepath = "#{tmp_dir}/#{dbx[:bak_filename]}"

  awscli_s3_file "#{tmp_dir}/#{keyname}" do
    region   node['cfe-mariadb']['s3_region']
    bucket   node['cfe-mariadb']['s3_bucket']
    key      keyname
    only_if  "test -d #{tmp_dir} || mkdir -p #{tmp_dir}"
    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
  end

  execute "decrypt_#{filepath}.gz.enc" do
    command  "openssl smime -decrypt -binary -inkey #{priv_key_file} "\
             "-in #{filepath}.gz.enc -out #{filepath}.gz -inform DEM"
    only_if  { ::File.exist?("#{filepath}.gz.enc") }
    notifies :delete, "file[#{filepath}.gz.enc]"
  end

  execute "gzip -d #{filepath}.gz"

  execute "reload_#{filepath}" 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} < #{filepath}"
    notifies  :delete, "file[#{filepath}]"
    sensitive true
  end

  file "#{filepath}.gz.enc" do
    action :nothing
  end

  file filepath do
    action :nothing
  end
end

file priv_key_file do
  action :delete
end