Packer: Shell script fails with permission denied, using sudo

Created on 11 Sep 2014  ยท  8Comments  ยท  Source: hashicorp/packer

ERROR:
/tmp/script.sh: 3: /tmp/script.sh: cannot create /root/.bashrc: Permission denied

SNIPPET:

  "builders": [{
    "type": "amazon-ebs",
    "access_key": "{{user `aws_access_key`}}",
    "secret_key": "{{user `aws_secret_key`}}",
    "region": "eu-west-1",
    "source_ami": "ami-0307d674",
    "instance_type": "c3.2xlarge",
    "ssh_username": "ubuntu",
    "ami_name": "packer-build-slave-0.1-{{timestamp}}"
  }
  ],
  "provisioners": [
    {
    "type": "shell",
    "inline": [
      "sudo apt-get install -y ksh",
      "sudo echo 'source /etc/profile.d/rvm.sh' >> /root/.bashrc"
    ]
    },

The failing line:
sudo echo 'source /etc/profile.d/rvm.sh' >> /root/.bashrc

works fine with the Vagrant shell provisioner, and also executing it manually, after logging in with SSH.
The "sudo apt-get" command works fine as well.

Please advise.
Thanks

Most helpful comment

You can't do like that, since you only sudo the _echo 'source..._ part no the redirect.

"sudo echo 'source /etc/profile.d/rvm.sh' >> /root/.bashrc"

Try something like:

"sudo bash -c \"echo 'source /etc/profile.d/rvm.sh' >> /root/.bashrc\""

And please try in a shell before automating.

All 8 comments

You can't do like that, since you only sudo the _echo 'source..._ part no the redirect.

"sudo echo 'source /etc/profile.d/rvm.sh' >> /root/.bashrc"

Try something like:

"sudo bash -c \"echo 'source /etc/profile.d/rvm.sh' >> /root/.bashrc\""

And please try in a shell before automating.

This also happens when I'm running this:
sudo echo "test" > /root/something

Using a standalone .sh file when I'm running a provisioner with type: shell

@Binternet yes see my previous answer.

@rickard-von-essen Got it, thanks.
Any reason why you need to use this syntax in packer and not just plain sudo command?

By the way, I've tried cat multiple lines into a file, quite annoying getting it to work via packer.

sudo echo "test" > /root/something never works, regardless of Packer. Everything after the redirect (>) is executed as the non-privileged user, that's just how shells works.

The only thing getting a bit more annoying in Packer with inline scripts are that you need to (json) quote ", but if you have trouble with that it's time to switch to scripts.

You can ask for general help with Packer and automation on _IRC #packer-tool, Freenode_ or the mailing list.

It's probably a permissions error on whatever you're trying to echo into.

I'm going to lock this issue because it has been closed for _30 days_ โณ. This helps our maintainers find and focus on the active issues.

If you have found a problem that seems similar to this, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further.

Was this page helpful?
0 / 5 - 0 ratings