Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Create a template within a ruby block
ruby_block "create ssh key" do
block do
k = SSHKey.generate(:type => 'RSA', :bits => 1024, :comment => "Postgres Master")
node.set[:postgresql][:pubkey] = k.ssh_public_key
node.save
# Much of the DSL disappears in ruby blocks. Here's how to create a template.
rc = Chef::RunContext.new(node, node.cookbook_collection)
t = Chef::Resource::Template.new "/var/lib/postgresql/.ssh/id_rsa"
t.source("id_rsa.erb")
t.owner("postgres")
t.group("postgres")
t.cookbook("postgresql")
t.mode("0600")
t.variables(
:k => k.private_key
)
t.action(:create_if_missing)
t.run_context=(rc)
t.run_action("create")
end
not_if { File.exists?("/var/lib/postgresql/.ssh/id_rsa") }
end

chr0n1x commented Feb 15, 2014

Does not seem to work with chef v11.10.0 due to Chef::RunContext requiring an events argument.

@chr0n1x, here's one that works in latest Chef:

ruby_block 'run_my_template_resource' do
  action :create
  block do
    r = Chef::Resource::Template.new('template_name', run_context)
    r.path       '/path/to/write.to'
    r.source     'source.erb'
    r.cookbook   'cookbook-name'
    r.owner      'root'
    r.group      'root'
    r.mode       00600
    r.variables  my: 'variables'
    r.run_action :create
  end
end

mansona commented Mar 28, 2014

@JeanMertz I found this while i was looking for a solution to one of my own problems with RemoteFile. By your example it feels like i should be able to do this:

ruby_block "parse-json" do
    block do
      f =  Chef::Provider::File::RemoteFile.new("/tmp/googlebackup", run_context)
      f.source "http://google.com"
      f.run_action :create
    end
    action :create
  end

but all i get is this error:

[2014-03-28T14:26:08+00:00] ERROR: ruby_block[parse-json] (/tmp/kitchen/cookbooks/jenkins_build_artefact/providers/default.rb line 16) had an error: NoMethodError: No resource or method named `source' for `Chef::Provider::RemoteFile ""'    

Any suggestions?

@mansona in my example, I instantiate the Resource instead of the Provider:

Chef::Resource::RemoteFile

This should not be used, it is not safe and breaks the Chef API.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment