How to update the file with multiple lines without deleting the contents of the original file using chef recipe

▼魔方 西西 提交于 2019-12-25 03:57:25

问题


I would like to append my file /var/rsyslog.conf file with the following lines without having to delete my existing file.

Lines to include in the file are

*************
#audit log
$ModLoad imfile
$InputFileName /var/log/audit/audit.log
$InputFileTag tag_audit_log:
$InputFileStateFile audit_log
$InputFileSeverity info
$InputFileFacility local6
$InputRunFileMonitor
*.* @@172.167.189.67:514
*************

In the recipe I gave the following as a file resourse

****
file '/etc/rsyslog.conf' do
    content ' #audit log
    $ModLoad imfile
    $InputFileName /var/log/audit/audit.log
    $InputFileTag tag_audit_log:
    $InputFileStateFile audit_log
    $InputFileSeverity info
    $InputFileFacility local6
    $InputRunFileMonitor'
    *.* @@172.167.189.67:514 --> #This value needs to be dynamically changed using String Intepolation
    mode '0644'
    owner 'root'
    group 'root'
end
****

Although it updated the file, it only has the above lines and all other file contents are now disappeared

I tried creating a new template file with the .erb extension which incidentally also does the same. Inserts the contents but deletes the older file contents.

What would be the suggested way to append the file along with attribute value interpolation.

Use Case:

Attribute.rb file

default['serverIP']['hostname'] = "172.167.189.67:514" This Attribute value will be dynamic and will change periodically.

I would like to use interpolate this in either the file or template so it picks the value provided in the attribute file.

What is the easiest way of achieving this???

Thank you


回答1:


The file resource is for managing the whole file at once as you’ve noticed. We recommend not doing partial file updates as it leads to very brittle Chef core but if you must, check out the poise-file and line cookbooks.




回答2:


as @coderander mentioned it's not recommended to do that in chef, as its better to manage the whole file in Chef.

However if you have to, which is sometimes the case, you can achieve it this way:

bash 'append line(s) to file if it doesnt exist' do
  user 'user'
  code <<-EOS
    cat >>/home/file <<EOL
      *.* @@172.167.189.67:514
      EOL
    EOS
  not_if "grep -q 172.167.189.67 /home/file"
end

you may need to run cookstyle on that ^



来源:https://stackoverflow.com/questions/51848305/how-to-update-the-file-with-multiple-lines-without-deleting-the-contents-of-the

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!