Download box from authenticated repo

I have base images hosted in JFrog’s Artifactory.

In order to manually download them I run these commands

export ATLAS_TOKEN=$(curl --silent --user my_user https://example.com/artifactory/api/vagrant/auth)
export VAGRANT_SERVER_URL=http://example.com/artifactory/api/vagrant/vagrant-local
export VAGRANT_SERVER_ACCESS_TOKEN_BY_URL=1
vagrant box add "https://example.com/artifactory/api/vagrant/vagrant-local/my_box.box" --name my-box

A colleague came up with this Ruby snippet for the Vagrantfile

if ['up', 'reload'].include?(ARGV[0])
  #
  # Artifactory ATLAS _TOKEN handling
  #
  require 'net/http'
  require 'uri'
  require 'io/console'

  unless ENV["USERNAME"].nil?
    username = ENV["USERNAME"]
  else
    puts "Enter your username:  "
    username = STDIN.gets.chomp
  end
  password = STDIN.getpass("Password:")

  uri = URI.parse($vagrant_server_base_url + "auth")
  request = Net::HTTP::Get.new(uri)
  request.basic_auth(username, password)

  req_options = {
    use_ssl: uri.scheme == "https",
  }

  response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
    http.request(request)
  end

  puts 'Response code from Artifactory for password retrieval: ' + response.code

  if response.code.to_i == 200
    ENV["ATLAS_TOKEN"] = response.body
    # puts ENV["ATLAS_TOKEN"]
  else 
    puts "Can't obtain ATLAS_TOKEN from Artifactory."
    abort ('Aborting ...' )
  end

  # https://www.jfrog.com/confluence/display/JFROG/Vagrant+Repositories
  ENV["VAGRANT_SERVER_URL"] = $vagrant_repo_url
  # https://www.vagrantup.com/docs/other/environmental-variables#vagrant_server_access_token_by_url
  ENV["VAGRANT_SERVER_ACCESS_TOKEN_BY_URL"] = "1"
end

During our tests we found and filed this bug #12402.

Our intention is to make an authentication plugin out of this.

But first we’d need some guidance as to how to embed that code in a way that seamlessly works with other checks performed by Vagrant, e.g., when you delete a box, when it checks for updates, etc.

How would you go about it?

Hi @soapy1

You were of huge help with the none communicator.

Could you give us some guidance with this code?

We would like to write a plugin for authenticating to repos.

Hmmm, so there exists some documentation for this.

Talks about how to setup a plugin.

This blog post is a bit more in depth

I’m guessing the easiest way to get this to run at the right time is to use a hook. Plugin Development Basics - Action Hooks | Vagrant by HashiCorp

Another option, if you already have code to do what you want in the form of a Vagrantfile is to rely on Vagrantfile merging and drop that snipped into a Vagrantfile in a users ~/vagrant.d directory.

I hope this gives you some direction

1 Like