Consul DNS Fowarding in Alpine, revisited

30 Dec 2019

I noticed when running an Alpine based virtual machine with Consul DNS forwarding set up, that sometimes the machine couldn’t resolve *.consul domains, but not in a consistent manner. Inspecting the logs looked like the request was being made and responded to successfully, but the result was being ignored.

After a lot of googling and frustration, I was able to track down that it’s down to a difference (or optimisation) in musl libc, which glibc doesn’t do. From Musl libc’s Functional differences from glibc page, we can see under the Name Resolver/DNS section the relevant information:

Traditional resolvers, including glibc’s, make use of multiple nameserver lines in resolv.conf by trying each one in sequence and falling to the next after one times out. musl’s resolver queries them all in parallel and accepts whichever response arrives first.

The machine’s /etc/resolv.conf file has two nameserver specified:

nameserver 127.0.0.1
nameserver 192.168.121.1

The first is our Unbound instance which handles the forwarding to Consul, and the second is the DHCP set DNS server, in this case, libvirt/qemu’s dnsmasq instance.

When running in a glibc based system, queries go to the first nameserver, and then if that can’t resolve the request, it is then sent to the next nameserver, and so forth. As Alpine Linux uses muslc, it makes the requests in parallel and uses the response from whichever response comes back first.

sequence diagram, showing parallel DNS requests

When the DHCP DNS server is a network hop away, the latency involved means our resolution usually works, as the queries will hit the local DNS and get a response first. However, when the DHCP DNS is not that far away, for example when it is the DNS server that libvirt runs in the virtual network the machine is attached to, it becomes much more likely to get a response from that DNS server first, causing the failures I was seeing.

The solution to this is to change the setup so that all requests go to Unbound, which can then decide where to send them on to. This also has the additional benefits of making all DNS requests work the same on all systems; regardless of glibc or muslc being used.

sequence diagram, showing all DNS requests going through unbound

Rebuilding DNS Resolution

You can follow the same instructions in my previous Consul DNS forwarding post to setup Consul, as that is already in the right state for us.

Once Consul is up and running, it’s time to fix the rest of our pipeline.

Unbound

First, install unbound and configure it to start on boot:

apk add unbound
rc-update add unbound

The unbound config file (/etc/unbound/unbound.conf) is almost the same as the previous version, except we also have an include statement, pointing to a second config file, which we will generate shortly:

server:
 verbosity: 1
 do-not-query-localhost: no
 domain-insecure: "consul"
stub-zone:
 name: "consul"
 stub-addr: [email protected]
include: "/etc/unbound/forward.conf"

Dhclient

Next, we install dhclient so that we can make use of it’s hooks feature to generate our additional unbound config file.

apk add dhclient

Create a config file for dhclient (/etc/dhcp/dhclient.conf), which again is almost the same as the previous post, but this time doesn’t specify prepend domain-name-servers:

option rfc3442-classless-static-routes code 121 = array of unsigned integer 8;
send host-name = gethostname();
request subnet-mask, broadcast-address, time-offset, routers,
 domain-name, domain-name-servers, domain-search, host-name,
 dhcp6.name-servers, dhcp6.domain-search, dhcp6.fqdn, dhcp6.sntp-servers,
 netbios-name-servers, netbios-scope, interface-mtu,
 rfc3442-classless-static-routes, ntp-servers;

Now we can write two hooks. The first is an enter hook, which we can use to write the forward.conf file out.

touch /etc/dhclient-enter-hooks
chmod +x /etc/dhclient-enter-hooks

The content is a single statement to write the new_domain_name_servers value into a forward-zone for unbound:

#!/bin/sh

(
cat <<-EOF
forward-zone:
 name: "."
 forward-addr: ${new_domain_name_servers}
EOF
) | sudo tee /etc/unbound/forward.conf

The second hook is an exit ook, which runs after dhclient has finished writing out all the files it controls (such as /etc/resolv.conf):

touch /etc/dhclient-exit-hooks
chmod +x /etc/dhclient-exit-hooks

The content is a single sed statement to replace the address of nameserver directives written to the /etc/resolv.conf with the unbound address:

#!/bin/sh
sudo sed -i 's/nameserver.*/nameserver 127.0.0.1/g' /etc/resolv.conf

It’s worth noting; we could put the content of the enter hook into the exit hook if you would rather.

Finally, we can delete our current resolv.conf and restart the networking service:

rm /etc/resolv.conf # hack due to it dhclient making an invalid `chown` call.
rc-service networking restart

Testing

We can now test that we can resolve the three kinds of address we care about:

  • dig consul.service.consul - should return the eth0 ip of the machine
  • dig alpinetest.karhu.xyz - should be resolved by libvirt’s dnsmasq instance
  • dig example.com - should be resolved by an upstream DNS server

Conculsion

This was an interesting and somewhat annoying problem to solve, but it means I have a more robust setup in my virtual machines now. It’s interesting to note that if the DNS server from DHCP were not a local instance, the network latency added would make all the system function properly most of the time, as the local instance would answer before the remote instance could.

consul, dns, infrastructure

---

Libvirt Hostname Resolution

22 Dec 2019

I use Vagrant when testing new machines and experimenting locally with clusters, and since moving (mostly) to Linux, I have been using the LibVirt Plugin to create the virtual machines. Not only is it significantly faster than Hyper-V was on windows, but it also means I don’t need to use Oracle products, so it’s win-win really.

The only configuration challenge I have had with it is setting up VM hostname resolution, and as I forget how to do it each time, I figured I should write about it.

Setup

First I install the plugin so Vagrant can talk to Libvirt.

vagrant plugin install vagrant-libvirt

I also created a single vagrantfile with two virtual machines defined in it, so that I can check that the machines can resolve each other, as well as the host being able to resolve the guests.

Vagrant.configure("2") do |config|
 config.vm.box = "elastic/ubuntu-16.04-x86_64"

 config.vm.define "one" do |n1|
 n1.vm.hostname = "one"
 end

 config.vm.define "two" do |n1|
 n1.vm.hostname = "two"
 end
end

Once running vagrant up has finished (either with --provider libvirt or setting ` VAGRANT_DEFAULT_PROVIDER=libvirt`), connect to one of the machines, and try to ping the other:

[email protected]$ vagrant ssh one
[email protected]$ ping two
ping: unknown host two
[email protected]$ exit

Now that we can see they can’t resolve each other let’s move on to fixing it.

Custom Domain

The solution is to configure the libvirt network to have a domain name, and then to set the host machine to send requests for that domain to the virtual network.

First, I picked a domain. It doesn’t matter what it is, but I gather using .local will cause problems with other services, so instead, I picked $HOSTNAME.xyz, which is karhu.xyz in this case.

Vagrant-libvirt by default creates a network called vagrant-libvirt, so we can edit it to include the domain name configuration by running the following command:

virsh net-edit --network vagrant-libvirt

And adding the ` line to the xml which is displayed:

<network ipv6='yes'>
 <name>vagrant-libvirt</name>
 <uuid>d265a837-96fd-41fc-b114-d9e076462051</uuid>
 <forward mode='nat'/>
 <bridge name='virbr1' stp='on' delay='0'/>
 <mac address='52:54:00:a0:ae:fd'/>
+ <domain name='karhu.xyz' localOnly='yes'/>
 <ip address='192.168.121.1' netmask='255.255.255.0'>
 <dhcp>
 <range start='192.168.121.1' end='192.168.121.254'/>
 </dhcp>
 </ip>
</network>

To make the changes take effect, we need to destroy and re-create the network, so first I destroy the vagrant machines, then destroy and restart the network:

vagrant destroy -f
virsh net-destroy --network vagrant-libvirt
virsh net-start --network vagrant-libvirt

Finally, we can re-create the machines, and log in to one to check that they can resolve each other:

[email protected]$ vagrant up
[email protected]$ vagrant ssh one
[email protected]$ ping two
PING two.karhu.xyz (192.168.121.243) 56(84) bytes of data.
[email protected]$ exit

You can also check that the host can resolve the machine names when querying the virtual network’s DNS server:

[email protected]$ dig @192.168.121.1 +short one
> 192.168.121.50

Host DNS Forwarding

The host cant talk to the machines by name still, so we need to tweak the host’s DNS, which means fighting with SystemD. Luckily, we only need to forward requests to a DNS server running on port 53 - if it was on another port then replacing systemd-resolved like my post on Consul DNS forwarding would be necessary.

Edit /etc/systemd/resolved.conf on the host, to add two lines which instruct it to send DNS requests for the domain picked earlier to the DNS server run by libvirt (dnsmasq):

[Resolve]
-#DNS=
+DNS=192.168.121.1
#FallbackDNS=
-#Domains=
+Domains=~karhu.xyz
#LLMNR=no
#MulticastDNS=no
#DNSSEC=no
#DNSOverTLS=no
#Cache=yes
#DNSStubListener=yes
#ReadEtcHosts=yes

Lastly, restart systemd-resolved for the changes to take effect:

systemctl restart systemd-resolved

Now we can resolve the guest machines by hostname at the domain we picked earlier:

[email protected]$ ping one.karhu.xyz
PING one.karhu.xyz (192.168.121.50) 56(84) bytes of data.

Done!

libvirt, vagrant, dns

---

Nomad Good, Kubernetes Bad

21 Nov 2019

I will update this post as I learn more (both positive and negative), and is here to be linked to when people ask me why I don’t like Kubernetes, and why I would pick Nomad in most situations if I chose to use an orchestrator at all.

TLDR: I don’t like complexity, and Kubernetes has more complexity than benefits.

Operational Complexity

Operating Nomad is very straight forward. There are very few moving parts, so the number of things which can go wrong is significantly reduced. No external dependencies are required to run it, and there is only one binary to use. You run 3-5 copies in Server mode to manage the cluster and as many as you want running in Client mode to do the actual work. You can add Consul if you want service discovery, but it’s optional. More on that later.

Compare this to operating a Kubernetes cluster. There are multiple Kubernetes orchestration projects, tools, and companies to get clusters up and running, which should be an indication of the level of complexity involved. Once you have the cluster set up, you need to keep it running. There are so many moving parts (Controller Manager, Scheduler, API Server, Etcd, Kubelets) that it quickly becomes a full-time job to keep the cluster up and running. Use a cloud service to run Kubernetes, and if you must use your own infrastructure, pay someone else to manage it. It’s cheaper in the long run. Trust me.

Deployment

Nomad, being a single binary, is easy to deploy. If you want to use Terraform to create a cluster, Hashicorp provides modules for both AWS and Azure. Alternatively, you can do everything yourself, as it’s just keeping one binary running on hosts, and a bit of network/DNS config to get them talking to each other.

By comparison, Kubernetes has a multitude of tools to help you deploy a cluster. Still, while it gives you a lot of flexibility in choice, you also have to hope that the tool continues to exist and that there is enough community/company/documentation about that specific tool to help you when something goes wrong.

Upgrading The Cluster

Upgrading Nomad involves doing a rolling deployment of the Servers and Clients. If you are using the Hashicorp Terraform module, you re-apply the module with the new AMI ID to use, and then delete nodes (gracefully!) from the cluster and let the AutoScaleGroup take care of bringing new nodes up. If you need to revert to an older version of Nomad, you follow the same process.

When it comes to Kubernetes, please pay someone else to do it. It’s not a fun process. The process will differ depending on which cluster management tool you are using, and you also need to think about updates to etcd and managing state in the process. There is a nice long document on how to upgrade etcd.

Debugging a Cluster

As mentioned earlier, Nomad has a small number of moving parts. There are three ports involved (HTTP, RPC and Gossip), so as long as those ports are open and reachable, Nomad should be operable. Then you need to keep the Nomad agents alive. That’s pretty much it.

Where to start for Kubernetes? As many Kubernetes Failure Stories point out: it’s always DNS. Or etcd. Or Istio. Or networking. Or Kubelets. Or all of these.

Local Development

To run Nomad locally, you use the same binary as the production clusters, but in dev mode: nomad agent -dev. To get a local cluster, you can spin up some Vagrant boxes instead. I use my Hashibox Vagrant box to do this when I do conference talks and don’t trust the wifi to work.

To run Kubernetes locally to test things, you need to install/deploy MiniKube, K3S, etc. The downside to this approach is that the environment is significantly different to your real Kubernetes cluster, and you can end up where a deployment works in one, but not the other, which makes debugging issues much harder.

Features & Choice

Nomad is relatively light on built-in features, which allows you the choice of what features to add, and what implementations of the features to use. For example, it is pretty popular to use Consul for service discovery, but if you would rather use Eureka, or Zookeeper, or even etcd, that is fine, but you lose out on the seamless integration with Nomad that other Hashicorp tools have. Nomad also supports Plugins if you want to add support for your favourite tool.

By comparison, Kubernetes does everything, but like the phrase “Jack of all trades, master of none”, often you will have to supplement the inbuilt features. The downside to this is that you can’t switch off Kubernetes features you are not using, or don’t want. So if you add Vault for secret management, the Kubernetes Secrets are still available, and you have to be careful that people don’t use them accidentally. The same goes for all other features, such as Load Balancing, Feature Toggles, Service Discovery, DNS, etc.

Secret Management

Nomad doesn’t provide a Secret Management solution out of the box, but it does have seamless Vault integration, and you are also free to use any other Secrets As A Service tool you like. If you do choose Vault, you can either use it directly from your tasks or use Nomad’s integration to provide the secrets to your application. It can even send a signal (e.g. SIGINT etc.) to your process when the secrets need re-reading.

Kubernetes, on the other hand, provides “Secrets”. I put the word “secrets” in quotes because they are not secrets at all. The values are stored encoded in base64 in etcd, so anyone who has access to the etcd cluster has access to all the secrets. The official documentation suggests making sure only administrators have access to the etcd cluster to solve this. Oh, and if you can deploy a container to the same namespace as a secret, you can reveal it by writing it to stdout.

Kubernetes secrets are not secret, just “slightly obscured.”

If you want real Secrets, you will almost certainly use Vault. You can either run it inside or outside of Kubernetes, and either use it directly from containers via it’s HTTPS API or use it to populate Kubernetes Secrets. I’d avoid populating Kubernetes Secrets if I were you.

Support

If Nomad breaks, you can either use community support or if you are using the Enterprise version, you have Hashicorp’s support.

When Kubernetes breaks, you can either use community support or find and buy support from a Kubernetes management company.

The main difference here is “when Kubernetes breaks” vs “if Nomad breaks”. The level of complexity in Kubernetes makes it far more likely to break, and that much harder to debug.

nomad, infrastructure, kubernetes

---

Creating a Vault instance with a TLS Consul Cluster

06 Oct 2019

So we want to set up a Vault instance, and have it’s storage be a TLS based Consul cluster. The problem is that the Consul cluster needs Vault to create the certificates for TLS, which is quite the catch-22. Luckily for us, quite easy to solve:

  1. Start a temporary Vault instance as an intermediate ca
  2. Launch Consul cluster, using Vault to generate certificates
  3. Destroy temporary Vault instance
  4. Start a permanent Vault instance, with Consul as the store
  5. Reprovision the Consul cluster with certificates from the new Vault instance

Sequence diagram of the previous numbered list

There is a repository on Github with all the scripts used, and a few more details on some options.

Assumptions:

The Host machine needs the following software available in your PATH:

You have a TLS Certificate you can use to create an intermediate CA with. See this blog post for How to create a local CA

Running

The run.sh script will do all of this for you, but an explanation of the steps is below:

  1. Start a Temporary Vault instance

     echo '
     storage "inmem" {}
     listener "tcp" {
       address = "0.0.0.0:8200"
       tls_disable = 1
     }' > "vault/temp_vault.hcl"
    
     vault server -config="vault/temp_vault.hcl" &
     echo "$!" > vault.pid
    
     export VAULT_TOKEN=$(./configure_vault.sh | tail -n 1)
    
  2. Generate a Vault token for the Consul machines to use to authenticate with Vault

     export CONSUL_VAULT_TOKEN=$(vault write -field=token -force auth/token/create)
    
  3. Launch 3 Consul nodes (uses the CONSUL_VAULT_TOKEN variable)

     vagrant up
    

    The vagrantfile just declares 3 identical machines:

     Vagrant.configure(2) do |config|
       config.vm.box = "pondidum/hashibox"
    
       config.vm.provision "consul",
         type: "shell",
         path: "./provision.sh",
         env: {
             "VAULT_TOKEN" => ENV["CONSUL_VAULT_TOKEN"]
         }
    
       config.vm.define "c1" do |c1|
         c1.vm.hostname = "consul1"
       end
    
       config.vm.define "c2" do |c2|
         c2.vm.hostname = "consul2"
       end
    
       config.vm.define "c3" do |c3|
         c3.vm.hostname = "consul3"
       end
     end
    

    The provisioning script just reads a certificate from Vault, and writes out pretty much the same configuration as in the last post on creating a TLS enabled Consul Cluster, but you can view it in the repository for this demo too.

  4. Create a local Consul server to communicate with the cluster:

     ./local_consul.sh
    

    This is done so that the Vault instance can always communicate with the Consul cluster, no matter which Consul node we are reprovisioning later. In a production environment, you would have this Consul server running on each machine that Vault is running on.

  5. Stop the temporary Vault instance now that all nodes have a certificate

    kill $(cat vault.pid)
    
  6. Start the persistent Vault instance, using the local Consul agent

     echo '
     storage "consul" {
       address = "localhost:8501"
       scheme = "https"
     }
     listener "tcp" {
       address = "0.0.0.0:8200"
       tls_disable = 1
     }' > "$config_dir/persistent_vault.hcl"
    
     vault server -config="$config_dir/persistent_vault.hcl" > /dev/null &
     echo "$!" > vault.pid
    
     export VAULT_TOKEN=$(./configure_vault.sh | tail -n 1)
    
  7. Generate a new Vault token for the Consul machines to use to authenticate with Vault (same as step 2)

     export CONSUL_VAULT_TOKEN=$(vault write -field=token -force auth/token/create)
    
  8. Reprovision the Consul nodes with new certificates

     vagrant provision c1 --provision-with consul
     vagrant provision c2 --provision-with consul
     vagrant provision c3 --provision-with consul
    
  9. Profit

    To clean up the host’s copy of Vault and Consul, you can run this:

     kill $(cat vault.pid)
     kill $(cat consul.pid)
    

Summary & Further Actions

Luckily, this is the kind of thing that should only need doing once (or once per isolated environment). When running in a real environment, you will also want to set up:

  • ACL in Consul which locks down the KV storage Vault uses to only be visible/writeable by Vault
  • Provisioning the VAULT_TOKEN to the machines in a secure fashion
  • Periodic refresh of the Certificates uses in the Consul cluster

consul, vault, infrastructure, security, tls

---

Consul DNS Fowarding in Ubuntu, revisited

24 Sep 2019

I was recently using my Hashibox for a test, and I noticed the DNS resolution didn’t seem to work. This was a bit worrying, as I have written about how to do DNS resolution with Consul forwarding in Ubuntu, and apparently something is wrong with how I do it. Interestingly, the Alpine version works fine, so it appears there is something not quite working with how I am configuring Systemd-resolved.

So this post is how I figured out what was wrong, and how to do DNS resolution with Consul forwarding on Ubuntu properly!

The Problem

If Consul is running on the host, I can only resolve .consul domains, and if Consul is not running, I can resolve anything else. Clearly I have configured something wrong!

To summarise, I want to be able to resolve 3 kinds of address:

  • *.consul addresses should be handled by the local Consul instance
  • $HOSTNAME.mshome.net should be handled by the Hyper-V DNS server (running on the Host machine)
  • reddit.com public DNS should be resolved properly

Discovery

To make sure that hostname resolution even works by default, I create a blank Ubuntu box in Hyper-V, using Vagrant.

Vagrant.configure(2) do |config|
  config.vm.box = "bento/ubuntu-16.04"
  config.vm.hostname = "test"
end

I set the hostname so that I can test that dns resolution works from the host machine to the guest machines too. I next bring up the machine, SSH into it, and try to dig my hostmachine’s DNS name (spectre.mshome.net):

> vagrant up
> vagrant ssh
> dig spectre.mshome.net

; <<>> DiG 9.10.3-P4-Ubuntu <<>> spectre.mshome.net
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 12333
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;spectre.mshome.net.            IN      A

;; ANSWER SECTION:
Spectre.mshome.net.     0       IN      A       192.168.181.161

;; Query time: 0 msec
;; SERVER: 192.168.181.161#53(192.168.181.161)
;; WHEN: Mon Sep 23 21:57:26 UTC 2019
;; MSG SIZE  rcvd: 70

> exit
> vagrant destroy -f

As you can see, the host machine’s DNS server responds with the right address. Now that I know that this should work, we can tweak the Vagrantfile to start an instance of my Hashibox:

Vagrant.configure(2) do |config|
  config.vm.box = "pondidum/hashibox"
  config.vm.hostname = "test"
end

When I run the same command sin this box, I get a slighty different response:

; <<>> DiG 9.10.3-P4-Ubuntu <<>> spectre.mshome.net
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 57216
;; flags: qr aa rd; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;spectre.mshome.net.            IN      A

;; AUTHORITY SECTION:
consul.                 0       IN      SOA     ns.consul. hostmaster.consul. 1569276784 3600 600 86400 0

;; Query time: 1 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Mon Sep 23 22:13:04 UTC 2019
;; MSG SIZE  rcvd: 103

As intended, the DNS server on localhost responded…but it looks like Consul answered, not the inbuilt dns server (systemd-resolved), as I intended.

The reason for this is that I am running Consul’s DNS endpoint on 8600, and Systemd-Resolved cannot send requests to anything other than port 53, so I use iptables to redirect the traffic from port 53 to 8600, which means any local use of DNS will always be sent to Consul.

The reason it works when Consul is not running is that we have both 127.0.0.1 specified as a nameserver, and a fallback set to be the eth0’s Gateway, so when Consul doesn’t respond, the request hits the default DNS instead.

The Solution: Dnsmasq.

Basically, stop using systemd-resolved and use something that has a more flexible configuration. Enter Dnsmasq.

Starting from the blank Ubuntu box, I install dnsmasq, and disable systemd-resolved. Doing this might prevent any DNS resolutio working for a while…

sudo apt-get install -yq dnsmasq
sudo systemctl disable systemd-resolved.service

If you would rather not disable systemd-resolved entirely, you can use these two lines instead to just switch off the local DNS stub:

echo "DNSStubListener=no" | sudo tee --append /etc/systemd/resolved.conf
sudo systemctl restart systemd-resolved

Next I update /etc/resolv.conf to not be managed by Systemd, and point to where dnsmasq will be running:

sudo rm /etc/resolv.conf
echo "nameserver 127.0.0.1" | sudo tee /etc/resolv.conf

The reason for deleting the file is that it was symlinked to the Systemd-Resolved managed file, so that link needed to be broken first to prevent Systemd interfering.

Lastly a minimal configuration for dnsmasq:

echo '
port=53
resolv-file=/var/run/dnsmasq/resolv.conf
bind-interfaces
listen-address=127.0.0.1
server=/consul/127.0.0.1#8600
' | sudo tee /etc/dnsmasq.d/default

sudo systemctl restart dnsmasq

This config does a few things, the two most important lines are:

  • resolv-file=/var/run/dnsmasq/resolv.conf which is pointing to the default resolv.conf written by dnsmasq. This file contains the default nameserver supplied by the default network connection, and I want to use this as a fallback for anything dnsmasq cannot resolve directly (which will be everything, except .consul). In my case, the content of this file is just nameserver 192.168.181.161.

  • server=/consul/127.0.0.1#8600 specifies that any address ending in .consul should be forwarded to Consul, running at 127.0.0.1 on port 8600. No more iptables rules!

Testing

Now that I have a (probably) working DNS system, let’s look at testing it properly this time. There are 3 kinds of address I want to test:

  • Consul resolution, e.g. consul.service.consul should return the current Consul instance address.
  • Hostname resolution, e.g. spectre.mshome.net should resolve to the machine hosting the VM.
  • Public resolution, e.g. reddit.com should resolve to…reddit.

I also want to test that the latter two cases work when Consul is not running too.

So let’s write a simple script to make sure these all work. This way I can reuse the same script on other machines, and also with other VM providers to check DNS works as it should. The entire script is here:

local_domain=${1:-mshome.net}
host_machine=${2:-spectre}

consul agent -dev -client 0.0.0.0 -bind '{{ GetInterfaceIP "eth0" }}' > /dev/null &
sleep 1

consul_ip=$(dig consul.service.consul +short)
self_ip=$(dig $HOSTNAME.$local_domain +short | tail -n 1)
host_ip=$(dig $host_machine.$local_domain +short | tail -n 1)
reddit_ip=$(dig reddit.com +short | tail -n 1)

kill %1

[ "$consul_ip" == "" ] && echo "Didn't get consul ip" >&2 && exit 1
[ "$self_ip" == "" ] && echo "Didn't get self ip" >&2 && exit 1
[ "$host_ip" == "" ] && echo "Didn't get host ip" >&2 && exit 1
[ "$reddit_ip" == "" ] && echo "Didn't get reddit ip" >&2 && exit 1

echo "==> Consul Running: Success!"

consul_ip=$(dig consul.service.consul +short | tail -n 1)
self_ip=$(dig $HOSTNAME.$local_domain +short | tail -n 1)
host_ip=$(dig $host_machine.$local_domain +short | tail -n 1)
reddit_ip=$(dig reddit.com +short | tail -n 1)

[[ "$consul_ip" != *";; connection timed out;"* ]] && echo "Got a consul ip ($consul_ip)" >&2 && exit 1
[ "$self_ip" == "" ] && echo "Didn't get self ip" >&2 && exit 1
[ "$host_ip" == "" ] && echo "Didn't get host ip" >&2 && exit 1
[ "$reddit_ip" == "" ] && echo "Didn't get reddit ip" >&2 && exit 1

echo "==> Consul Stopped: Success!"

exit 0

What this does is:

  1. Read two command line arguments, or use defaults if not specified
  2. Start Consul as a background job
  3. Query 4 domains, storing the results
  4. Stop Consul (kill %1)
  5. Check an IP address came back for each domain
  6. Query the same 4 domains, storing the results
  7. Check that a timeout was received for consul.service.consul
  8. Check an IP address came back for the other domains

To further prove that dnsmasq is forwarding requests correctly, I can include two more lines to /etc/dnsmasq.d/default to enable logging, and restart dnsmasq

echo "log-queries" | sudo tee /etc/dnsmasq.d/default
echo "log-facility=/var/log/dnsmasq.log" | sudo tee /etc/dnsmasq.d/default
sudo systemctl restart dnsmasq
dig consul.service.consul

Now I can view the log file and check that it received the DNS query and did the right thing. In this case, it recieved the consul.service.consul query, and forwarded it to the local Consul instance:

Sep 24 06:30:50 dnsmasq[13635]: query[A] consul.service.consul from 127.0.0.1
Sep 24 06:30:50 dnsmasq[13635]: forwarded consul.service.consul to 127.0.0.1
Sep 24 06:30:50 dnsmasq[13635]: reply consul.service.consul is 192.168.181.172

I don’t tend to keep DNS logging on in my Hashibox as the log files can grow very quickly.

Wrapping Up

Now that I have proven my DNS resolution works (I think), I have rolled it back into my Hashibox, and can now use machine names for setting up clusters, rather than having to specify IP addresses initially.

consul, dns, infrastructure

---