While there’s no “best practice” on how to add entries to a local hosts file, I’d strongly recommend against using FileEdit directly - I’ve found it really hard to debug when the logic goes beyond a single line.
To start off with: I highly suggest using a layered cookbook approach. Have a “base” worker cookbook, and a “wrapper” that defines the node attributes appropriately. It will make your life easier if you are working on a project that has a “medium” or larger scope and complexity.
I also, personally, tend to shy away from databags unless the information is sensitive and needs to be encrypted. They are not versioned by default - if you wish to change the format of the databag, everything which uses that databag must be kept in lockstep. Doing it in node attributes in a cookbook means that “schema” changes don’t break nodes running a different version (such as multiple environments).
Now, that being said, however you get your variables, I’m going to suggest another change in the hashes you are using for “ease of loop”:
Giving you a hash where iem_hosts[node.chef_environment][hostname] will give you the correct ip for the host. Then your template can do something like this:
(assuming your template resource passes :iem_hosts => iem_hosts[node.chef_environment ):
## This file generated by chef
127.0.0.1 localhost localhost.localdomain
<%=node['ipaddress']%> <%=node['hostname']%> <%=node['fqdn']%>
## IEM hosts
<% @iem_hosts.each do |cur_host, cur_ip| %>
<%=cur_ip%> <%=cur_host.split('.')[0]%> <%=cur_host%>
<%end%>
This should give the kind of output you are looking for. I also highly suggest reading over the templates documentation: https://docs.chef.io/resources.html#template
It is rather thorough.
Do I need to mention or define anywhere about chef_envirnoment?
If I create a databag with diff env and call node[chef.environment] , how it reads the env ?
I was looking at chef_envrinoment resource In chef docs and saw 4 env, staging, prod, testing and dev. Can I add one more env? if yes how?
I'll try to answer these as best I can:
0. chef_environment is the environment in chef server your node is assigned into, it is a an "automatic" level attribute.
I'm not clear on what you mean with this question, unless my previous answer covers it.
You can define any number of environments you like. See: About Environments
You should really try to have Chef manage the whole file. When you only partially manage a file, you open yourself to a lot of situations where the file can have different content based on the history of how the edits were applied.
That said, if you have no other option than to edit a file line-by-line, you can use a cookbook like this one to help you do that: https://supermarket.chef.io/cookbooks/line