如果我在EC2实例中有一个bash脚本,lambda是否可以触发它?
lambda的触发器将来自RDS。因此,mysql中的表会更新,并且该表中的特定列会更新为" Ready",Lambda必须使用" Ready"来提取该行的ID。 status并将该ID发送到bash脚本。
答案 0 :(得分:5)
使用Amazon EC2 Simple Systems Manager,您可以配置SSM文档以在实例上运行脚本,并为该脚本传递参数。 Lambda实例需要运行SSM send-command,以实例id为目标实现。
示例SSM文档: run_my_example.json:
{
"schemaVersion": "1.2",
"description": "Run shell script to launch.",
"parameters": {
"taskId":{
"type":"String",
"default":"",
"description":"(Required) the Id of the task to run",
"maxChars":16
}
},
"runtimeConfig": {
"aws:runShellScript": {
"properties": [
{
"id": "0.aws:runShellScript",
"runCommand": ["run_my_example.sh"]
}
]
}
}
}
上述SSM文档接受taskId作为参数。
将此文档另存为JSON文件,并使用AWS CLI调用create-document:
aws ssm create-document --content file:///tmp/run_my_example.json --name "run_my_example"
您可以致电describe-document
:
aws ssm describe-document --name "run_my_example"
您可以指定taskId参数并使用包含send-command
aws ssm send-command --instance-ids i-12345678 --document-name "run_my_example" --parameters --taskid=123456
备注强>
您需要在Lambda脚本中使用一些逻辑来识别服务器EG的实例ID,查找特定标记实例的实例ID。
答案 1 :(得分:4)
让我们假设一些事情。首先,您知道如何使用sns设置“触发器”(请参阅here)以及如何从所述触发器挂起lambda脚本。其次,你对python有一点了解(Lambda的语法产品是Node,Java和Python),因为这个例子将在Python中。另外,我不会介绍如何使用mysql查询数据库。您没有提到您的RDS实例是MySQL,Postgress还是其他。最后,您需要了解如何通过IAM角色和策略允许跨AWS资源的权限。
以下脚本将至少概述向您的实例触发脚本的方法(您必须弄清楚如何查询相关信息或将该信息传递到SNS主题),然后运行shell命令您指定的实例。
import boto3
def lambda_handler(event, context):
#query RDS to get ID or get from SNS topic
id = *queryresult*
command = 'sh /path/to/scriptoninstance' + id
ssm = boto3.client('ssm')
ssmresponse = ssm.send_command(InstanceIds=['i-instanceid'], DocumentName='AWS-RunShellScript', Parameters= { 'commands': [command] } )
我可能有两个RDS行的标志。一个说“准备好”,一个说“已识别”。所以SNS主题触发lambda脚本,lambda脚本查找'ready'= true和'identify'= false的行,将'identify'更改为true(以确保可能同时运行的其他lambda脚本不会运行拿起它,然后开火脚本。如果脚本未成功运行,请将“已识别”更改回false以确保您的数据保持有效。
答案 2 :(得分:2)
有几件事情要考虑其中之一:
我建议看一下消息队列(比如SQS)。这样可以解决很多问题。
它是如何运作的:
答案 3 :(得分:1)
我认为您可以使用新的EC2 Run Command功能来完成此任务。