Updating configuration files for EC2 dynamic IP’s

Needed to connect some of the EC2 instances running my kids Minecraft servers. Problem is, I am cheap and run a bunch of the free tier instances. I need to stop and start the instances all the time to save on the hosting costs. This results in all of them getting new IP addresses all the time, which makes a mess of the application server configurations. I can use a dynamic DNS service to address the basic requirement to give the main server an address. But then I also needed to connect several of them together, and their addresses keeps changing..

The solution is actually very simple (as usual). The AWS development kit provides means to query all my AWS instance information, including their names and IP addresses. The name is actually just a tag given to the instance, so any other tag could be used as well. To give a simple interface to redo configurations I just query the data, put all the addresses using their tag information as keys and use a template engine to generate a list of the IP addresses preformatted for the server configuration. The server in this case being BungeeCord, which needs to be able to forward players to the different EC2 instances.

Java code:

    AWSCredentials credentials = null;
    try {
      credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (Exception e) {
      throw new AmazonClientException("Cannot load AWS credentials.", e);
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);
    Region eu = Region.getRegion(Regions.EU_CENTRAL_1);
    DescribeInstancesResult result = ec2.describeInstances();
    List<Reservation> reservations = result.getReservations();
    for (Reservation res : reservations) {
      List<Instance> instances = res.getInstances();
      for (Instance ins : instances) {
        String ip = ins.getPublicIpAddress();
        List<Tag> tags = ins.getTags();
        for (Tag tag : tags) {
          String key = tag.getKey();
          if (key.equals("Name")) {
            String name = tag.getValue();
            vc.put(name + "-ip", ip);

    StringWriter sw = new StringWriter();
    velocity.mergeTemplate("template.vm", "UTF8", vc, sw);
    write(sw.toString(), "generated.txt");

With this, it gets the names of all of my EC2 instances, loads a Velocity template and sets a key-value pair with key=-ip and the value as IP. I then run Velocity to generate a configuration file with the current instance IP addresses filled in. Now the kids can just run the command to update the server config.


One thought on “Updating configuration files for EC2 dynamic IP’s

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s