'how to pass parameter to execute in chef?
I'm new to chef. Recently, I'm studying the resources, I got a problem on how to pass parameter to command in execute in chef. Here's the details -- I searched this page -- https://discourse.chef.io/t/pass-parameter-to-bash-script-and-call-bash-scripts-in-chef-cookbook/10431 -- it looks using ruby variable format #{xxx} can pass a variable in recipe to the script in "execute" in recipe I made a test, first my recipe --
execf="haha"
file '/tmp/e.sh' do
content '
#!/bin/bash
cat /tmp/e.log
DT=`date +%F" "%T`
echo $1" "${DT} >> /tmp/e.log
'
mode '755'
execf="e1"
notifies :run, 'execute[e.sh]', :delayed
end
file '/tmp/e2.sh' do
content '
#!/bin/bash
cat /tmp/e.log
DT=`date +%F" "%T`
echo $1" "${DT} >> /tmp/e.log
'
mode '777'
execf="e2"
notifies :run, 'execute[e.sh]', :delayed
end
execute 'e.sh' do
command '/tmp/e.sh #{execf}'
action :nothing
end
I think -- this can record resouce "e.sh" or "e2.sh"'s runtime to e.log. And there's no syntax error when run "chef-client". But to my suprise -- the #{execf} -- is always a "" string while calling /tmp/e.sh... So in e.log, I can only see --
2022-05-13 22:04:48
2022-05-13 22:17:44
2022-05-13 22:19:07
Only a "" was passing to the /tmp/e.sh as $1... At first I think maybe it's due to the execf is a local variable in ruby so I tried @execf and $execf ... but all didn't work. Maybe in recipe, I shouldn't use variable, but should use node attribute? But I can't find how to modify node attribute in resource... Please kind help. Thanks in advance for any idea.
Solution 1:[1]
The main issue is the use of single quotes (''
) in the command
. Single quotes in Ruby don't allow for interpolation of the variable #{execf}
. You should rewrite it as:
execute 'e.sh' do
command "/tmp/e.sh #{execf}"
action :nothing
end
However variable assignment (such as execf="e1"
) in the file
resources will not have any effect. You will get something like haha 2022-05-13 22:04:48
in the logs.
Edit
However variable assignment (such as
execf="e1"
) in thefile
resources will not have any effect.
Turns out that the variable assignment from within resource is also compiled, and last assigned value is used.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |