Skip to content

Instantly share code, notes, and snippets.

@ngyuki
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngyuki/6442e80b9ed0a4b62246 to your computer and use it in GitHub Desktop.
Save ngyuki/6442e80b9ed0a4b62246 to your computer and use it in GitHub Desktop.
aws ec2 change route table lsb script
#!/bin/sh
#
# chkconfig: 12345 01 99
# description: EC2 route change
. /etc/rc.d/init.d/functions
prog=${0##*/}
lock=/var/lock/subsys/$prog
instance_id=`curl -s http://169.254.169.254/latest/meta-data/instance-id`
az=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone`
region=${az%[a-z]}
# route_table_id=rtb-xxxxxxxx
# destination_cidr_block=192.168.0.128/32
[ -f /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog
[ -z "$route_table_id" ] && exit 0
[ -z "$destination_cidr_block" ] && exit 0
function has_route
{
cnt=`aws ec2 describe-route-tables --output text --region "$region" --filters \
Name=route-table-id,Values="$route_table_id" \
Name=route.destination-cidr-block,Values="$destination_cidr_block" \
| wc -l`
if [ "$cnt" -gt 0 ]; then
return 0
else
return 1
fi
}
function has_my_route
{
cnt=`aws ec2 describe-route-tables --output text --region "$region" --filters \
Name=route-table-id,Values="$route_table_id" \
Name=route.destination-cidr-block,Values="$destination_cidr_block" \
Name=route.instance-id,Values="$instance_id" \
| wc -l`
if [ "$cnt" -gt 0 ]; then
return 0
else
return 1
fi
}
function create_route
{
echo -n "create route ..."
aws ec2 create-route --output text \
--region "$region" \
--route-table-id "$route_table_id" \
--instance-id "$instance_id" \
--destination-cidr-block "$destination_cidr_block" \
2>&1 | logger -s -i -t "$prog" 2>&1
ret=${PIPESTATUS[0]}
[ "$ret" -eq 0 ] && success || failure
echo
return "$ret"
}
function delete_route
{
echo -n "delete route ..."
aws ec2 delete-route --output text \
--region "$region" \
--route-table-id "$route_table_id" \
--destination-cidr-block "$destination_cidr_block" \
2>&1 | logger -s -i -t "$prog" 2>&1
ret=${PIPESTATUS[0]}
[ "$ret" -eq 0 ] && success || failure
echo
return "$ret"
}
function start
{
has_my_route && return 0
has_route && delete_route
create_route
}
function stop
{
! has_my_route && return 0
delete_route
}
function status()
{
if has_my_route; then
echo ok
return 0
else
echo ng
return 3
fi
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
*)
echo "Usage: ec2-route {start|stop|status}"
exit 2
esac
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment