Search code examples
rubychef-infra

Writing two variables in a file via chef file resource content


Is it possible to write two variables to a file generated by chef - without using a template erb file?

username = secret[:username]
password = secret[:password]

file "/home/secret_file.txt" do
  content username password
  owner 'user'
  group 'user'
  mode '0755'
end

Adding only one variable is working as expected but with two variables as shown above I get a error message "undefined method `username' for Chef::Resource::File"


Solution

  • Are you looking to add these variables in one line in the file? The content property takes a string type.

    You could do use string interpolation to create a string and add the content to the file:

    username = secret[:username]
    password = secret[:password]
    
    file "/home/secret_file.txt" do
      content "#{username} #{password}"
      owner 'user'
      group 'user'
      mode '0755'
    end
    

    or if you need to format it a certain way:

    username = secret[:username]
    password = secret[:password]
    output = <<-CODE
    The username is #{username}
    The password is #{password}
    CODE
    
    file "/home/secret_file.txt" do
      content output
      owner 'user'
      group 'user'
      mode '0755'
    end