How to print or get IP and Hostname of VM in config file using Chef Template?

Hi,

I am a beginner in Chef Infra and I am trying to achieve this. I went through documentation here template Resource and was able create a sudoers file as mentioned, be defining the values in attributes file. I would like to print the IP and Hostname of VM in a config file. Suppose I have a file like test.config like below;

hostname: <hostname_of_vm>
host_address: <ip_address>

is it possible to fill hostname and ip using template? Can somebody please help me with this?

Thanks.

Hello! You could accomplish this a few ways, but the article you were looking at is a great source for different ways of doing it

You can pass explicit named variables to a template, or you could read node attributes directly which would likely be easier in this case.

hostname: <%= node['hostname'] %>
host_address: <%= node['ipaddress'] %>

The node attributes above are referenced here, collected via OHAI: About Ohai

If this is my template resource:

template '/tmp/myfile.txt' do
  source 'myfile.txt.erb'
  action :create
end

and this is my template file:

hostname: <%= node['hostname'] %>
host_address: <%= node['ipaddress'] %>

It will render out like this (as seen in test kitchen):

  * template[/tmp/myfile.txt] action create
    - create new file /tmp/myfile.txt
    - update content in file /tmp/myfile.txt from none to 0a020d
    --- /tmp/myfile.txt 2021-02-16 14:35:52.120293022 +0000
    +++ /tmp/.chef-myfile20210216-15-1os8qbo.txt        2021-02-16 14:35:52.119293022 +0000
    @@ -1 +1,3 @@
    +hostname: dokken
    +host_address: 172.18.0.2
1 Like