Mark Estrada
Mark Estrada

Reputation: 9201

Replacing a string in between using Chef and Ruby

I have a string that looks like this. Note the spaces in front. I wanted to replace this line that contains this string >"${WLS_REDIRECT_LOG}".

${JAVA_HOME}/bin/java ${JAVA_VM} ${MEM_ARGS} -Dweblogic.Name=${SERVER_NAME} -Djava.security.policy=${WLS_POLICY_FILE} ${JAVA_OPTIONS} ${PROXY_SETTINGS} ${SERVER_CLASS}  >"${WLS_REDIRECT_LOG}" 2>&1

I just don't know if my regex is correct to match the line

mynewline = "TESTTTIIINGGG!!!"
ruby_block "Editing File" do
  block do
    fe = Chef::Util::FileEdit.new("myFile.sh")
    fe.search_file_replace_line(/*>"${WLS_REDIRECT_LOG}"*/, mynewline)
    fe.write_file
  end
  #only_if { File.read("myFile.sh")
end

I am not that good in regex.

Upvotes: 0

Views: 1381

Answers (2)

coderanger
coderanger

Reputation: 54251

FileEdit is an internal API within Chef and is not recommended for use by cookbook code. While you can use other Ruby code as mentioned in the other other answer, in general this kind of approach is very fragile. Creating a replacement that is fully convergent is often difficult, sometimes impossible. Check out cookbooks like line or poise-file for examples of a more refined API expressed as custom resources, but we recommend using fully convergent resources like template or cookbook_file whenever possible for this kind of thing.

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

You don’t need chef for that, plain old good ruby is fine:

corrected = File.read('myFile.sh')
corrected[/>"\$\{WLS_REDIRECT_LOG\}"/] = "TESTTTIIINGGG!!!"
File.write('myFile.sh', corrected)

More info: String#[]=.

Upvotes: 3

Related Questions