Skip to content

Instantly share code, notes, and snippets.

@jumping
Created September 2, 2016 10:08
Show Gist options
  • Save jumping/8509248d1dbe77209711e880a101b11c to your computer and use it in GitHub Desktop.
Save jumping/8509248d1dbe77209711e880a101b11c to your computer and use it in GitHub Desktop.
an mysql lookup Module for Ansible
#!/usr/bin/python
"""
Example Usage:
{{ lookup('mysql', ('1x.1xx.x.12', 'username', 'passwd', 'db_name', 'table_name', 'key_name')) }}
"""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
try:
import MySQLdb
except ImportError:
pass
class LookupModule(LookupBase):
def run(self, terms, **kwargs):
if len(terms) != 6:
AnsibleError("The number of arguments are not right! ")
ret = []
host, user, passwd, db, table, key = (terms[0], terms[1], terms[2], terms[3], terms[4], terms[5])
conn = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, port=3306)
cur = conn.cursor()
sql = 'select value from %s where keyname = "%s"' %(table, key)
cur.execute(sql)
result = cur.fetchone()
if result[0]:
ret.append(result[0])
else:
return None
@viikasgarg
Copy link

Try *terms as argument instead of terms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment