我正在尝试对PostgreSQL进行基本备份。我的代码是Ruby中的一个简单的Bash运行。它只会执行一个basebackup并将其tar转换为/ tmp /(DIR)
file "/tmp/basebackup.sh" do
user "postgres"
mode 0755
content <<-EOH
su - postgres
export PATH=$PATH:/usr/lib/postgresql/9.2/bin
su -c "/usr/lib/postgresql/9.2/bin/initdb -D /tmp/pg_data/ -s --no-locale --encoding=UTF8" - postgres
su -c "/usr/lib/postgresql/9.2/bin/pg_ctl -D /tmp/pg_data -l logfile start" - postgres
su -c "/usr/lib/postgresql/9.2/bin/psql -c "SELECT pg_start_backup('initial backup for SR')" template1" - postgres
tar -cvf pg_base_backup.tar /tmp/pg_data
su -c "/usr/lib/postgresql/9.2/bin/psql -c "SELECT pg_stop_backup()" template1" - postgres
exit 0
EOH
end
execute "/tmp/basebackup.sh" do
ignore_failure true
action :run
end
有更好的方法吗?
答案 0 :(得分:2)
Ruby支持__END__
,用于标记可运行脚本的结尾。之后的任何内容都不会被正在运行的程序看到,但可以使用DATA
文件句柄访问,该句柄可以是read
,就像普通文件一样。试试这段代码就可以了:
File.open('trashme.txt', 'w') do |content|
content << DATA.read
end
__END__
su - postgres
export PATH=$PATH:/usr/lib/postgresql/9.2/bin
su -c "/usr/lib/postgresql/9.2/bin/initdb -D /tmp/pg_data/ -s --no-locale --encoding=UTF8" - postgres
su -c "/usr/lib/postgresql/9.2/bin/pg_ctl -D /tmp/pg_data -l logfile start" - postgres
su -c "/usr/lib/postgresql/9.2/bin/psql -c "SELECT pg_start_backup('initial backup for SR')" template1" - postgres
tar -cvf pg_base_backup.tar /tmp/pg_data
su -c "/usr/lib/postgresql/9.2/bin/psql -c "SELECT pg_stop_backup()" template1" - postgres
exit 0
我会使用该功能将shell脚本移到普通的Ruby / chef脚本之外,以便维护和清晰。