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

查看:59
本文介绍了在 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 中的一个表被更新,并且该表中的特定列被更新为就绪",Lambda 必须以就绪"状态提取该行的 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 主题中),然后在您指定的实例.

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天全站免登陆