首页 > 解决方案 > AWS Lambda、Python:从 Lambda 或 Linux 命令调用 Shell 脚本

问题描述

我正在编写一个用 Python 编写的 AWS Lambda 脚本,我目前正在获取所有带有特定标签的实例,并从中删除最旧的实例。之后,从剩余的实例中,我想在实例上调用 linux 命令。我唯一需要的是调用crontab -r,因为最旧的实例将设置 cron,在 ASG 生成的实例中添加这些 cron 将导致发送重复的电子邮件。

我已经完成了获取除最旧实例之外的所有实例的部分,但是我如何调用crontab -r每个实例?有任何想法吗。谢谢你。

代码 :

import boto.ec2
import boto3
conn=boto.ec2.connect_to_region("eu-central-1")
reservations = conn.get_all_instances()
instances_list = []
process_instance_list = []
for res in reservations:
    for inst in res.instances:
        if 'Name' in inst.tags:
            if inst.tags['Name'] == 'PROJECT_NAME' :
               instances_list.append(inst);


instances_list.sort(key=lambda x: x.launch_time, reverse=False)
non_processed_id=instances_list[0]

for val in instances_list:
    if val.id != non_processed_id.id:
       // Call crontab -r here.

谢谢你。:-)

标签: pythonamazon-web-servicesamazon-ec2aws-lambda

解决方案


使用boto3 send_command在 ec2 上执行命令。

您的案例示例:

boto3.client('ssm').send_command(
    InstanceIds=[val.id], 
    DocumentName='AWS-RunShellScript', 
    Parameters={'commands': ['crontab -r']}, 
    Comment='Crontab remove'
)

推荐阅读