Cheh wll not work with bash


#1

Why is happening in chef?

If I run the below command line in the shell…the replace works sed -i
’s/^(127)/#\1/’ /etc/hosts

I use chef it does not work. Kinda shocked. Why is chef having a problem
with line of code?

bash “comment_hostname” do
user “root"
code <<-EOH
sed -i ‘s/^(127)/#\1/’ /etc/hosts
EOH
action :run
not_if {File.exists?(”#{Chef::Config[:file_cache_path]}/hostname_test")}
end


#2

this is a ruby issue, you need to escape
to debug this, you could try to log the script

On Thu, Oct 31, 2013 at 9:20 AM, David Montgomery <davidmontgomery@gmail.com

wrote:

Why is happening in chef?

If I run the below command line in the shell…the replace works sed -i
’s/^(127)/#\1/’ /etc/hosts

I use chef it does not work. Kinda shocked. Why is chef having a problem
with line of code?

bash “comment_hostname” do
user “root"
code <<-EOH
sed -i ‘s/^(127)/#\1/’ /etc/hosts
EOH
action :run
not_if {File.exists?(”#{Chef::Config[:file_cache_path]}/hostname_test")}
end


#3

It’s also possible that file exists, meaning the script will not run. Is recommend running the chef client in debug mode.

Also, please do not do this. Bash scripts are notoriously not idempotentent. Chef has a built in FileEdit utility and there’s also a hostsfile cookbook to handle your specific use case.

You won’t be able to leverage the full power of Chef if you just copy-paste exiting scripts using the bash resource. You should convert them to primitive Chef resources instead.

Not that the script resources (bash, ruby, python) aren’t useful, but you should always ask yourself - “do I really need to use a script resource, or is there a chef primitive that does this for me?”

Consider installing a package. In bash (on Ubuntu) you would do something like:

apt-get install apache2

And on subsequent runs of the script, you would still try to install the package, so you’d need to add a conditional:

if [ dpkg-list | grep apache ]
  apt-get install apache2
end

Whereas if you just use chefs native package resource:

package 'apache2'

:slight_smile:

On Oct 31, 2013, at 4:22 AM, Alexandre Russel alexandre@russel.fr wrote:

this is a ruby issue, you need to escape \
to debug this, you could try to log the script

On Thu, Oct 31, 2013 at 9:20 AM, David Montgomery davidmontgomery@gmail.com wrote:
Why is happening in chef?

If I run the below command line in the shell…the replace works sed -i ‘s/^(127)/#\1/’ /etc/hosts

I use chef it does not work. Kinda shocked. Why is chef having a problem with line of code?

bash “comment_hostname” do
user “root"
code <<-EOH
sed -i ‘s/^(127)/#\1/’ /etc/hosts
EOH
action :run
not_if {File.exists?(”#{Chef::Config[:file_cache_path]}/hostname_test")}
end