[AWS][Elasticsearch]记一次Elasticsearch无法捕捉到fargate log的解决

说问题前,首先说一下这个做法的思路和实现步骤:

  • Cloudformation定义Resource时需要AWS::Logs::LogGroup
  • 在Cloudwatch Log group里找到对应ECS fargate产生的Log, 选中后Actions-->Stream to Amazon Elasticsearch Service,选中已创建的ES Cluster, 选择Log Format,后续会自动生成对应的Lambda和Role
  • 修改Lambda, 将indexName由原先的
    payload.logEvents.forEach(function(logEvent) {
        var timestamp = new Date(1 * logEvent.timestamp);
        var indexName = [
            'cw-' + timestamp.getUTCFullYear(),              // year
            ('0' + (timestamp.getUTCMonth() + 1)).slice(-2),  // month
            ('0' + timestamp.getUTCDate()).slice(-2)          // day
        ].join('.');

修改为带有index-prefix的indexName, 方便分离创建不同index

    var indexPrefix = payload.logGroup.split('/').slice(-1)[0];
    payload.logEvents.forEach(function(logEvent) {
        var timestamp = new Date(1 * logEvent.timestamp);
              
        // index name format: indexPrefix-YYYY.MM.DD
        var indexName = [
            indexPrefix + '-' + timestamp.getUTCFullYear(),              // year
            ('0' + (timestamp.getUTCMonth() + 1)).slice(-2),  // month
            ('0' + timestamp.getUTCDate()).slice(-2)          // day
        ].join('.');

  • 在ES中进入Kibana, 在management-->Index Patterns里创建新的对应的index pattern即可。创建成功的可在Saved Objects里看到。

再说实现过程中遇到的问题症状:Dev环境下ES可以正常捕捉到Fargate产生的Log,Prod环境下却不行。

最后是我们查到的原因:自动创建的Lambda所对应IAM的Role缺少Policy. 需要包含两个Policy:

  • 一个是AwsLambdaVPCAccessExecutionRole, 用以访问VPC内内容。
AWSLambdaVPCAccessExecutionRole – Grants permissions for Amazon Elastic Compute Cloud (Amazon EC2) actions to manage elastic network interfaces (ENIs).
If you are writing a Lambda function to access resources in a VPC in the Amazon Virtual Private Cloud (Amazon VPC) service, you can attach this permissions policy. The policy also grants permissions for CloudWatch Logs actions to write logs.
  • 另一个Policy则包含一个是ES Cluster的Write,和Cloudwatch Logs的Write,可能由系统产生,名称形式如‘oneClick_lambda_elasticsearch_execution_157xxxxxx’

因为我们建的Managed Elasticseach是private的cluster, 而Lambda作为有可能面向外部的资源,自动生成对应的IAM Role时出于安全考虑,系统不会自动添加允许访问VPC内内容的Policy, 所以需要手动添加,也就是上面提到的第一个Policy。

Subscribe to 隅

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe