Ubuntu – Howto use apt-cacher-ng only when available

aptapt-cacher-ngPROXY

I'm using apt-cacher-ng at my local network with the following configuration on the clients:

Acquire::http { Proxy "http://acng-host:3142"; };

Some of the clients are laptops, so how do I configure them to use the cache only when it's available on this network?

Best Answer

Something like this should work:

/etc/NetworkManager/dispatcher.d

#!/bin/bash
ip=10.0.1.13
port=3142
nc -w 1 $ip $port
proxy_file="/etc/apt/apt.conf.d/02local_proxy"
if [ $? -eq 0 ]; then
    echo "Acquire::http { Proxy \"http://$ip:$port\"; };" > $proxy_file
    echo 'Acquire::https { Proxy "false"; };' >> $proxy_file
else
    rm -f $proxy_file
fi

Fix permissions

sudo chmod +x /etc/NetworkManager/dispatcher.d/99SetAptProxy

Notes:

  • The "nc" command tests that it can connect to the 3142 port on the given IP address.
  • This script is run everytime the networking interfaces are changed by network manager.
  • Feel free to alter the way that you detect for the proxy, this works for me, but it is a security vulnerability if you install packages on a foreign network, for example.