summaryrefslogtreecommitdiffstats
path: root/ansible_collections/community/general/plugins/modules/vertica_configuration.py
blob: 09b80df3d7a401475d88aa48a7b52b336dd90105 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later

from __future__ import absolute_import, division, print_function
__metaclass__ = type


DOCUMENTATION = '''
---
module: vertica_configuration
short_description: Updates Vertica configuration parameters
description:
    - Updates Vertica configuration parameters.
extends_documentation_fragment:
    - community.general.attributes
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
options:
  parameter:
    description:
        - Name of the parameter to update.
    required: true
    aliases: [name]
    type: str
  value:
    description:
        - Value of the parameter to be set.
    type: str
  db:
    description:
        - Name of the Vertica database.
    type: str
  cluster:
    description:
        - Name of the Vertica cluster.
    default: localhost
    type: str
  port:
    description:
        - Vertica cluster port to connect to.
    default: '5433'
    type: str
  login_user:
    description:
        - The username used to authenticate with.
    default: dbadmin
    type: str
  login_password:
    description:
        - The password used to authenticate with.
    type: str
notes:
  - The default authentication assumes that you are either logging in as or sudo'ing
    to the C(dbadmin) account on the host.
  - This module uses C(pyodbc), a Python ODBC database adapter. You must ensure
    that C(unixODBC) and C(pyodbc) is installed on the host and properly configured.
  - Configuring C(unixODBC) for Vertica requires C(Driver = /opt/vertica/lib64/libverticaodbc.so)
    to be added to the C(Vertica) section of either C(/etc/odbcinst.ini) or C($HOME/.odbcinst.ini)
    and both C(ErrorMessagesPath = /opt/vertica/lib64) and C(DriverManagerEncoding = UTF-16)
    to be added to the C(Driver) section of either C(/etc/vertica.ini) or C($HOME/.vertica.ini).
requirements: [ 'unixODBC', 'pyodbc' ]
author: "Dariusz Owczarek (@dareko)"
'''

EXAMPLES = """
- name: Updating load_balance_policy
  community.general.vertica_configuration: name=failovertostandbyafter value='8 hours'
"""
import traceback

PYODBC_IMP_ERR = None
try:
    import pyodbc
except ImportError:
    PYODBC_IMP_ERR = traceback.format_exc()
    pyodbc_found = False
else:
    pyodbc_found = True

from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.text.converters import to_native


class NotSupportedError(Exception):
    pass


class CannotDropError(Exception):
    pass

# module specific functions


def get_configuration_facts(cursor, parameter_name=''):
    facts = {}
    cursor.execute("""
        select c.parameter_name, c.current_value, c.default_value
        from configuration_parameters c
        where c.node_name = 'ALL'
        and (? = '' or c.parameter_name ilike ?)
    """, parameter_name, parameter_name)
    while True:
        rows = cursor.fetchmany(100)
        if not rows:
            break
        for row in rows:
            facts[row.parameter_name.lower()] = {
                'parameter_name': row.parameter_name,
                'current_value': row.current_value,
                'default_value': row.default_value}
    return facts


def check(configuration_facts, parameter_name, current_value):
    parameter_key = parameter_name.lower()
    if current_value and current_value.lower() != configuration_facts[parameter_key]['current_value'].lower():
        return False
    return True


def present(configuration_facts, cursor, parameter_name, current_value):
    parameter_key = parameter_name.lower()
    changed = False
    if current_value and current_value.lower() != configuration_facts[parameter_key]['current_value'].lower():
        cursor.execute("select set_config_parameter('{0}', '{1}')".format(parameter_name, current_value))
        changed = True
    if changed:
        configuration_facts.update(get_configuration_facts(cursor, parameter_name))
    return changed

# module logic


def main():

    module = AnsibleModule(
        argument_spec=dict(
            parameter=dict(required=True, aliases=['name']),
            value=dict(default=None),
            db=dict(default=None),
            cluster=dict(default='localhost'),
            port=dict(default='5433'),
            login_user=dict(default='dbadmin'),
            login_password=dict(default=None, no_log=True),
        ), supports_check_mode=True)

    if not pyodbc_found:
        module.fail_json(msg=missing_required_lib('pyodbc'), exception=PYODBC_IMP_ERR)

    parameter_name = module.params['parameter']
    current_value = module.params['value']
    db = ''
    if module.params['db']:
        db = module.params['db']

    changed = False

    try:
        dsn = (
            "Driver=Vertica;"
            "Server={0};"
            "Port={1};"
            "Database={2};"
            "User={3};"
            "Password={4};"
            "ConnectionLoadBalance={5}"
        ).format(module.params['cluster'], module.params['port'], db,
                 module.params['login_user'], module.params['login_password'], 'true')
        db_conn = pyodbc.connect(dsn, autocommit=True)
        cursor = db_conn.cursor()
    except Exception as e:
        module.fail_json(msg="Unable to connect to database: {0}.".format(to_native(e)),
                         exception=traceback.format_exc())

    try:
        configuration_facts = get_configuration_facts(cursor)
        if module.check_mode:
            changed = not check(configuration_facts, parameter_name, current_value)
        else:
            try:
                changed = present(configuration_facts, cursor, parameter_name, current_value)
            except pyodbc.Error as e:
                module.fail_json(msg=to_native(e), exception=traceback.format_exc())
    except NotSupportedError as e:
        module.fail_json(msg=to_native(e), ansible_facts={'vertica_configuration': configuration_facts})
    except CannotDropError as e:
        module.fail_json(msg=to_native(e), ansible_facts={'vertica_configuration': configuration_facts})
    except SystemExit:
        # avoid catching this on python 2.4
        raise
    except Exception as e:
        module.fail_json(msg=to_native(e), exception=traceback.format_exc())

    module.exit_json(changed=changed, parameter=parameter_name, ansible_facts={'vertica_configuration': configuration_facts})


if __name__ == '__main__':
    main()