Consul Service Discovery

Sets up HashiCorp Consul for service discovery and configuration

Script Author

Rowan de Haas's avatar
Rowan de Haas
Script Author

Script Details

Created 10 months ago
Size 2 KB

Tags

Script Content

Raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#cloud-config
package_update: true
package_upgrade: true

packages:
  - wget
  - unzip
  - curl

users:
  - name: consul
    system: true
    shell: /bin/false
    home: /opt/consul

write_files:
  - path: /etc/consul.d/consul.json
    content: |
      {
        "datacenter": "dc1",
        "data_dir": "/opt/consul/data",
        "log_level": "INFO",
        "server": true,
        "bind_addr": "0.0.0.0",
        "client_addr": "0.0.0.0",
        "retry_join": ["127.0.0.1"],
        "ui_config": {
          "enabled": true
        },
        "connect": {
          "enabled": true
        },
        "ports": {
          "grpc": 8502
        },
        "bootstrap_expect": 1
      }
    permissions: '0640'
    owner: consul:consul

  - path: /etc/systemd/system/consul.service
    content: |
      [Unit]
      Description=Consul
      Documentation=https://www.consul.io/
      Requires=network-online.target
      After=network-online.target
      ConditionFileNotEmpty=/etc/consul.d/consul.json

      [Service]
      Type=notify
      User=consul
      Group=consul
      ExecStart=/usr/local/bin/consul agent -config-dir=/etc/consul.d/
      ExecReload=/bin/kill -HUP $MAINPID
      KillMode=process
      Restart=on-failure
      LimitNOFILE=65536

      [Install]
      WantedBy=multi-user.target

runcmd:
  # Download and install Consul
  - cd /tmp
  - wget https://releases.hashicorp.com/consul/1.16.0/consul_1.16.0_linux_amd64.zip
  - unzip consul_1.16.0_linux_amd64.zip
  - mv consul /usr/local/bin/
  - chmod +x /usr/local/bin/consul
  # Create directories
  - mkdir -p /opt/consul/data
  - mkdir -p /etc/consul.d
  - chown -R consul:consul /opt/consul /etc/consul.d
  # Enable and start Consul
  - systemctl enable consul
  - systemctl start consul
  # Configure firewall
  - ufw allow 8300:8302/tcp
  - ufw allow 8500/tcp
  - ufw allow 8600/tcp
  - ufw allow 8600/udp

How to Use This Script

Cloud Provider Examples

Amazon EC2

aws ec2 run-instances
  --image-id ami-12345678
  --instance-type t3.micro
  --user-data file://script.yaml

DigitalOcean

doctl compute droplet create
  --image ubuntu-22-04-x64
  --size s-1vcpu-1gb
  --user-data-file script.yaml
  my-droplet

Google Cloud

gcloud compute instances create
  my-instance
  --metadata-from-file
  user-data=script.yaml