0

I'm trying to add new set of FQDN and IPs into the existing Windows hosts file by using the Chef template resources. What I found out is when I ran the chef recipe it will erase the existing hosts file and then add the new updates. I only want to append the new resources to the end of the file, am I doing something wrong here by using action :touch?

template file hosts.erb:

<% node['hostnames'].each do |name, value| %>
<%= value %>
<% end %>

recipe windows.rb file:

template 'C:\\Windows\\system32\\drivers\\etc\\hosts' do
  source 'hosts.erb'
  action :touch
end

kitchen converge output file tells me the hosts file is getting overwritten and not update? why?

   Recipe: hostnames::windows
     * template[C:\Windows\system32\drivers\etc\hosts] action touch
       - update content in file C:\Windows\system32\drivers\etc\hosts from 2d6bdf to 8068b4
       --- C:\Windows\system32\drivers\etc\hosts    2016-07-16 13:21:31.289888800 +0000
       +++ C:\Windows\system32\drivers\etc/chef-hosts20181128-568-1skk2oh   2018-11-28 01:15:55.998460000 +0000
       @@ -1,22 +1,6 @@
       -# Copyright (c) 1993-2009 Microsoft Corp.
       -#
       -# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
       -#
       -# This file contains the mappings of IP addresses to host names. Each
       -# entry should be kept on an individual line. The IP address should
       -# be placed in the first column followed by the corresponding host name.
       -# The IP address and the host name should be separated by at least one
       -# space.
       -#
       -# Additionally, comments (such as these) may be inserted on individual
       -# lines or following the machine name denoted by a '#' symbol.
       -#
       -# For example:
       -#
       -#      102.54.94.97     rhino.acme.com          # source server
       -#       38.25.63.10     x.acme.com              # x client host
       +# Content of the following hostnames are mainten by Chef cookbook

       -# localhost name resolution is handled within DNS itself.
       -#   127.0.0.1       localhost
       -#   ::1             localhost
       +10.219.33.1 a.us.bb-ops.io
       +10.219.34.2 b.us.bb-ops.io
       +10.219.35.3 c.us.bb-ops.io
       - update utime on file C:\Windows\system32\drivers\etc\hosts
Fang
  • 151
  • 1
  • 11

1 Answers1

0

This is proper Chef's behavior. You have two options: 1) Provide whole hosts file as atemplate or 2) Use FileEdit class, for example insert_line_if_no_match-instance_method.

Szymon
  • 1,525
  • 1
  • 11
  • 12
  • Thanks for clarifying the behavior of the "action :touch" it makes sense. I'll be adding all the content to the template as the completed file. I also used the function insert_line_if_no_match and it also works as expected. – Fang Nov 28 '18 at 18:59