0

I want to use private ip address later in my Chef recipe for that how can I catch it in a variable. My code looks like...

execute 'privateip' do
command 'curl http://169.254.169.254/latest/meta-data/local-ipv4'
action :run
end

I want to catch the output of curl command in a variable something like..

privip = 'curl http://169.254.169.254/latest/meta-data/local-ipv4'

and then use that value in configuration file OR is there any way to get the private ipaddresses of aws instance, because ohai doesn't support the privateip attribute. Any help will highly appreciated.

Sagar Ghuge
  • 231
  • 3
  • 9
  • Possible duplicate of [How can I put the output of a Chef 'execute resource' into a variable](http://stackoverflow.com/questions/16309808/how-can-i-put-the-output-of-a-chef-execute-resource-into-a-variable) – StephenKing Jan 06 '16 at 12:27

1 Answers1

1

You can read the local-ipv4 value in the node['ec2']['local_ipv4'] attribute. IIRC all the EC2 meta-data is included under node['ec2'].

If you still prefer to run a command, you can use the shell_out! helper:

output = shell_out!('mycommand --some --arguments').stdout

As they said in the comments, for this particular case you can also use the Chef::HTTP class:

http = Chef::HTTP.new('http://169.254.169.254')
privip = http.get('/latest/meta-data/local-ipv4')
zuazo
  • 5,398
  • 2
  • 23
  • 22
  • Why not use ruby's HTTP libraries directly? – StephenKing Jan 06 '16 at 18:08
  • So a few levels of "don't actually do this". First, as mentioned, you should use `Chef::HTTP` for HTTP requests. Second, you should always use the `shell_out!` wrapper when possible. I'll edit the answer. – coderanger Jan 06 '16 at 18:18
  • The only limitation of using `shell_out!` is that it does not work with Chef 11. You need Chef 12. But it looks much simpler. Of course, in this particular case, it is better to use the HTTP libraries if you know how. Thanks Noah! – zuazo Jan 07 '16 at 02:33
  • Thanks...I will try this in my recipe. – Sagar Ghuge Jan 11 '16 at 08:39