Repository: ansible/ansible

Issue:
Ansible 2.3 Datadog module: No handlers could be found for logger dd.datadogpy
##### ISSUE TYPE
Bug Report

##### COMPONENT NAME
datadog module

##### ANSIBLE VERSION
2.3

##### SUMMARY
We assume there is an issue with Ansible 2.3 Datadog module.

After upgrade of Ansible to 2.3 and Python to 2.7.12 we have faced following issue when using Datadog module. Googling around does not really help. 

TASK [datadog-monitor : Module name] ***************************************************************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "module_stderr": "No handlers could be found for logger \"dd.datadogpy\"\nTraceback (most recent call last):\n  File \"/tmp/ansible_2Gi1Dz/ansible_module_datadog_monitor.py\", line 343, in <module>\n    main()\n  File \"/tmp/ansible_2Gi1Dz/ansible_module_datadog_monitor.py\", line 202, in main\n    install_monitor(module)\n  File \"/tmp/ansible_2Gi1Dz/ansible_module_datadog_monitor.py\", line 289, in install_monitor\n    monitor = _get_monitor(module)\n  File \"/tmp/ansible_2Gi1Dz/ansible_module_datadog_monitor.py\", line 225, in _get_monitor\n    if monitor['name'] == module.params['name']:\nTypeError: string indices must be integers, not str\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 0}

---------

ansible --version
ansible 2.3.0.0
  config file = <pass to folder>/ansible/ansible.cfg
  configured module search path = [u'library']
  python version = 2.7.12 (default, Jul 18 2016, 15:02:52) [GCC 4.8.4]

OS: Ubuntu




Discussion:
@vanomashey Greetings! Thanks for taking the time to open this issue. In order for the community to handle your issue effectively, we need a bit more information. 

Here are the items we could not find in your description:
- issue type
- ansible version
- component name

Please set the description of this issue with this template:
https://raw.githubusercontent.com/ansible/ansible/devel/.github/ISSUE_TEMPLATE.md

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: issue_missing_data --->
@vanomashey Thanks for reporting this issue. Could you please provide your Ansible playbook sample ? 
Hi @Akasurde,

Thank you for prompt reply.

This is my yml file:

```
# Install Datadog Monitors
- hosts: localhost
  connection: local
  roles:
    - { role: datadog-monitor, tags: ['datadog-monitor'] }
```

And this is a datadog-monitor role: 

```
- name: Create Datadog Server can connect
  datadog_monitor:
    type: "service check"
    name: "Masters can connect"
    state: "present"
    notify_no_data: true
    no_data_timeframe: 30
    query: '"mesos_master.can_connect".over("type:dcos").last(4).count_by_status()'
    message: "Mesos Masters"
    api_key: "{{ dd_api_key }}"
    app_key: "{{ dd_app_key }}"
  tags:
    - mesos
```


@vanomashey Are you sure that you are using correct `api_key` and `app_key` ? I am able to run given playbook with my `api_key` and `app_key`. Can you paste output of following script ?

```
from datadog import initialize, api
options = {
    'api_key': 'abcdefghijklmnop',
    'app_key': 'abcdefghijklmnop'
}

initialize(**options)
print api.Monitor.get_all()
```

Resolving patch:
diff --git a/lib/ansible/modules/monitoring/datadog_monitor.py b/lib/ansible/modules/monitoring/datadog_monitor.py
--- a/lib/ansible/modules/monitoring/datadog_monitor.py
+++ b/lib/ansible/modules/monitoring/datadog_monitor.py
@@ -210,6 +210,14 @@ def main():
 
     initialize(**options)
 
+    # Check if api_key and app_key is correct or not
+    # if not, then fail here.
+    response = api.Monitor.get_all()
+    if isinstance(response, dict):
+        msg = response.get('errors', None)
+        if msg:
+            module.fail_json(msg="Failed to connect Datadog server using given app_key and api_key : {0}".format(msg[0]))
+
     if module.params['state'] == 'present':
         install_monitor(module)
     elif module.params['state'] == 'absent':
@@ -219,6 +227,7 @@ def main():
     elif module.params['state'] == 'unmute':
         unmute_monitor(module)
 
+
 def _fix_template_vars(message):
     if message:
         return message.replace('[[', '{{').replace(']]', '}}')
@@ -255,11 +264,13 @@ def _post_monitor(module, options):
         e = get_exception()
         module.fail_json(msg=str(e))
 
+
 def _equal_dicts(a, b, ignore_keys):
     ka = set(a).difference(ignore_keys)
     kb = set(b).difference(ignore_keys)
     return ka == kb and all(a[k] == b[k] for k in ka)
 
+
 def _update_monitor(module, monitor, options):
     try:
         kwargs = dict(id=monitor['id'], query=module.params['query'],
@@ -290,7 +301,7 @@ def install_monitor(module):
         "escalation_message": module.params['escalation_message'],
         "notify_audit": module.boolean(module.params['notify_audit']),
         "locked": module.boolean(module.params['locked']),
-        "require_full_window" : module.params['require_full_window']
+        "require_full_window": module.params['require_full_window']
     }
 
     if module.params['type'] == "service check":
@@ -323,8 +334,7 @@ def mute_monitor(module):
         module.fail_json(msg="Monitor %s not found!" % module.params['name'])
     elif monitor['options']['silenced']:
         module.fail_json(msg="Monitor is already muted. Datadog does not allow to modify muted alerts, consider unmuting it first.")
-    elif (module.params['silenced'] is not None
-         and len(set(monitor['options']['silenced']) - set(module.params['silenced'])) == 0):
+    elif (module.params['silenced'] is not None and len(set(monitor['options']['silenced']) - set(module.params['silenced'])) == 0):
         module.exit_json(changed=False)
     try:
         if module.params['silenced'] is None or module.params['silenced'] == "":


Test patch:
diff --git a/test/sanity/pep8/legacy-files.txt b/test/sanity/pep8/legacy-files.txt
--- a/test/sanity/pep8/legacy-files.txt
+++ b/test/sanity/pep8/legacy-files.txt
@@ -426,7 +426,6 @@ lib/ansible/modules/monitoring/bigpanda.py
 lib/ansible/modules/monitoring/boundary_meter.py
 lib/ansible/modules/monitoring/circonus_annotation.py
 lib/ansible/modules/monitoring/datadog_event.py
-lib/ansible/modules/monitoring/datadog_monitor.py
 lib/ansible/modules/monitoring/honeybadger_deployment.py
 lib/ansible/modules/monitoring/icinga2_feature.py
 lib/ansible/modules/monitoring/librato_annotation.py