This commit is contained in:
Jonas Forsberg
2021-09-25 16:04:59 +02:00
parent 0a1dbb5971
commit 6638cda6fb
4 changed files with 137 additions and 1 deletions

View File

@@ -69,3 +69,69 @@ def user(name, host, password):
ret["changes"].update({"Created user": f"{name}@{host}"})
ret["result"]=True
return ret
def database(name, users=[]):
"""
Creates database
name
name of the database
users
list of user dict
name: username@localhost
grant: [ALL]
or
name: user2@%
grant: [CREATE, DELETE, DROP]
"""
ret = {
"name": name,
"changes": {},
"result": False,
"comment": ""
}
#check if db exists
result = __salt__["mysql.execute"]("root", __pillar__['mysql']['root_password'],f'USE {name};')
if not result["result"]:
result = __salt__["mysql.execute"]("root", __pillar__['mysql']['root_password'],f'CREATE DATABASE {name};')
if not result["result"]:
ret["comment"] = result["err"]
return ret
ret["changes"].update({"Database created": name})
for user in users:
result = __salt__["mysql.execute"]("root", __pillar__['mysql']['root_password'],f'SHOW GRANTS FOR {user};')
if not result["result"]:
ret["comment"] = result["err"]
return ret
have_grants = False
for row in result["out"].decode("utf-8").split("\n"):
if f" `{name}`.* " in row:
have_grants = True
break
if not have_grants:
result = __salt__["mysql.execute"]("root", __pillar__['mysql']['root_password'],f'GRANT ALL PRIVILEGES ON {name}.* to {user};')
if not result["result"]:
ret["comment"] = result["err"]
return ret
ret["changes"].update({user: "grantad ALL privileges"})
if len(ret["changes"]):
ret["comment"] = "Changed"
else:
ret["comment"] = "Database is in desired state"
ret["result"] = True
return ret
ret["comment"] = "Database exists"
ret["result"] = True
return ret