首页 > 解决方案 > 尝试从 aws lambda 运行 javascript 代码以列出或终止 ecs 任务

问题描述

我一直在努力从 aws lambda 运行以下代码,但我没有看到任何错误,也没有看到任何 ECS 任务被杀死。

角色都很好。

是否可以从 lambda 连接到 ECS?

  // NOTE: Set Lambda timeout to at least 60 seconds
const AWS = require('aws-sdk');

AWS.config.region = 'us-east-1';

const ecs = new AWS.ECS({ apiVersion: '2014-11-13' });
const sns = new AWS.SNS({ apiVersion: '2016-11-15' });

// ARN of the SNS topic to get generate exceptions
// *** UPDATE FOR YOUR REGION, ACCOUNT, AND SNS TOPIC ***
const TOPIC_INFORMATION_ARN = 'arn:aws:sns:[REGION]:[ACCOUNT NUMBER]:[SNS TOPIC]';  //replaced by sns

// *** MODIFY SETTINGS HERE FOR YOUR FARGATE CLUSTERS
const FARGATE_CLUSTERS = [
    {
        cluster: "ecs-dev",
        period: 15,  // 4 times an hour
        enabled: false
    },
    {
        cluster: "ecs-stage",
        period: 30,  // 2 times an hour
        enabled: false
    },
    {
        cluster: "ecs-prod",
        period: 60,  // 1 time an hour
        enabled: false
    }];

// Called every 15 minutes using CRON, so minute value should be 00, 15, 30, 45
async function main(event) {
    try {

        // For each ECS cluster listed above...
        for (var i = 0; i < FARGATE_CLUSTERS.length; i++) {

            // Only kill a task if cluster is enabled
            if (FARGATE_CLUSTERS[i].enabled) {

                let date = new Date(event.time);
                let minutes = date.getMinutes();                

                // Only kill a task if schedule matches the current time
                if ((minutes % FARGATE_CLUSTERS[i].period) == 0) {
                   
                    // Get the list of currently running Fargate tasks in the cluster.
                    var res = await ecs.listTasks({
                        cluster: FARGATE_CLUSTERS[i].cluster,
                        desiredStatus: 'RUNNING',
                        launchType: 'FARGATE'
                    }).promise();

                    // Select one of the tasks at random for termination.
                    var index = Math.floor(Math.random() * res.taskArns.length);
                    var doomedTask = res.taskArns[index];

                    // Kill the selected task.
                    await ecs.stopTask({
                        cluster: FARGATE_CLUSTERS[i].cluster,
                        task: doomedTask,
                        reason: 'CHAOS MONKEY'
                    }).promise();
                }
            }
        }
    } catch (err) {
        console.log(err.stack);
        await sns.publish({
            Message: err.stack,
            Subject: 'Chaos Monkey Fargate',
            TopicArn: TOPIC_INFORMATION_ARN
        }).promise();
    }
};

exports.handler = async (event) => {
    await main(event);
};

尝试连接到 Fargate ECS 集群并执行 lambda 以在特定时间间隔列出并终止正在运行的 ECS 任务。

如何在调试模式下运行 javascript?

这里可能是什么问题?

标签: javascriptamazon-web-servicesaws-lambdaamazon-ecschaos

解决方案


我认为您想安排启动/停止 ECS 任务,您可以执行此操作,您需要以下内容:

1- 创建一个 lambda 函数,通过更新 ECS 服务 DesiredCount 来启动或停止(DesiredCount=0 停止,DesiredCount>0 启动)。

2- 创建计划的 CloudWatch 事件,以启动 ECS 任务(将 DesiredCount 设置为您喜欢的任务数)。

3- 创建计划的 CloudWatch 事件,以停止 ECS 任务(将 DesiredCount 设置为 0 )。

此 lambda 代码由 python,检查集群 Env 标记是否为 Dev 以根据 cloudwatch 事件(开始或停止)更改 DesiredCount 值

import boto3 
import json
  ecs_client = boto3.client('ecs')
  client_scale = boto3.client('application-autoscaling')
def lambda_handler(event, context):
  response_clusters = ecs_client.list_clusters()
  clusters_list = response_clusters['clusterArns']
  for cluster in clusters_list:
    cluster_info = ecs_client.describe_clusters(clusters=[cluster,],include=['TAGS'])
    print(cluster)
    for cluster_item_info in cluster_info['clusters']:
      ISDev = False
      IsService = False
      for tag in cluster_item_info['tags']:
         if tag['key'] == 'Env' and tag['value'] =='Dev':
            ISDev = True
         if tag['key'] == 'Type' and tag['value'] =='Service':
            IsService = True
         if ISDev and IsService:
           print(cluster_item_info['clusterName'])
           response_services =
           ecs_client.list_services(cluster=cluster_item_info['clusterName'])
           services_list = response_services['serviceArns']
           for service in services_list:
              service_info = 
                                                                                               
              ecs_client.describe_services(cluster=cluster_item_info['clusterName'],
              services= [service,],)
              for item in service_info ['services']:
                 print(item['serviceName'])
                 print(item['desiredCount'])
                 resource = 
                 'service/'+cluster_item_info['clusterName']+'/'+item['serviceName']
                 scale_info = client_scale.describe_scalable_targets
                 (ServiceNamespace='ecs',ResourceIds=[resource,])
                 for scale_item_info in scale_info['ScalableTargets']:
                    print(scale_item_info['MinCapacity'])
                    print(scale_item_info['MaxCapacity'])
                    print(event['Action'])
                    if event['Action'] == 'stop':
                       desiredCount_number = 0
                    else:
                       desiredCount_number = scale_item_info['MinCapacity']
                    response_ecs_update = ecs_client.update_service(
                    cluster=cluster_item_info['clusterName'],
                    service=item['serviceName'],
                    desiredCount=desiredCount_number
                    )

推荐阅读