Search code examples
rubychef-infrachef-recipe

Ruby copy file by extension


I'm trying to execute below command Ruby block from Chef and giving below error.

FileUtils.cp_r Dir.glob "#{node['default']['home']}/standalone/deployments/'*.ear'", "#{node['default']['default_backup_path']}/my_bkp_#{time}", :noop => true, :verbose => true

ArgumentError: wrong number of arguments (given 3, expected 1..2)


Solution

  • Most probably you need parenthesis for your Dir.glob method, it's taking just the first argument being passed, and the rest, is being considered as a FileUtils.cp_r argument, try with:

    FileUtils.cp_r(
      Dir.glob(
        "#{node['default']['home']}/standalone/deployments/'*.ear'", 
        "#{node['default']['default_backup_path']}/my_bkp_#{time}"
      ),
      'destination/',
      noop: true,
      verbose: true
    )
    

    You're passing two patterns argument to the glob method, that's the reason of the error:

    no implicit conversion of String into Integer (TypeError)

    Try just using cp_r for each pattern, like:

    FileUtils.cp_r(
      Dir.glob("#{node['default']['home']}/standalone/deployments/'*.ear'"), 
      'destination/',
      noop: true,
      verbose: true
    )
    
    FileUtils.cp_r(
      Dir.glob("#{node['default']['default_backup_path']}/my_bkp_#{time}"),
      'destination/',
      noop: true,
      verbose: true
    )
    

    I think your goal is to iterate get the elements in

    • "#{node['default']['home']}/standalone/deployments/'*.ear'"
    • "#{node['default']['default_backup_path']}/my_bkp_#{time}"

    so you could iterate over these two directories, and use this pattern within the Dir.glob method, like:

    patterns = [
      "#{node['default']['home']}/standalone/deployments/'*.ear'", 
      "#{node['default']['default_backup_path']}/my_bkp_#{time}"
    ]
    patterns.each do |pattern|
      FileUtils.cp_r Dir.glob(pattern), 'destination/', noop: true, verbose: true
    end
    

    Where 'destination/' is the folder in which the elements will be copied, that you're missing.

    Or in the case you want to use the default_backup_path folder as destination, then you don't need the Dir.glob method, just add it as the dest parameter, as a String

    FileUtils.cp_r(
      Dir.glob("#{node['default']['home']}/standalone/deployments/'*.ear'"),
      "#{node['default']['default_backup_path']}/my_bkp_#{time}",
      noop: true,
      verbose: true
    )