Copy file from chef client node to workstation

2019-01-25 22:47发布

问题:

I would like to know how to transfer a file from a client node to a remote machine. I have checked whether there any resource available for doing this. The closest thing I found is remote_file, but it is fetching a file from remote location and transfer it to the client node.

So I tried another option by writing a bash script which will perform an automated scp. But I cant able to copy the file, but the chef-client was running fine without showing any errors.

Here is my script for copying the file:

#!/usr/bin/expect -f

# connect via scp
spawn scp "/tmp/testfile" chef-ws@10.232.110.113:/home/chef-ws/fileserver

expect {
-re ".*es.*o.*" {
exp_send "yes\r"
exp_continue
}
-re ".*sword.*" {
exp_send "password\r"
}
}
interact

I have copied this script in my cookbook's templates directory as automatecopy.erb and then in default.rb, I have the following code

template "/tmp/automatecopy" do
  source "automatecopy.erb"
  mode 0777
end

execute "automatecopy" do
  command "/usr/bin/expect /tmp/automatecopy"
  timeout 100
  action :run
end

Here, the chef-client runs successfully, but the file was not copied to my workstation machine. One more thing is that, when I logged in to my client node and run the script from there, its working. So why chef failing on do so?

Please help me to solve this issue by suggesting what can be wrong or is there any in built chef resource that can be used for copying files from client to workstation.

P.S: Both my workstation and client node was running Ubuntu 12.04. Thanks in advance.

回答1:

I have found solution for this.Thanks to this SO post which is similar to my need and there i found the usage of sshpass instead of expect. So I altered my script like below and now chef is happy and its copying...:)

Modified script using sshpass

#!/bin/bash

#Copy file from client's source path to workstation's dest path
sshpass -p <%= @password%> scp -o StrictHostKeyChecking=no <%= @sourcefile%> <%= @user%>@<%= @ip%>:<%= @destinationpath%>

And in default.rb

template "/tmp/automatecopy" do
  source "automatecopy.erb"
  mode 0777
  variables(
       :user=> "chef-ws",
       :ip=> "10.232.110.113",
       :sourcefile=> "/tmp/outfile",
       :destinationpath => "/home/chef-ws/fileserver",
       :password=> "pass"
  )
end