Writing tasks
Bolt tasks are similar to scripts, but they are kept in modules and can have metadata. This allows you to reuse and share them.
You can write tasks in any programming language the target nodes run, such
as Bash, PowerShell, or Python. A task can even be a compiled
binary that runs on the target. Place your task in the ./tasks
directory of a module and add a metadata file to describe
parameters and configure task behavior.
For a task to run on remote *nix systems, it
must include a shebang (#!
)
line at the top of the file to specify the interpreter.
For example, the Puppet mysql::sql
task is written in
Ruby and provides the path to the Ruby interpreter. This example also accepts several parameters as
JSON on stdin
and returns an
error.
#!/opt/puppetlabs/puppet/bin/ruby require 'json' require 'open3' require 'puppet' def get(sql, database, user, password) cmd = ['mysql', '-e', "#{sql} "] cmd << "--database=#{database}" unless database.nil? cmd << "--user=#{user}" unless user.nil? cmd << "--password=#{password}" unless password.nil? stdout, stderr, status = Open3.capture3(*cmd) # rubocop:disable Lint/UselessAssignment raise Puppet::Error, _("stderr: ' %{stderr}') % { stderr: stderr }") if status != 0 { status: stdout.strip } end params = JSON.parse(STDIN.read) database = params['database'] user = params['user'] password = params['password'] sql = params['sql'] begin result = get(sql, database, user, password) puts result.to_json exit 0 rescue Puppet::Error => e puts({ status: 'failure', error: e.message }.to_json) exit 1 end