==== Service Discovery ====
Examples
Add service
#/bin/bash -e
#stop on error
#set -e
######## ARGUMENTS
# retrieve the ec2 instance ID: i-0d39e398760299ce0
instanceId=${1?Pass the ec2 instance ID.}
# retrieve the private ip of the instance: 10.142.251.149
instancePrivateIp=${2?Pass the private ipv4 of the instance.}
# retrieve name of the building: zurich-klinik
buildingName=${3?Pass the name of the building, to be used in the service url.}
# retrieve the vpc id: vpc-00aeb2af06257ebf8
vpcid=${4?Pass the vpc id.}
########## SCRIPT START
dnsnamespace="navvis.local"
servicename="${buildingName}.renderer"
aws servicediscovery create-private-dns-namespace --name $dnsnamespace --vpc $vpcid
# retrieve the namespace id
namespaceId=$(aws servicediscovery list-namespaces --query "\"Namespaces\"[?Name==\`$dnsnamespace\`].Id" --output text)
echo "NameSpaceId: $namespaceId"
# ignore errors, when service already exists
aws servicediscovery create-service --name $servicename \
--dns-config "NamespaceId=$namespaceId,RoutingPolicy=WEIGHTED,DnsRecords=[{Type=A,TTL=10}]" 2> /dev/null
# retrieve the service id
serviceId=$(aws servicediscovery list-services --query "\"Services\"[?Name==\`$servicename\`].Id" --output text)
echo "ServiceId: $serviceId"
aws servicediscovery register-instance --service-id $serviceId \
--instance-id $instanceId --attributes "AWS_INSTANCE_IPV4=$instancePrivateIp"
# ping the service
echo -e "Service available under '$servicename.$dnsnamespace'"
Remove service
#/bin/bash -e
# Removes the services and the namespace, if no instances are available in the service anymore
#stop on error
#set -e
######## ARGUMENTS
# retrieve the building ID: zurich-klinik
buildingName=${1?Pass in the building id.}
########## SCRIPT START
dnsnamespace="navvis.local"
servicename="${buildingName}.renderer"
# get the instance id by service
serviceId=$(aws servicediscovery list-services --query "\"Services\"[?Name==\`$servicename\`].Id" --output text) 2> /dev/null
echo "ServiceId: $serviceId"
# get the instace id by service
instanceId=$(aws servicediscovery list-instances --service-id $serviceId --query "\"Instances\"[0].Id" --output text) 2> /dev/null
echo "InstanceId: $instanceId"
# retrieve the namespace id
namespaceId=$(aws servicediscovery list-namespaces --query "\"Namespaces\"[?Name==\`$dnsnamespace\`].Id" --output text) 2> /dev/null
echo "NameSpaceId: $namespaceId"
# deregister the instance
aws servicediscovery deregister-instance --service-id $serviceId --instance-id $instanceId 2> /dev/null
# deregister the service, will only work if no instances are left
aws servicediscovery delete-service --id $serviceId 2> /dev/null
# deregister the namespace, will only work if no services
aws servicediscovery delete-namespace --id $namespaceId 2> /dev/null
# ping the service
echo -e "Removed service '$servicename.$dnsnamespace'"