Search code examples
amazon-web-serviceschef-infracookbook

Get instance public ip with chef recepie


I try to get ip address of the instance and create my cron job:

command "curl --silent \"http://#{instance['public_ip']}/module.php/cron/cron.php?key=TPUmg16HBBZ8G2LgyySulHHuC2fGdIjf&tag=hourly\" > /dev/null 2>&1"

But when the instance lanched and when i list the cron job i found that {instance['public_ip']}= wrong ip address. Can some one help me ? is this the right why to get the ip @


Solution

  • If the machine has multiple IPs, Chef can sometimes return the IP we aren't expecting. In order to find the IP required, Chef support suggested overriding Ohai and that ended up working for us.

    Create an attribute to regex match the IP expected:

    default['ohai']['override']['ip_matcher'] = '/^10\.\d+\.\d+\.4\d+/'

    Then we have to literally override Ohai by writing a file named with a Z, so it saves the IP address we want last.

    # dynamically grab the path name
    ohai_path = ::File.join(Ohai.config[:plugin_path][0], '/windows')
    
    template "#{ohai_path}/zeta.rb" do
      # keep this template named zeta so it runs last.
      source 'zeta.rb.erb'
      variables(
        ip_matcher: node['ohai']['override']['ip_matcher']
      )
    end
    

    The template file looks like this (and was provided by Chef support):

    Ohai.plugin(:Zeta) do
      provides 'ipaddress'
      depends 'ipaddress', 'network/interfaces'
    
      collect_data do
        network['interfaces'].each do | interf |
          network['interfaces']["#{interf[0]}"]['addresses'].each do | ip |
            if ip[0] =~ <%= @ip_matcher %>
              ipaddress ip[0]
            end
          end
        end
      end
    end
    

    Hope this helps!