2015-01-24 02:33:53 +01:00
#!/usr/bin/python
#
# (c) 2015, Steve Gargan <steve.gargan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = """
module : consul
2015-07-17 07:19:21 +02:00
short_description : " Add, modify & delete services within a consul cluster. "
2015-01-24 02:33:53 +01:00
description :
2015-07-17 07:19:21 +02:00
- Registers services and checks for an agent with a consul cluster .
A service is some process running on the agent node that should be advertised by
2015-04-26 23:27:53 +02:00
consul ' s discovery mechanism. It may optionally supply a check definition,
a periodic service test to notify the consul cluster of service ' s health.
2015-07-17 07:19:21 +02:00
- " Checks may also be registered per node e.g. disk usage, or cpu usage and
2015-01-24 02:33:53 +01:00
notify the health of the entire node to the cluster .
Service level checks do not require a check name or id as these are derived
2015-07-17 07:19:21 +02:00
by Consul from the Service name and id respectively by appending ' service: '
Node level checks require a check_name and optionally a check_id . "
- Currently , there is no complete way to retrieve the script , interval or ttl
2015-04-26 23:27:53 +02:00
metadata for a registered check . Without this metadata it is not possible to
2015-07-17 07:19:21 +02:00
tell if the data supplied with ansible represents a change to a check . As a
result this does not attempt to determine changes and will always report a
2015-04-26 23:27:53 +02:00
changed occurred . An api method is planned to supply this metadata so at that
stage change management will be added .
2015-07-17 07:19:21 +02:00
- " See http://consul.io for more details. "
2015-04-27 14:40:21 +02:00
requirements :
2015-05-11 22:25:50 +02:00
- " python >= 2.6 "
2015-04-27 14:40:21 +02:00
- python - consul
- requests
2015-05-28 16:04:58 +02:00
version_added : " 2.0 "
2015-07-17 07:19:21 +02:00
author : " Steve Gargan (@sgargan) "
2015-01-24 02:33:53 +01:00
options :
state :
description :
- register or deregister the consul service , defaults to present
required : true
choices : [ ' present ' , ' absent ' ]
2015-04-26 23:27:53 +02:00
service_name :
2015-07-17 07:19:21 +02:00
description :
2015-04-26 23:27:53 +02:00
- Unique name for the service on a node , must be unique per node ,
required if registering a service . May be ommitted if registering
a node level check
required : false
2015-01-24 02:33:53 +01:00
service_id :
description :
- the ID for the service , must be unique per node , defaults to the
2015-04-26 23:27:53 +02:00
service name if the service name is supplied
2015-01-24 02:33:53 +01:00
required : false
2015-04-26 23:27:53 +02:00
default : service_name if supplied
2015-01-24 02:33:53 +01:00
host :
description :
2015-04-26 23:27:53 +02:00
- host of the consul agent defaults to localhost
required : false
default : localhost
port :
description :
- the port on which the consul agent is running
2015-01-24 02:33:53 +01:00
required : false
2015-04-26 23:27:53 +02:00
default : 8500
2016-03-05 01:37:41 +01:00
scheme :
description :
- the protocol scheme on which the consul agent is running
required : false
default : http
2016-03-05 01:55:08 +01:00
version_added : " 2.1 "
2016-03-23 14:23:30 +01:00
validate_certs :
2016-03-05 01:37:41 +01:00
description :
- whether to verify the tls certificate of the consul agent
required : false
default : True
2016-03-05 01:55:08 +01:00
version_added : " 2.1 "
2015-01-24 02:33:53 +01:00
notes :
description :
- Notes to attach to check when registering it .
required : false
2015-04-26 23:27:53 +02:00
default : None
2015-01-24 02:33:53 +01:00
service_port :
description :
- the port on which the service is listening required for
2015-04-26 23:27:53 +02:00
registration of a service , i . e . if service_name or service_id is set
required : false
2016-04-25 09:58:07 +02:00
service_address :
description :
- the address on which the service is serving required for
registration of a service
required : false
2016-04-25 10:09:15 +02:00
default : localhost
version_added : " 2.1 "
2015-01-24 02:33:53 +01:00
tags :
description :
- a list of tags that will be attached to the service registration .
required : false
2015-04-26 23:27:53 +02:00
default : None
2015-01-24 02:33:53 +01:00
script :
description :
- the script / command that will be run periodically to check the health
2015-04-26 23:27:53 +02:00
of the service . Scripts require an interval and vise versa
2015-01-24 02:33:53 +01:00
required : false
2015-04-26 23:27:53 +02:00
default : None
2015-01-24 02:33:53 +01:00
interval :
description :
2015-04-26 23:27:53 +02:00
- the interval at which the service check will be run . This is a number
2015-07-17 07:19:21 +02:00
with a s or m suffix to signify the units of seconds or minutes e . g
15 s or 1 m . If no suffix is supplied , m will be used by default e . g .
2015-04-26 23:27:53 +02:00
1 will be 1 m . Required if the script param is specified .
required : false
2015-07-17 07:19:21 +02:00
default : None
2015-01-24 02:33:53 +01:00
check_id :
description :
- an ID for the service check , defaults to the check name , ignored if
2015-04-26 23:27:53 +02:00
part of a service definition .
required : false
default : None
2015-01-24 02:33:53 +01:00
check_name :
description :
- a name for the service check , defaults to the check id . required if
standalone , ignored if part of service definition .
2015-04-26 23:27:53 +02:00
required : false
default : None
ttl :
2015-07-17 07:19:21 +02:00
description :
2015-04-26 23:27:53 +02:00
- checks can be registered with a ttl instead of a script and interval
this means that the service will check in with the agent before the
2015-07-17 07:19:21 +02:00
ttl expires . If it doesn ' t the check will be considered failed.
2015-04-26 23:27:53 +02:00
Required if registering a check and the script an interval are missing
2015-07-17 07:19:21 +02:00
Similar to the interval this is a number with a s or m suffix to
signify the units of seconds or minutes e . g 15 s or 1 m . If no suffix
2015-04-26 23:27:53 +02:00
is supplied , m will be used by default e . g . 1 will be 1 m
required : false
default : None
2015-08-16 17:55:10 +02:00
http :
description :
- checks can be registered with an http endpoint . This means that consul
will check that the http endpoint returns a successful http status .
Interval must also be provided with this option .
required : false
default : None
2015-10-14 17:06:29 +02:00
version_added : " 2.0 "
2015-08-16 17:55:10 +02:00
timeout :
description :
- A custom HTTP check timeout . The consul default is 10 seconds .
Similar to the interval this is a number with a s or m suffix to
signify the units of seconds or minutes , e . g . 15 s or 1 m .
required : false
default : None
2015-10-14 17:06:29 +02:00
version_added : " 2.0 "
2015-04-26 23:27:53 +02:00
token :
description :
2015-07-17 07:19:21 +02:00
- the token key indentifying an ACL rule set . May be required to register services .
2015-04-26 23:27:53 +02:00
required : false
default : None
2015-01-24 02:33:53 +01:00
"""
EXAMPLES = '''
- name : register nginx service with the local consul agent
consul :
2015-10-13 00:20:01 +02:00
service_name : nginx
2015-04-26 23:27:53 +02:00
service_port : 80
2015-01-24 02:33:53 +01:00
- name : register nginx service with curl check
consul :
2015-10-13 00:20:01 +02:00
service_name : nginx
2015-04-26 23:27:53 +02:00
service_port : 80
2015-01-24 02:33:53 +01:00
script : " curl http://localhost "
interval : 60 s
2015-08-16 17:55:10 +02:00
- name : register nginx with an http check
consul :
name : nginx
service_port : 80
interval : 60 s
http : / status
2016-04-25 09:58:07 +02:00
- name : register nginx with address
consul :
service_name : nginx
service_port : 80
service_address : 127.0 .0 .1
2016-04-25 10:09:15 +02:00
2015-01-24 02:33:53 +01:00
- name : register nginx with some service tags
consul :
2015-10-13 00:20:01 +02:00
service_name : nginx
2015-04-26 23:27:53 +02:00
service_port : 80
2015-01-24 02:33:53 +01:00
tags :
- prod
- webservers
- name : remove nginx service
consul :
2015-10-13 00:20:01 +02:00
service_name : nginx
2015-01-24 02:33:53 +01:00
state : absent
- name : create a node level check to test disk usage
consul :
check_name : Disk usage
check_id : disk_usage
script : " /opt/disk_usage.py "
interval : 5 m
'''
try :
import consul
2015-04-27 14:40:21 +02:00
from requests . exceptions import ConnectionError
python_consul_installed = True
2015-01-24 02:33:53 +01:00
except ImportError , e :
2015-04-27 14:40:21 +02:00
python_consul_installed = False
2015-07-21 08:02:44 +02:00
2015-01-24 02:33:53 +01:00
def register_with_consul ( module ) :
state = module . params . get ( ' state ' )
if state == ' present ' :
add ( module )
else :
remove ( module )
def add ( module ) :
''' adds a service or a check depending on supplied configuration '''
check = parse_check ( module )
service = parse_service ( module )
if not service and not check :
module . fail_json ( msg = ' a name and port are required to register a service ' )
if service :
if check :
service . add_check ( check )
add_service ( module , service )
elif check :
add_check ( module , check )
def remove ( module ) :
''' removes a service or a check '''
service_id = module . params . get ( ' service_id ' ) or module . params . get ( ' service_name ' )
check_id = module . params . get ( ' check_id ' ) or module . params . get ( ' check_name ' )
if not ( service_id or check_id ) :
2015-10-14 17:06:29 +02:00
module . fail_json ( msg = ' services and checks are removed by id or name. please supply a service id/name or a check id/name ' )
2015-01-24 02:33:53 +01:00
if service_id :
remove_service ( module , service_id )
else :
remove_check ( module , check_id )
def add_check ( module , check ) :
''' registers a check with the given agent. currently there is no way
retrieve the full metadata of an existing check through the consul api .
Without this we can ' t compare to the supplied check and so we must assume
a change . '''
if not check . name :
2015-10-14 17:06:29 +02:00
module . fail_json ( msg = ' a check name is required for a node level check, one not attached to a service ' )
2015-01-24 02:33:53 +01:00
consul_api = get_consul_api ( module )
check . register ( consul_api )
module . exit_json ( changed = True ,
check_id = check . check_id ,
check_name = check . name ,
script = check . script ,
interval = check . interval ,
2015-08-16 17:55:10 +02:00
ttl = check . ttl ,
http = check . http ,
timeout = check . timeout )
2015-01-24 02:33:53 +01:00
def remove_check ( module , check_id ) :
''' removes a check using its id '''
consul_api = get_consul_api ( module )
if check_id in consul_api . agent . checks ( ) :
consul_api . agent . check . deregister ( check_id )
module . exit_json ( changed = True , id = check_id )
module . exit_json ( changed = False , id = check_id )
def add_service ( module , service ) :
''' registers a service with the the current agent '''
result = service
changed = False
consul_api = get_consul_api ( module )
existing = get_service_by_id ( consul_api , service . id )
2016-04-25 10:09:15 +02:00
# there is no way to retrieve the details of checks so if a check is present
# in the service it must be re-registered
2015-03-03 15:18:56 +01:00
if service . has_checks ( ) or not existing or not existing == service :
2015-01-24 02:33:53 +01:00
service . register ( consul_api )
# check that it registered correctly
registered = get_service_by_id ( consul_api , service . id )
if registered :
result = registered
changed = True
module . exit_json ( changed = changed ,
service_id = result . id ,
service_name = result . name ,
service_port = result . port ,
checks = map ( lambda x : x . to_dict ( ) , service . checks ) ,
tags = result . tags )
def remove_service ( module , service_id ) :
''' deregister a service from the given agent using its service id '''
consul_api = get_consul_api ( module )
service = get_service_by_id ( consul_api , service_id )
if service :
consul_api . agent . service . deregister ( service_id )
module . exit_json ( changed = True , id = service_id )
module . exit_json ( changed = False , id = service_id )
def get_consul_api ( module , token = None ) :
return consul . Consul ( host = module . params . get ( ' host ' ) ,
port = module . params . get ( ' port ' ) ,
2016-03-05 01:37:41 +01:00
scheme = module . params . get ( ' scheme ' ) ,
2016-05-27 15:46:56 +02:00
verify = module . params . get ( ' validate_certs ' ) ,
2015-01-24 02:33:53 +01:00
token = module . params . get ( ' token ' ) )
def get_service_by_id ( consul_api , service_id ) :
''' iterate the registered services and find one with the given id '''
for name , service in consul_api . agent . services ( ) . iteritems ( ) :
if service [ ' ID ' ] == service_id :
return ConsulService ( loaded = service )
def parse_check ( module ) :
2015-08-16 17:55:10 +02:00
if len ( filter ( None , [ module . params . get ( ' script ' ) , module . params . get ( ' ttl ' ) , module . params . get ( ' http ' ) ] ) ) > 1 :
2015-01-24 02:33:53 +01:00
module . fail_json (
2015-10-14 17:06:29 +02:00
msg = ' check are either script, http or ttl driven, supplying more than one does not make sense ' )
2015-01-24 02:33:53 +01:00
2015-08-16 17:55:10 +02:00
if module . params . get ( ' check_id ' ) or module . params . get ( ' script ' ) or module . params . get ( ' ttl ' ) or module . params . get ( ' http ' ) :
2015-01-24 02:33:53 +01:00
return ConsulCheck (
module . params . get ( ' check_id ' ) ,
module . params . get ( ' check_name ' ) ,
module . params . get ( ' check_node ' ) ,
module . params . get ( ' check_host ' ) ,
module . params . get ( ' script ' ) ,
module . params . get ( ' interval ' ) ,
module . params . get ( ' ttl ' ) ,
2015-08-16 17:55:10 +02:00
module . params . get ( ' notes ' ) ,
module . params . get ( ' http ' ) ,
module . params . get ( ' timeout ' )
2015-01-24 02:33:53 +01:00
)
def parse_service ( module ) :
if module . params . get ( ' service_name ' ) and module . params . get ( ' service_port ' ) :
return ConsulService (
module . params . get ( ' service_id ' ) ,
module . params . get ( ' service_name ' ) ,
2016-04-25 09:58:07 +02:00
module . params . get ( ' service_address ' ) ,
2015-01-24 02:33:53 +01:00
module . params . get ( ' service_port ' ) ,
module . params . get ( ' tags ' ) ,
)
elif module . params . get ( ' service_name ' ) and not module . params . get ( ' service_port ' ) :
2015-10-14 17:06:29 +02:00
module . fail_json ( msg = " service_name supplied but no service_port, a port is required to configure a service. Did you configure the ' port ' argument meaning ' service_port ' ? " )
2015-01-24 02:33:53 +01:00
2016-04-25 09:58:07 +02:00
class ConsulService ( ) :
2015-01-24 02:33:53 +01:00
2016-04-25 09:58:07 +02:00
def __init__ ( self , service_id = None , name = None , address = None , port = - 1 ,
2015-01-24 02:33:53 +01:00
tags = None , loaded = None ) :
self . id = self . name = name
if service_id :
self . id = service_id
2016-04-25 09:58:07 +02:00
self . address = address
2015-01-24 02:33:53 +01:00
self . port = port
self . tags = tags
self . checks = [ ]
if loaded :
self . id = loaded [ ' ID ' ]
self . name = loaded [ ' Service ' ]
self . port = loaded [ ' Port ' ]
self . tags = loaded [ ' Tags ' ]
def register ( self , consul_api ) :
if len ( self . checks ) > 0 :
check = self . checks [ 0 ]
2015-08-16 17:55:10 +02:00
2015-01-24 02:33:53 +01:00
consul_api . agent . service . register (
self . name ,
service_id = self . id ,
2016-04-25 09:58:07 +02:00
address = self . address ,
2015-01-24 02:33:53 +01:00
port = self . port ,
tags = self . tags ,
2015-08-16 17:55:10 +02:00
check = check . check )
2015-01-24 02:33:53 +01:00
else :
consul_api . agent . service . register (
self . name ,
service_id = self . id ,
2016-04-25 09:58:07 +02:00
address = self . address ,
2015-01-24 02:33:53 +01:00
port = self . port ,
tags = self . tags )
def add_check ( self , check ) :
self . checks . append ( check )
def checks ( self ) :
return self . checks
def has_checks ( self ) :
return len ( self . checks ) > 0
def __eq__ ( self , other ) :
return ( isinstance ( other , self . __class__ )
and self . id == other . id
and self . name == other . name
and self . port == other . port
and self . tags == other . tags )
def __ne__ ( self , other ) :
return not self . __eq__ ( other )
def to_dict ( self ) :
data = { ' id ' : self . id , " name " : self . name }
if self . port :
data [ ' port ' ] = self . port
if self . tags and len ( self . tags ) > 0 :
data [ ' tags ' ] = self . tags
if len ( self . checks ) > 0 :
data [ ' check ' ] = self . checks [ 0 ] . to_dict ( )
return data
class ConsulCheck ( ) :
def __init__ ( self , check_id , name , node = None , host = ' localhost ' ,
2015-08-16 17:55:10 +02:00
script = None , interval = None , ttl = None , notes = None , http = None , timeout = None ) :
2015-01-24 02:33:53 +01:00
self . check_id = self . name = name
if check_id :
self . check_id = check_id
self . notes = notes
self . node = node
self . host = host
2015-08-16 17:55:10 +02:00
self . interval = self . validate_duration ( ' interval ' , interval )
self . ttl = self . validate_duration ( ' ttl ' , ttl )
self . script = script
self . http = http
self . timeout = self . validate_duration ( ' timeout ' , timeout )
self . check = None
if script :
self . check = consul . Check . script ( script , self . interval )
if ttl :
self . check = consul . Check . ttl ( self . ttl )
if http :
2016-04-25 10:09:15 +02:00
if interval is None :
2015-08-16 17:55:10 +02:00
raise Exception ( ' http check must specify interval ' )
self . check = consul . Check . http ( http , self . interval , self . timeout )
2015-10-14 17:06:29 +02:00
2015-01-24 02:33:53 +01:00
2015-03-03 21:03:46 +01:00
def validate_duration ( self , name , duration ) :
if duration :
duration_units = [ ' ns ' , ' us ' , ' ms ' , ' s ' , ' m ' , ' h ' ]
if not any ( ( duration . endswith ( suffix ) for suffix in duration_units ) ) :
raise Exception ( ' Invalid %s %s you must specify units ( %s ) ' %
( name , duration , ' , ' . join ( duration_units ) ) )
return duration
2015-01-24 02:33:53 +01:00
def register ( self , consul_api ) :
consul_api . agent . check . register ( self . name , check_id = self . check_id ,
2015-08-16 17:55:10 +02:00
notes = self . notes ,
check = self . check )
2015-01-24 02:33:53 +01:00
def __eq__ ( self , other ) :
return ( isinstance ( other , self . __class__ )
and self . check_id == other . check_id
and self . name == other . name
and self . script == script
and self . interval == interval )
def __ne__ ( self , other ) :
return not self . __eq__ ( other )
def to_dict ( self ) :
data = { }
self . _add ( data , ' id ' , attr = ' check_id ' )
self . _add ( data , ' name ' , attr = ' check_name ' )
self . _add ( data , ' script ' )
self . _add ( data , ' node ' )
self . _add ( data , ' notes ' )
self . _add ( data , ' host ' )
self . _add ( data , ' interval ' )
self . _add ( data , ' ttl ' )
2015-08-16 17:55:10 +02:00
self . _add ( data , ' http ' )
self . _add ( data , ' timeout ' )
2015-01-24 02:33:53 +01:00
return data
def _add ( self , data , key , attr = None ) :
try :
2016-04-25 10:09:15 +02:00
if attr is None :
2015-01-24 02:33:53 +01:00
attr = key
data [ key ] = getattr ( self , attr )
except :
pass
2015-04-27 14:40:21 +02:00
def test_dependencies ( module ) :
if not python_consul_installed :
2015-10-14 17:06:29 +02:00
module . fail_json ( msg = " python-consul required for this module. see http://python-consul.readthedocs.org/en/latest/#installation " )
2015-01-24 02:33:53 +01:00
def main ( ) :
module = AnsibleModule (
argument_spec = dict (
2015-04-26 23:27:53 +02:00
host = dict ( default = ' localhost ' ) ,
port = dict ( default = 8500 , type = ' int ' ) ,
2016-03-05 01:37:41 +01:00
scheme = dict ( required = False , default = ' http ' ) ,
2016-03-23 14:23:30 +01:00
validate_certs = dict ( required = False , default = True , type = ' bool ' ) ,
2015-01-24 02:33:53 +01:00
check_id = dict ( required = False ) ,
check_name = dict ( required = False ) ,
check_node = dict ( required = False ) ,
check_host = dict ( required = False ) ,
notes = dict ( required = False ) ,
script = dict ( required = False ) ,
service_id = dict ( required = False ) ,
service_name = dict ( required = False ) ,
2016-04-25 09:58:07 +02:00
service_address = dict ( required = False , type = ' str ' , default = ' localhost ' ) ,
2015-01-24 02:33:53 +01:00
service_port = dict ( required = False , type = ' int ' ) ,
state = dict ( default = ' present ' , choices = [ ' present ' , ' absent ' ] ) ,
2015-04-26 23:27:53 +02:00
interval = dict ( required = False , type = ' str ' ) ,
ttl = dict ( required = False , type = ' str ' ) ,
2015-08-16 17:55:10 +02:00
http = dict ( required = False , type = ' str ' ) ,
timeout = dict ( required = False , type = ' str ' ) ,
2015-01-24 02:33:53 +01:00
tags = dict ( required = False , type = ' list ' ) ,
2015-12-18 05:32:05 +01:00
token = dict ( required = False , no_log = True )
2015-01-24 02:33:53 +01:00
) ,
supports_check_mode = False ,
)
2015-10-14 17:06:29 +02:00
2015-04-27 14:40:21 +02:00
test_dependencies ( module )
2015-10-14 17:06:29 +02:00
2015-01-24 02:33:53 +01:00
try :
register_with_consul ( module )
2015-03-16 17:50:53 +01:00
except ConnectionError , e :
module . fail_json ( msg = ' Could not connect to consul agent at %s : %s , error was %s ' % (
module . params . get ( ' host ' ) , module . params . get ( ' port ' ) , str ( e ) ) )
except Exception , e :
module . fail_json ( msg = str ( e ) )
2015-01-24 02:33:53 +01:00
# import module snippets
from ansible . module_utils . basic import *
2015-07-21 08:02:44 +02:00
if __name__ == ' __main__ ' :
main ( )