作ってしまった…
definitions/execute_on.rb
class ::Chef
class Definition
# execute command on a host via ssh
#
# HOW TO USE:
#
# 1)
#
# execute_on "#{name}" do
# host "#{host}"
# command "#{command}"
# end
#
# 2) notifies must specify `execute` not `execute_on`
#
# cookbook_file "/tmp/foo" do
# source "tmp/foo"
# notifies :run, "execute[#{name}]"
# end
#
# execute_on "#{name}" do
# host "#{host}"
# command "#{command}"
# end
#
# OPTIONS:
#
# Other options are same with `execute` resource.
# See https://docs.chef.io/resource_execute.html
module ExecuteOn
# ssh command
def ssh_command
@ssh_command ||= [
'ssh -S none -T -n',
'-o BatchMode\ yes',
'-o ConnectTimeout\ 5',
'-o StrictHostKeyChecking\ no',
'-o UserKnownHostsFile\ /dev/null',
'-o LogLevel\ ERROR',
].join(' ')
end
module_function :ssh_command
# build ssh command
#
# @param [String] ssh_command Default is self.ssh_command
# @param [String] host
# @param [String] command
# @return [String] built ssh command
def build_command(ssh_command: nil, host: , command: )
ssh_command ||= self.ssh_command
"#{ssh_command} #{host} #{Shellwords.escape(command)}"
end
module_function :build_command
end
end
end
opts = {
:ssh_command => ::Chef::Definition::ExecuteOn.ssh_command,
:host => nil,
}
define :execute_on, opts do
raise ArgumentError, "`host` is missing for execute_on" unless params[:host]
name = params[:name]
command = params[:command] || params[:name]
ssh_command = params[:ssh_command]
execute_params = params.dup.tap do |params|
params.delete(:host)
params.delete(:name)
params.delete(:commond)
params.delete(:ssh_command)
end
command = command.call if command.is_a?(Chef::DelayedEvaluator)
execute_params[:command] = ::Chef::Definition::ExecuteOn.build_command(
ssh_command: ssh_command,
host: params[:host],
command: command,
)
execute name do
execute_params.each {|key, val| send(key, *val) }
end
end
作ったものの ssh_command を作るヘルパーメソッドだけあれば definitions まではいらない気がしてきている。そもそも chef で他のサーバに入って何かするとかやるなっていう。