Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add file::with_tmpfile() function #3288

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions bolt-modules/file/lib/puppet/functions/file/with_tmpfile.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# frozen_string_literal: true

require 'tempfile'

# Create a temporary file and execute the block with the filename created as an
# argument. The file is deleted after the block execution. This will only
# operate on the machine you run Bolt on.
Puppet::Functions.create_function(:'file::with_tmpfile') do
# @param basename Determines the name of the temporary file (see ruby's Tempfile.new)
# @param tmpdir Directory to place the temporary file in (ruby's Dir.tmpdir is default value)
# @param block The block to execute with a temporary filename
# @example Run a command with a temporary file
# # NOTE: This will work on the Bolt controller node only!
# $res = file::with_tmpfile('foo') |$filename| {
# run_command("do_something_with '${filename}'", 'localhost')
# upload_file($filename, $targets)
# }
dispatch :with_tmpfile do
param 'String', :basename
optional_param 'Optional[String[1]]', :tmpdir
block_param 'Callable[1, 1]', :block
return_type 'Any'
end

def with_tmpfile(basename = '', tmpdir = nil)
# Send Analytics Report
Puppet.lookup(:bolt_executor) {}&.report_function_call(self.class.name)

f = Tempfile.new(basename, tmpdir)
f.close
begin
result = yield f.path
ensure
f.unlink
end

result
end
end
12 changes: 12 additions & 0 deletions bolt-modules/file/spec/functions/file/with_tmpfile_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

require 'spec_helper'

describe 'file::with_tmpfile' do
it do
is_expected.to run
.with_params('foo')
.with_lambda { |_| 'bar' }
.and_return('bar')
end
end
Loading