Categories
DevOps

How to setup apt-cacher-ng Vagrant box

Vagrant is an awesome piece of software, but constantly downloading system packages can be very time-consuming. The simplest solution is to set up an apt caching proxy as a Vagrant box.

Server configuration

Vagrant configuration file for apt caching proxy.

# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|
        # base box
        config.vm.box = "debian/jessie64"
        # private network IP address
        # it will be used as local proxy
        # apt configuration defined on a client: Acquire::http::Proxy "http://192.168.33.10:3142";
        config.vm.network "private_network", ip: "192.168.33.10"
        # virtualbox configuration
        config.vm.provider "virtualbox" do |vb|
                # memory
                vb.memory = "256"
                # cpu
                vb.cpus = 1
        end
        # install and configure apt-cacher-ng
        config.vm.provision "shell", inline: <<-SHELL
                sudo apt-get update
                sudo apt-get install -y apt-cacher-ng
                sudo sed -i -e "/AdminAuth/c AdminAuth: administrator:password" /etc/apt-cacher-ng/security.conf
        SHELL
end

Client configuration

Simple Vagrant shell provision block using defined apt caching proxy.

config.vm.provision "shell", inline: <<-SHELL
	echo "===> Define cache server"
	echo Acquire::http::Proxy \\"http://192.168.33.10:3142\\"\\; | sudo tee /etc/apt/apt.conf.d/00proxy

	echo "===> Update packages"
	sudo apt-get update
SHELL

Use DIRECT keyword to skip using a proxy for a defined server.

config.vm.provision "shell", inline: <<-SHELL
	echo "===> Define cache server"
	echo Acquire::http::Proxy \\"http://192.168.33.10:3142\\"\\; | sudo tee /etc/apt/apt.conf.d/00proxy

	echo "===> Skip using proxy for personal.repository.local"
	echo Acquire::HTTP::Proxy::personal.repository.local \\"DIRECT\\"\\; | sudo tee -a /etc/apt/apt.conf.d/00proxy

	echo "===> Update packages"
	sudo apt-get update
SHELL

Additional notes

Shell code that can be used outside of Vagrant does not require so many escape sequences.

echo Acquire::http::Proxy \"http://192.168.33.10:3142\"\; | sudo tee /etc/apt/apt.conf.d/00proxy