Provision Chef using Packer on local machine

1.2k views Asked by At

I'm new to Chef/Packer so apologies if this is a novice question, basically I'm trying to get Packer to use my local machine to build the image and execute a shell script. Following is my packer-build.json

{
  "builders": [
    {
      "type": "file",
      "name": "example",
      "target": "./test_artifact.txt",
      "content": "example content"
    }
  ],
  "provisioners": [
    {
      "type": "chef-solo",
      "cookbook_paths": ["/Users/bakthak/code/nc_deployment/chef-repo/cookbooks"],
      "staging_directory": "/Users/bakthak",
      "execute_command": "sh /Users/bakthak/check.sh"
    }
  ]
}

Running build with this file produces the output

==> example: Provisioning with chef-solo
    example: Installing Chef...
    example: Creating directory: /Users/bakthak
    example: Creating directory: /Users/bakthak/cookbooks-0
    example: Creating configuration file 'solo.rb'
    example: Creating JSON attribute file
    example: Executing Chef: sh /Users/bakthak/check.sh
Build 'example' finished.

I had a few questions about this:

  1. Is packer using my local machine to install chef and build the image?
  2. Looks like the shell script sh /Users/bakthak/check.sh is not executed since that script creates a bunch of files in a directory which does not exist after packer build completion.

Thanks for the help :)

1

There are 1 answers

0
seshadri_c On

Packer will connect and run the "provisioner" on the machine/target identified or created in "builders": section. As per the documentation on the file builder:

The file Packer builder is not really a builder, it just creates an artifact from a file. It can be used to debug post-processors without incurring high wait times.

So by using this builder, you are not creating a connection to anywhere. However there is a builder called null which can be used establish an SSH session and run the provisioner.

Consider the example below where 192.168.1.102 is the IP address of my machine (localhost on which packer is running), with the credentials that can SSH to it:

{
  "builders": [
    {
      "type": "null",
      "ssh_host": "192.168.1.102",
      "ssh_username": "user1",
      "ssh_password": "changeit"
    }
  ],
  "provisioners": [
    {
      "type": "chef-solo",
      "cookbook_paths": ["/home/user1/.chef/cookbooks"],
      "run_list": "my_cookbook",
      "execute_command": "sh /home/user1/myscript.sh"
    }
  ]
}

That said, it would be better to stick to the default execute_command, for the chef-solo provisioner:

chef-solo --no-color -c <ConfigPath> -j <.JsonPath>

and run the script from a Chef resource:

my_cookbook/recipes/default.rb:

script 'myscript.sh' do
  interpreter 'bash'
  cwd '/home/user1/'
  code <<-EOH
    # Content of the script as
    # some shell commands
  EOH
end