Connect from Golang to Consul with TLS

This post shows how to turn on TLS for connections to Consul from with hashicorp's official API library for Golang

Posted by Tobias Begalke on Mon Oct 31 2016
In Golang
Tags golang ssl

Consul is able to use SSL certificates in order to authenticate connections and to encrypt traffic. As a requirement for the rest of this post I’m assuming you have successfully set up Consul encryption.

The official Golang API library can be made to use SSL but documentation regarding how is not abundant, so here goes:

consulTLSConfig, err := consulAPI.SetupTLSConfig(&consulAPI.TLSConfig{
  Address:            "my.consul-server.address",
  CAFile:             "/etc/consul/ca.pem",
  CertFile:           "/etc/consul/client-cert.pem",
  KeyFile:            "/etc/consul/client-key.pem",
  InsecureSkipVerify: true,

This is how you create a *tls.Config struct that will in the next step configure the TLS connection for Consul’s http client.

The Address field needs to contain the hostname or IP address of your Consul server. CAFile, CertFile and KeyFile are self-explicatory. Specify the path to each of the three files you have created earlier according to the tutorial mentioned in the Consul docs.

InsecureSkipVerify is set to true because the Consul nodes, for some reason, require certificates that don’t match their hostnames.

consulConfig := consulAPI.DefaultConfig()
consulConfig.Address = ""
consulConfig.Scheme = "https"
if err != nil {
  panic(fmt.Sprintf("SSL Configuration error: %s\n", err))

consulConfig.HttpClient.Transport = &http.Transport{
  TLSClientConfig: consulTLSConfig,

consulConn, err = consulAPI.NewClient(consulConfig)
if err != nil {
  panic(fmt.Sprintf("Consul error: %s\n", err))

This creates a new TLS-enabled Consul client. The magic is where you overwrite the default config’s HttpClient.Transport with one that contains the correct TLSClientConfig.

Photo Credits

Consul by jimmy pereira (licensed under CC BY 2.0).