| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2022-2026 The Project Contributors. |
| 4 |
# |
| 5 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
# you may not use this file except in compliance with the License. |
| 7 |
# You may obtain a copy of the License at |
| 8 |
# |
| 9 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
# |
| 11 |
# Unless required by applicable law or agreed to in writing, software |
| 12 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 |
# See the License for the specific language governing permissions and |
| 15 |
# limitations under the License. |
| 16 |
# |
| 17 |
# For a detailed list of copyright holders and contribution history, |
| 18 |
# please refer to the CONTRIBUTORS.md file in the project root. |
| 19 |
|
| 20 |
from __future__ import (absolute_import, division, print_function) |
| 21 |
__metaclass__ = type |
| 22 |
|
| 23 |
DOCUMENTATION = r''' |
| 24 |
--- |
| 25 |
module: sap_hdbsql |
| 26 |
short_description: Ansible Module to execute SQL on SAP HANA |
| 27 |
version_added: "1.0.0" |
| 28 |
description: This module executes SQL statements on HANA with hdbsql. |
| 29 |
options: |
| 30 |
sid: |
| 31 |
description: The system ID. |
| 32 |
type: str |
| 33 |
required: false |
| 34 |
bin_path: |
| 35 |
description: The path to the hdbsql binary. |
| 36 |
type: str |
| 37 |
required: false |
| 38 |
instance: |
| 39 |
description: The instance number. |
| 40 |
type: str |
| 41 |
required: true |
| 42 |
user: |
| 43 |
description: A dedicated username. The user could be also in hdbuserstore. |
| 44 |
type: str |
| 45 |
default: SYSTEM |
| 46 |
userstore: |
| 47 |
description: If C(true), the user must be in hdbuserstore. |
| 48 |
type: bool |
| 49 |
default: false |
| 50 |
password: |
| 51 |
description: |
| 52 |
- The password to connect to the database. |
| 53 |
- "B(Note:) Since the passwords have to be passed as command line arguments, I(userstore=true) should |
| 54 |
be used whenever possible, as command line arguments can be seen by other users |
| 55 |
on the same machine." |
| 56 |
type: str |
| 57 |
autocommit: |
| 58 |
description: Autocommit the statement. |
| 59 |
type: bool |
| 60 |
default: true |
| 61 |
host: |
| 62 |
description: The Host IP address. The port can be defined as well. |
| 63 |
type: str |
| 64 |
database: |
| 65 |
description: Define the database on which to connect. |
| 66 |
type: str |
| 67 |
encrypted: |
| 68 |
description: Use encrypted connection. |
| 69 |
type: bool |
| 70 |
default: false |
| 71 |
properties: |
| 72 |
description: |
| 73 |
- Sets SQLDBC connect options e.g. sqlMode=SAPR3 |
| 74 |
- Must be a string or list containing strings. |
| 75 |
- See SAP HANA documentation for list of available options. |
| 76 |
type: list |
| 77 |
elements: str |
| 78 |
filepath: |
| 79 |
description: |
| 80 |
- One or more files each containing one SQL query to run. |
| 81 |
- Must be a string or list containing strings. |
| 82 |
type: list |
| 83 |
elements: path |
| 84 |
query: |
| 85 |
description: |
| 86 |
- SQL query to run. |
| 87 |
- Must be a string or list containing strings. Please note that if you supply a string, it will be split by commas (C(,)) to a list. |
| 88 |
It is better to supply a one-element list instead to avoid mangled input. |
| 89 |
type: list |
| 90 |
elements: str |
| 91 |
notes: |
| 92 |
- Does not support C(check_mode). |
| 93 |
- If filepath is used, changed is true. If query is used, changed is true if it is not a SELECT. |
| 94 |
- Avoid using login shell flags (like 'become_flags' with value of '-i') when become_user is a SAP admin. |
| 95 |
- If a login shell is required, manually reset the environment in the task using the environment keyword. |
| 96 |
author: |
| 97 |
- Rainer Leber (@rainerleber) |
| 98 |
''' |
| 99 |
|
| 100 |
EXAMPLES = r''' |
| 101 |
- name: Simple select query |
| 102 |
community.sap_libs.sap_hdbsql: |
| 103 |
sid: "hdb" |
| 104 |
instance: "01" |
| 105 |
password: "Test123" |
| 106 |
query: select user_name from users |
| 107 |
|
| 108 |
- name: RUN select query with host port |
| 109 |
community.sap_libs.sap_hdbsql: |
| 110 |
sid: "hdb" |
| 111 |
instance: "01" |
| 112 |
password: "Test123" |
| 113 |
host: "10.10.2.4:30001" |
| 114 |
query: select user_name from users |
| 115 |
|
| 116 |
- name: Run several queries |
| 117 |
community.sap_libs.sap_hdbsql: |
| 118 |
sid: "hdb" |
| 119 |
instance: "01" |
| 120 |
password: "Test123" |
| 121 |
query: |
| 122 |
- select user_name from users |
| 123 |
- select * from SYSTEM |
| 124 |
host: "localhost" |
| 125 |
autocommit: False |
| 126 |
|
| 127 |
- name: Run several queries with path |
| 128 |
community.sap_libs.sap_hdbsql: |
| 129 |
bin_path: "/usr/sap/HDB/HDB01/exe/hdbsql" |
| 130 |
instance: "01" |
| 131 |
password: "Test123" |
| 132 |
query: |
| 133 |
- select user_name from users |
| 134 |
- select * from users |
| 135 |
host: "localhost" |
| 136 |
autocommit: False |
| 137 |
|
| 138 |
- name: Run several queries from file |
| 139 |
community.sap_libs.sap_hdbsql: |
| 140 |
sid: "hdb" |
| 141 |
instance: "01" |
| 142 |
password: "Test123" |
| 143 |
filepath: |
| 144 |
- /tmp/HANA_CPU_UtilizationPerCore_2.00.020+.txt |
| 145 |
- /tmp/HANA.txt |
| 146 |
host: "localhost" |
| 147 |
|
| 148 |
- name: Run several queries from user store |
| 149 |
community.sap_libs.sap_hdbsql: |
| 150 |
sid: "hdb" |
| 151 |
instance: "01" |
| 152 |
user: hdbstoreuser |
| 153 |
userstore: true |
| 154 |
query: |
| 155 |
- select user_name from users |
| 156 |
- select * from users |
| 157 |
autocommit: False |
| 158 |
|
| 159 |
- name: Run query with SQLDBC connect options |
| 160 |
community.sap_libs.sap_hdbsql: |
| 161 |
sid: "hdb" |
| 162 |
instance: "01" |
| 163 |
password: "Test123" |
| 164 |
query: select user_name from users |
| 165 |
properties: |
| 166 |
- "sqlMode=SAPR3" |
| 167 |
- "sslHostNameInCertificate=hana.example.com" |
| 168 |
''' |
| 169 |
|
| 170 |
RETURN = r''' |
| 171 |
query_result: |
| 172 |
description: List containing results of all queries executed (one sublist for every query). |
| 173 |
returned: on success |
| 174 |
type: list |
| 175 |
elements: list |
| 176 |
sample: [[{"Column": "Value1"}, {"Column": "Value2"}], [{"Column": "Value1"}, {"Column": "Value2"}]] |
| 177 |
''' |
| 178 |
|
| 179 |
import csv |
| 180 |
from ansible.module_utils.basic import AnsibleModule |
| 181 |
from io import StringIO |
| 182 |
from ansible.module_utils.common.text.converters import to_native |
| 183 |
|
| 184 |
|
| 185 |
def csv_to_list(raw_csv): |
| 186 |
if not raw_csv.strip(): |
| 187 |
return [] |
| 188 |
|
| 189 |
reader_raw = csv.DictReader(StringIO(raw_csv)) |
| 190 |
# Using to_native and strip to ensure clean dictionary keys/values |
| 191 |
reader = [dict((to_native(k), to_native(v).strip()) for k, v in row.items()) for row in reader_raw] |
| 192 |
return list(reader) |
| 193 |
|
| 194 |
|
| 195 |
def run_hdb_command(module, full_cmd): |
| 196 |
rc, out_raw, err = module.run_command(full_cmd) |
| 197 |
|
| 198 |
if rc != 0: |
| 199 |
err_msg = to_native(err).lower() |
| 200 |
|
| 201 |
if "authentication failed" in err_msg or "invalid username or password" in err_msg: |
| 202 |
module.fail_json(msg="SAP HANA Authentication Failed. Please check credentials/userstore.", rc=rc, stderr=err) |
| 203 |
|
| 204 |
elif "insufficient privilege" in err_msg or "258:" in err_msg: |
| 205 |
module.fail_json(msg="SAP HANA Authorization Error: The user has insufficient privileges to perform this action.", rc=rc, stderr=err) |
| 206 |
|
| 207 |
elif "connect failed" in err_msg: |
| 208 |
module.fail_json(msg="SAP HANA Connection Failed. Check host, instance, and port.", rc=rc, stderr=err) |
| 209 |
|
| 210 |
else: |
| 211 |
module.fail_json(msg="SQL Execution Error", rc=rc, stderr=err, cmd=full_cmd) |
| 212 |
|
| 213 |
return out_raw |
| 214 |
|
| 215 |
|
| 216 |
def main(): |
| 217 |
module = AnsibleModule( |
| 218 |
argument_spec=dict( |
| 219 |
sid=dict(type='str', required=False), |
| 220 |
bin_path=dict(type='str', required=False), |
| 221 |
instance=dict(type='str', required=True), |
| 222 |
encrypted=dict(type='bool', default=False), |
| 223 |
host=dict(type='str', required=False), |
| 224 |
user=dict(type='str', default="SYSTEM"), |
| 225 |
userstore=dict(type='bool', default=False), |
| 226 |
password=dict(type='str', no_log=True), |
| 227 |
database=dict(type='str', required=False), |
| 228 |
query=dict(type='list', elements='str', required=False), |
| 229 |
filepath=dict(type='list', elements='path', required=False), |
| 230 |
autocommit=dict(type='bool', default=True), |
| 231 |
properties=dict(type='list', elements='str', required=False), |
| 232 |
), |
| 233 |
required_one_of=[('query', 'filepath')], |
| 234 |
required_if=[('userstore', False, ['password'])], |
| 235 |
supports_check_mode=False, |
| 236 |
) |
| 237 |
|
| 238 |
params = module.params |
| 239 |
output = [] |
| 240 |
has_changed = False |
| 241 |
|
| 242 |
# Determine if module will show as changed. |
| 243 |
# If filepaths are provided, we assume changes will be made, as files typically contain DDL or DML statements. |
| 244 |
# If only queries are provided, we check if any of them are not SELECT statements. If at least one is not a SELECT, we assume changes will be made. |
| 245 |
if params['filepath']: |
| 246 |
has_changed = True |
| 247 |
|
| 248 |
elif params['query']: |
| 249 |
for q in params['query']: |
| 250 |
# Strip whitespace and check if it starts with SELECT |
| 251 |
if not q.strip().upper().startswith("SELECT"): |
| 252 |
has_changed = True |
| 253 |
break |
| 254 |
|
| 255 |
# Construct Binary Path |
| 256 |
bin_path = params['bin_path'] |
| 257 |
if bin_path is None: |
| 258 |
if not params['sid']: |
| 259 |
module.fail_json(msg="Parameter 'sid' is required to determine default bin_path if 'bin_path' is not provided.") |
| 260 |
|
| 261 |
bin_path = "/usr/sap/{sid}/HDB{instance}/exe/hdbsql".format( |
| 262 |
sid=params['sid'].upper(), |
| 263 |
instance=params['instance'] |
| 264 |
) |
| 265 |
|
| 266 |
try: |
| 267 |
command = [module.get_bin_path(bin_path, required=True)] |
| 268 |
except Exception as e: |
| 269 |
module.fail_json(msg='Executable binary hdbsql not found at {0}: {1}'.format(bin_path, to_native(e))) |
| 270 |
|
| 271 |
# Build Base Command |
| 272 |
if params['encrypted']: |
| 273 |
# -e: Enforce encryption (don't fall back) |
| 274 |
# -ssltrustcert: Trust the server certificate |
| 275 |
# -sslcreatecert: Create a local certificate if necessary |
| 276 |
command.extend(['-e', '-ssltrustcert', '-sslcreatecert']) |
| 277 |
|
| 278 |
if not params['autocommit']: |
| 279 |
command.extend(['-z']) |
| 280 |
|
| 281 |
if params['host']: |
| 282 |
command.extend(['-n', params['host']]) |
| 283 |
|
| 284 |
if params['database']: |
| 285 |
command.extend(['-d', params['database']]) |
| 286 |
|
| 287 |
if params['properties']: |
| 288 |
for prop in params['properties']: |
| 289 |
command.extend(['-Z', prop]) |
| 290 |
|
| 291 |
if params['userstore']: |
| 292 |
command.extend(['-x', '-U', params['user']]) |
| 293 |
|
| 294 |
else: |
| 295 |
command.extend(['-x', '-i', params['instance'], '-u', params['user'], '-p', params['password']]) |
| 296 |
|
| 297 |
# Process Queries |
| 298 |
if params['query']: |
| 299 |
for q in params['query']: |
| 300 |
query_command = command + [q] |
| 301 |
out_raw = run_hdb_command(module, query_command) |
| 302 |
try: |
| 303 |
output.append(csv_to_list(out_raw)) |
| 304 |
except Exception as e: |
| 305 |
module.fail_json(msg="Failed to parse CSV output: {0}".format(to_native(e))) |
| 306 |
|
| 307 |
# Process Files |
| 308 |
# Note: File processing adds extra arguments so it has to execute after query processing. |
| 309 |
if params['filepath']: |
| 310 |
for p in params['filepath']: |
| 311 |
file_query_command = command + ['-E', '3', '-I', p] |
| 312 |
out_raw = run_hdb_command(module, file_query_command) |
| 313 |
try: |
| 314 |
output.append(csv_to_list(out_raw)) |
| 315 |
except Exception as e: |
| 316 |
module.fail_json(msg="Failed to parse output from file {0}: {1}".format(p, to_native(e))) |
| 317 |
|
| 318 |
module.exit_json(changed=has_changed, query_result=output) |
| 319 |
|
| 320 |
|
| 321 |
if __name__ == '__main__': |
| 322 |
main() |