Ant: hostnames made easy

Ant Hostname: sometimes, you just need to know the name of the computer that you’re running the build on. If you can’t get away with using ‘localhost’ (maybe you have host specific properties for each machine the developers work on), then you need to work it out. Most of the advice out there runs towards fetching the ‘COMPUTERNAME’ environment variable if you’re running Ant on a windows system, or the ‘HOSTNAME’ environment variable if you’re on a Unix system. If you take that route you can use some simple logic to make that one cross-platform.

You could also run the ‘hostname’ command and put the output in a property. I was never a fan of either to be honest: I don’t like builds depending on the environment, for one.

So I set out to write some Java that would fetch the hostname and set a property with the system’s hostname. It looks like this

    <taskdef classname="org.juliansimpson.HostName" name="hostname" classpathref="cp" />
    <hostname property="hostname" />
    <echo message="property $${hostname} = ${hostname}" />

It works very well. Please feel free to use it. Comments welcome.

Link (952kB Zip file, md5sum “ae82000aa2c4b87b966347cc5a36c200”)
I just put the code on GitHub.

Tagged ,

6 thoughts on “Ant: hostnames made easy

  1. Sudhindra Rao says:

    Hi Julian Here is how you do it for crossplatform.“The env.COMPUTERNAME property line is an interesting trick to get the host name of the machine running the build in a cross-platform manner. Windows machines use the COMPUTERNAME environment variable while ‘nix platforms use HOSTNAME (except Mac OS X, through version 10.2.3 at least, *arg*).”

  2. Julian says:

    Hi Sudhindra,Thanks for your comment.It’s that bit at the end that gets me. šŸ™‚ It seems much easier to get the hostname via cross-platform Java code than to depend on quirks of each platform.BestJulian.

  3. Isaac says:

    nant is trickier. in 0.85 (and maybe earlier) you can use get-machine-name. In 0.86 and newer there is also get-host-hame:

  4. simpsonjulian says:

    Cheers Isaac. That’s one of the things I like about NAnt. Much easier to put simple logic into target ‘if’ or ‘unless’ attributes.

  5. stu taylor says:

    Hi Julian,

    small world!

    I was just shaving a Yak and thought, someone else must have hit this issue. And lo, here i am.

    I’m doing something that feels a bit dirty, in that i don’t care about windows or Mac, because my target is 64bit linux. I do care though that when the instance was spun up it hadn’t be configured fully, so that ‘hostname -d’ returns null. its the domain bit i’m after, so if on the first run it doesn’t exist, i want to create it, because i then go on to create host entries and apache vhosts; i need to level the playing field so to speak.



    • Julian Simpson says:

      Hi Stuart,

      Nice to hear from you. Are you doing this from Ant? There may be nicer tools for this …


Comments are closed.

%d bloggers like this: