Skip to content
Advertisement

Shell complains about file permissions when creating a config file

I’m not completely sure if I should ask here, over at the Unix forums or somewhere completely different but, here we go.

I’m using Packer to create a set of images (running Debian 8) for AWS and GCE, and during this process I want to install HAProxy and set up a config file for it. The image building and package installation goes smooth, but I’m having problems with file permissions when I’m trying to either create the config file or overwrite the existing one.

My Packer Shell Provisioner runs a set of scripts as the user admin (as far as I know I can’t SSH into this setup with root), where as the one I’m having trouble with looks like this:

#!/bin/bash

# Install HAProxy
sudo apt-get update
sudo apt-get install -y haproxy

# Create backup of default config file
sudo mv /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak

# Write content over to new config file
OLDIFS=$IFS
IFS=''
sudo cat << EOF > /etc/haproxy/haproxy.cfg
# Content line 1
# Content line 2
# (...)
EOF
IFS=$OLDIFS

The log output gives me this error: /tmp/script_6508.sh: line 17: /etc/haproxy/haproxy.cfg: Permission denied

I’ve also thought of having a premade config file moved over to the newly created image, but I’m not sure how to do that. And that wouldn’t work without writing permissions either, right?

So, does anyone know how I can set up my Shell script to fix this? Or if there is another viable solution?

Advertisement

Answer

The problem with the script is the line

sudo cat << EOF > /etc/haproxy/haproxy.cfg

The redirection to /etc/haproxy/haproxy.cfg happens before sudo is called, and thus requires that the file can be created and written to by whatever user is running the script.

Your idea of changing the permissions and ownership of that file solves this issue by making the file writable by the user running the script, but really, you seem to be executing every single line of the script as root in any case, so why not just drop all the sudos altogether and run the whole thing as root?

$ sudo myscript.sh   # executed by the 'admin' user

EDIT: Since this script isn’t run on the target machine manually, there are two solutions:

  1. Go with the chmod solution.
  2. Write the config file to a temporary file and move it with sudo.

The second solution involves changing the line

sudo cat << EOF > /etc/haproxy/haproxy.cfg

to

cat <<EOF >/tmp/haproxy.cfg.tmp

and then after the EOF further down

sudo cp /tmp/haproxy.cfg.tmp /etc/haproxy/haproxy.cfg
rm -f /tmp/haproxy.cfg.tmp

This is arguably “cleaner” than messing around with file permissions.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement