Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using packer to copy file from host to generated image without password

I am currently using packer to generate customized images from a given configuration. The packer .json file includes provisions, which are described in this packer tutorial.

Instead of typing the commands there, I used the shell option in which I can write a bunch of sudo apt-get install commands to customize the images.

The problem is that I need to copy a file from a computer I own to the images. To be clear, the computer I own is also the one I'm running the command packer build example.json.

In the shell script, how can I do a secure copy so that from the perspective of the newly-created images, the image can securely copy the file from my computer to itself, without having to type a password? This is a shell script so I couldn't type one in if I wanted to.

I understand that to avoid typing in the password, I need public/private key authentication. In the shell script, I have:

sudo ssh-keygen -t rsa -b 2048
sudo scp ~/.ssh/id_rsa.pub [email protected]:/home/user/.ssh/uploaded_key.pub
sudo ssh [email protected] "echo `cat ~/.ssh/uploaded_key.pub` >> ~/.ssh/authorized_keys"

(Taken from the example here and elsewhere. My understanding from this is that the image which is generated is running these commands.)

The problem with this and many approaches I see on StackOverflow, such as with this related question, is either one of two things.

  • The first time this public/private authentication happens, it seems like a password is needed. However, this is done entirely in a shell script so I don't know how to avoid it.
  • packer generates these images on the fly, so other approaches that require me to type in explicit AMI IDs for ssh or scp do not seem to work.

A closely related question uses the "file" provision type, but I would like to do this with the "shell" type and I'm not sure how to use both the file and the shell options.

How may I resolve this?

like image 348
ComputerScientist Avatar asked Feb 05 '23 09:02

ComputerScientist


1 Answers

You should use the file provisioner, something like:

"provisioners": [
  {
    "type": "file",
    "source": "source_file",
    "destination": "dest"
  },
  {
    "type": "script",
    "inline": [ "echo do something here" ]
  }
]

See documentation: provisioners

like image 160
Rickard von Essen Avatar answered Feb 06 '23 22:02

Rickard von Essen