在AWS中从Lambda启动Shell脚本 [英] Launch a shell script from Lambda in AWS

查看:536
本文介绍了在AWS中从Lambda启动Shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在EC2实例中有一个bash脚本,那么lambda可以触发它吗?

If I have a bash script sitting in an EC2 instance, is there a way that lambda could trigger it?

lambda的触发来自RDS。因此,mysql中的表被更新,并且该表中的特定列被更新为 Ready,Lambda必须拉出具有 Ready状态的该行的ID并将该ID发送到bash脚本。

The trigger for lambda would be coming from RDS. So a table in mysql gets updated and a specific column in that table gets updated to "Ready", Lambda would have to pull the ID of that row with a "Ready" status and send that ID to the bash script.

推荐答案

让我们假设一些事情。首先,您知道如何使用sns设置触发器(请参见此处),以及如何将lambda脚本挂在上述触发器之外。其次,您对python有所了解(Lambda的语法产品包括Node,Java和Python),因为此示例将在Python中进行。此外,我不会介绍如何使用mysql查询数据库。您没有提到RDS实例是MySQL,Postgress还是其他。最后,您需要了解如何通过具有IAM角色和策略的AWS资源来允许权限。

Let's assume some things. First, you know how to set up a "trigger" using sns (see here) and how to hang a lambda script off of said trigger. Secondly, you know a little about python (Lambda's syntax offerings are Node, Java, and Python) because this example will be in Python. Additionally, I will not cover how to query a database with mysql. You did not mention whether your RDS instance was MySQL, Postgress, or otherwise. Lastly, you need to understand how to allow permission across AWS resources with IAM roles and policies.

以下脚本至少将概述向实例触发脚本的方法(您必须弄清楚如何查询相关信息或将该信息传递到SNS主题中),然后在您指定的实例上运行shell命令。

The following script will at least outline the method of firing a script to your instance (you'll have to figure out how to query for relevant information or pass that information into the SNS topic), and then run the shell command on an instance you specify.

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和 identified = false的行,将 identified更改为true(以确保不会同时运行其他lambda脚本)拿起),然后启动脚本。如果脚本无法成功运行,请将 identified改回false以确保您的数据仍然有效。

I would probably have two flags for the RDS row. One that says 'ready' and one that says 'identified'. So SNS topic triggers lambda script, lambda script looks for rows with 'ready' = true and 'identified' = false, change 'identified' to true (to make sure other lambda scripts that could be running at the same time aren't going to pick it up), then fire script. If script doesn't run successfully, change 'identified' back to false to make sure your data stays valid.

这篇关于在AWS中从Lambda启动Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆