keepalived check which is master node

15,611

Solution 1

I just had to do this. If you just want to check if the box you are on is floating the public ip and the ip is, say, a.b.c.d, then it is enough to run:

ip a | grep a.b.c.d

I'm pretty sure in bash you can use the output of that command as a conditional itself. If the machine is not floating the public ip, the output should be empty, hence evaluate to false and if there is a match for the ip, then it should evaluate to true.

Solution 2

Here's a generalized script I suggest calling is_primary to do that:

#!/bin/bash
#
# Tells you if this node is the primary or secondary with keepalived

conf=/etc/keepalived/keepalived.conf
# Not sure why I can't do this in 1 step, but this works:
vip=$(expr "$(cat $conf)" : '.*\bvirtual_ipaddress\s*{\s*\(.*\)/*}')
vip=`expr "$vip" : '\([^ ]*\)' | sed 's/\./\\\\./g'`
if ip addr | grep -q "$vip"
then    echo Primary ; exit 0
else    echo Secondary ; exit 1
fi
Share:
15,611

Related videos on Youtube

twb
Author by

twb

Updated on September 18, 2022

Comments

  • twb
    twb over 1 year

    I have 2 app servers both configured to run a php cron job, but only 1 can run the job at any time. Since I am already using keepalived for other purposes, I am thinking of having some logic in the cron job to check if the node has the virtual ip, then execute the job. So theoretically even though both servers are running the cron job at the same time, only 1 will be executing the 'real' job.

    But my question is how to check if the node has the vip? Can someone advise me on that?

    Thanks.

  • parhamr
    parhamr about 8 years
    With a few dozen virtual_ipaddress definitions in keepalived v1.2.7 on Ubuntu 14.04 I do not see a significant difference in the results of ip addr show between the master and secondary nodes.
  • John_Smith
    John_Smith over 4 years
    Exellent, I'll use it! But I will change the suggested name and the echoed strings to master and backup since that is the names used by keepalived. Adding a new set of names for the same thing is sort of obfuscating things I think.