使用Lambda在ec2上执行脚本时出现问题

时间:2019-02-22 17:47:53

标签: python-2.7 amazon-ec2 aws-lambda

我已经在python中创建了一个脚本,以便在MySQL 5.7中创建数据库

这是脚本

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()

当我手动运行它时,它会创建一个数据库,但是当我使用AWS Lambda执行脚本时,会给我一个错误

我已经在Ec2上安装了mysql.connector

----------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

这是我创建的Lambda

导入boto3 导入json

def lambda_handler(事件,上下文):

#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 个答案:

答案 0 :(得分:1)

在您的系统上为python版本全局安装mysql连接器,就像使用python命令执行脚本一样,它可能是python 2.7,因此您可以使用以下命令

sudo pip安装mysql-connector-python