Debian Codegraph @

ansible_collections/community/general/plugins/modules/vertica_role.py

raw
1 #!/usr/bin/python
2
3 # Copyright Ansible Project
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: vertica_role
11 short_description: Adds or removes Vertica database roles and assigns roles to them
12 description:
13 - Adds or removes Vertica database role and, optionally, assign other roles.
14 extends_documentation_fragment:
15 - community.general._attributes
16 attributes:
17 check_mode:
18 support: full
19 diff_mode:
20 support: none
21 options:
22 role:
23 description:
24 - Name of the role to add or remove.
25 required: true
26 type: str
27 aliases: ['name']
28 assigned_roles:
29 description:
30 - Comma separated list of roles to assign to the role.
31 aliases: ['assigned_role']
32 type: str
33 state:
34 description:
35 - Whether to create V(present), drop V(absent) or lock V(locked) a role.
36 choices: ['present', 'absent']
37 default: present
38 type: str
39 db:
40 description:
41 - Name of the Vertica database.
42 type: str
43 cluster:
44 description:
45 - Name of the Vertica cluster.
46 default: localhost
47 type: str
48 port:
49 description:
50 - Vertica cluster port to connect to.
51 default: '5433'
52 type: str
53 login_user:
54 description:
55 - The username used to authenticate with.
56 default: dbadmin
57 type: str
58 login_password:
59 description:
60 - The password used to authenticate with.
61 type: str
62 notes:
63 - The default authentication assumes that you are either logging in as or sudo'ing to the C(dbadmin) account on the host.
64 - This module uses C(pyodbc), a Python ODBC database adapter. You must ensure that C(unixODBC) and C(pyodbc) is installed
65 on the host and properly configured.
66 - Configuring C(unixODBC) for Vertica requires C(Driver = /opt/vertica/lib64/libverticaodbc.so) to be added to the C(Vertica)
67 section of either C(/etc/odbcinst.ini) or C($HOME/.odbcinst.ini) and both C(ErrorMessagesPath = /opt/vertica/lib64) and
68 C(DriverManagerEncoding = UTF-16) to be added to the C(Driver) section of either C(/etc/vertica.ini) or C($HOME/.vertica.ini).
69 requirements: ['unixODBC', 'pyodbc']
70 author: "Dariusz Owczarek (@dareko)"
71 """
72
73 EXAMPLES = r"""
74 - name: Creating a new vertica role
75 community.general.vertica_role: name=role_name db=db_name state=present
76
77 - name: Creating a new vertica role with other role assigned
78 community.general.vertica_role: name=role_name assigned_role=other_role_name state=present
79 """
80 import traceback
81
82 PYODBC_IMP_ERR = None
83 try:
84 import pyodbc
85 except ImportError:
86 PYODBC_IMP_ERR = traceback.format_exc()
87 pyodbc_found = False
88 else:
89 pyodbc_found = True
90
91 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
92
93
94 class NotSupportedError(Exception):
95 pass
96
97
98 class CannotDropError(Exception):
99 pass
100
101
102 # module specific functions
103
104
105 def get_role_facts(cursor, role=""):
106 facts = {}
107 cursor.execute(
108 """
109 select r.name, r.assigned_roles
110 from roles r
111 where (? = '' or r.name ilike ?)
112 """,
113 role,
114 role,
115 )
116 while True:
117 rows = cursor.fetchmany(100)
118 if not rows:
119 break
120 for row in rows:
121 role_key = row.name.lower()
122 facts[role_key] = {"name": row.name, "assigned_roles": []}
123 if row.assigned_roles:
124 facts[role_key]["assigned_roles"] = row.assigned_roles.replace(" ", "").split(",")
125 return facts
126
127
128 def update_roles(role_facts, cursor, role, existing, required):
129 for assigned_role in set(existing) - set(required):
130 cursor.execute(f"revoke {assigned_role} from {role}")
131 for assigned_role in set(required) - set(existing):
132 cursor.execute(f"grant {assigned_role} to {role}")
133
134
135 def check(role_facts, role, assigned_roles):
136 role_key = role.lower()
137 if role_key not in role_facts:
138 return False
139 return not (assigned_roles and sorted(assigned_roles) != sorted(role_facts[role_key]["assigned_roles"]))
140
141
142 def present(role_facts, cursor, role, assigned_roles):
143 role_key = role.lower()
144 if role_key not in role_facts:
145 cursor.execute(f"create role {role}")
146 update_roles(role_facts, cursor, role, [], assigned_roles)
147 role_facts.update(get_role_facts(cursor, role))
148 return True
149 else:
150 changed = False
151 if assigned_roles and (sorted(assigned_roles) != sorted(role_facts[role_key]["assigned_roles"])):
152 update_roles(role_facts, cursor, role, role_facts[role_key]["assigned_roles"], assigned_roles)
153 changed = True
154 if changed:
155 role_facts.update(get_role_facts(cursor, role))
156 return changed
157
158
159 def absent(role_facts, cursor, role, assigned_roles):
160 role_key = role.lower()
161 if role_key in role_facts:
162 update_roles(role_facts, cursor, role, role_facts[role_key]["assigned_roles"], [])
163 cursor.execute(f"drop role {role_facts[role_key]['name']} cascade")
164 del role_facts[role_key]
165 return True
166 else:
167 return False
168
169
170 # module logic
171
172
173 def main():
174 module = AnsibleModule(
175 argument_spec=dict(
176 role=dict(required=True, aliases=["name"]),
177 assigned_roles=dict(aliases=["assigned_role"]),
178 state=dict(default="present", choices=["absent", "present"]),
179 db=dict(),
180 cluster=dict(default="localhost"),
181 port=dict(default="5433"),
182 login_user=dict(default="dbadmin"),
183 login_password=dict(no_log=True),
184 ),
185 supports_check_mode=True,
186 )
187
188 if not pyodbc_found:
189 module.fail_json(msg=missing_required_lib("pyodbc"), exception=PYODBC_IMP_ERR)
190
191 role = module.params["role"]
192 assigned_roles = []
193 if module.params["assigned_roles"]:
194 assigned_roles = module.params["assigned_roles"].split(",")
195 assigned_roles = [_f for _f in assigned_roles if _f]
196 state = module.params["state"]
197 db = ""
198 if module.params["db"]:
199 db = module.params["db"]
200
201 changed = False
202
203 try:
204 dsn = (
205 "Driver=Vertica;"
206 f"Server={module.params['cluster']};"
207 f"Port={module.params['port']};"
208 f"Database={db};"
209 f"User={module.params['login_user']};"
210 f"Password={module.params['login_password']};"
211 f"ConnectionLoadBalance=true"
212 )
213 db_conn = pyodbc.connect(dsn, autocommit=True)
214 cursor = db_conn.cursor()
215 except Exception as e:
216 module.fail_json(msg=f"Unable to connect to database: {e}.")
217
218 try:
219 role_facts = get_role_facts(cursor)
220 if module.check_mode:
221 changed = not check(role_facts, role, assigned_roles)
222 elif state == "absent":
223 try:
224 changed = absent(role_facts, cursor, role, assigned_roles)
225 except pyodbc.Error as e:
226 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
227 elif state == "present":
228 try:
229 changed = present(role_facts, cursor, role, assigned_roles)
230 except pyodbc.Error as e:
231 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
232 except NotSupportedError as e:
233 module.fail_json(msg=f"{e}", ansible_facts={"vertica_roles": role_facts})
234 except CannotDropError as e:
235 module.fail_json(msg=f"{e}", ansible_facts={"vertica_roles": role_facts})
236 except SystemExit:
237 # avoid catching this on python 2.4
238 raise
239 except Exception as e:
240 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
241
242 module.exit_json(changed=changed, role=role, ansible_facts={"vertica_roles": role_facts})
243
244
245 if __name__ == "__main__":
246 main()