2

I have created a script in python to create a database in MySQL 5.7

here is the script

import io
import os
import json
import requests
import subprocess
import mysql.connector

try:
#Create Database Connection
  mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="****"
  )
  mycursor = mydb.cursor()
  dbStatus = mycursor.execute(createDatabaseQuery)
  print('Database Created')
except Exception as e :
  print ("Error while connecting to MySQL", e)
finally:
  #closing database connection.
  if(mydb .is_connected()):
      mydb.close()

When I run it manually it creates a database, but when I execute the script using a AWS Lambda it gives me a error

I have already installed the mysql.connector on Ec2

----------ERROR-------
Traceback (most recent call last):
  File "CreateBrand.py", line 6, in <module>
  import mysql.connector
ImportError: No module named mysql.connector
failed to run commands: exit status 1

Here is the Lambda that I have created

import boto3 import json

def lambda_handler(event, context):

#boto3 Clients
 instanceID = ['i-*******']
 params={"commands":["cd /var/www/html/sites"]}
 cmd = 'touch /var/www/html/sites/demo'
 runscript = 'sudo python CreateDB.py'
 try:
    ssm_client = boto3.client('ssm')
    response = ssm_client.send_command(
        InstanceIds=instanceID,
        DocumentName="AWS-RunShellScript",
        Parameters={"workingDirectory": ["/var/www/html/sites/"],   "executionTimeout": ["3600"], "commands": [runscript]}, )
 except Exception as e:
    print(e)

1 Answer 1

3

Install the mysql connector globally for the python version on your system using as you are using python command to execute the script it is probably python 2.7 so you can use the below command

sudo pip install mysql-connector-python

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.