github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/docs/sources/clients/aws/ecs/_index.md (about)

     1  ---
     2  title: ECS
     3  ---
     4  # Sending Logs From AWS Elastic Container Service (ECS)
     5  
     6  [ECS][ECS] is the fully managed container orchestration service by Amazon. Combined with [Fargate][Fargate] you can run your container workload without the need to provision your own compute resources. In this tutorial we will see how you can leverage [Firelens][Firelens] an AWS log router to forward all your logs and your workload metadata to a Grafana Loki instance.
     7  
     8  After this tutorial you will able to query all your logs in one place using Grafana.
     9  
    10  <!-- TOC -->
    11  
    12  - [Sending Logs From AWS Elastic Container Service (ECS)](#sending-logs-from-aws-elastic-container-service-ecs)
    13    - [Requirements](#requirements)
    14    - [Setting up the ECS cluster](#setting-up-the-ecs-cluster)
    15    - [Creating your task definition](#creating-your-task-definition)
    16    - [Running your service](#running-your-service)
    17  
    18  <!-- /TOC -->
    19  
    20  ## Requirements
    21  
    22  Before we start you'll need:
    23  
    24  - The [AWS CLI][aws cli] configured (run `aws configure`).
    25  - A Grafana instance with a Loki data source already configured, you can use [GrafanaCloud][GrafanaCloud] free trial.
    26  - A Subnet in VPC that is routable from the internet. (Follow those [instructions][create an vpc] if you need to create one).
    27  - A [Security group][security group] of your choice for your containers. (Follow those [instructions][managing sg] if you need to create one).
    28  
    29  For the sake of simplicity we'll use a GrafanaCloud Loki and Grafana instances, you can get an free account for this tutorial on our [website][GrafanaCloud], but all the steps are the same if you're running your own Open Source version of Loki and Grafana instances.
    30  
    31  ## Setting up the ECS cluster
    32  
    33  To run containers with ECS you need an [ECS cluster][ecs cluster], we'll use a [Fargate][Fargate] cluster, but if you prefer to use an EC2 cluster all the given steps are still applicable.
    34  
    35  Let's create the cluster with awscli:
    36  
    37  ```bash
    38  aws ecs create-cluster --cluster-name ecs-firelens-cluster
    39  ```
    40  
    41  We will also need an [IAM Role to run containers][ecs iam] with, let's create a new one and authorize [ECS][ECS] to endorse this role.
    42  
    43  > You might already have this `ecsTaskExecutionRole` role in your AWS account if that's the case you can skip this step.
    44  
    45  ```bash
    46  curl https://raw.githubusercontent.com/grafana/loki/master/docs/sources/clients/aws/ecs/ecs-role.json > ecs-role.json
    47  aws iam create-role --role-name ecsTaskExecutionRole  --assume-role-policy-document file://ecs-role.json
    48  
    49  {
    50      "Role": {
    51          "Path": "/",
    52          "RoleName": "ecsTaskExecutionRole",
    53          "RoleId": "AROA5FW5RZWLXFPU656SQ",
    54          "Arn": "arn:aws:iam::0000000000:role/ecsTaskExecutionRole",
    55          "CreateDate": "2020-07-09T14:51:49+00:00",
    56          "AssumeRolePolicyDocument": {
    57              "Version": "2012-10-17",
    58              "Statement": [
    59                  {
    60                      "Effect": "Allow",
    61                      "Principal": {
    62                          "Service": [
    63                              "ecs-tasks.amazonaws.com"
    64                          ]
    65                      },
    66                      "Action": "sts:AssumeRole"
    67                  }
    68              ]
    69          }
    70      }
    71  }
    72  ```
    73  
    74  Note down the [ARN][arn] of this new role, we'll use it later to create an ECS task.
    75  
    76  Finally we'll give the [ECS task execution policy][ecs iam](`AmazonECSTaskExecutionRolePolicy`) to the created role, this will allows us to manage logs with [Firelens][Firelens]:
    77  
    78  ```bash
    79  aws iam attach-role-policy --role-name ecsTaskExecutionRole --policy-arn "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
    80  ```
    81  
    82  ## Creating your task definition
    83  
    84  Amazon [Firelens][Firelens] is a log router (usually `fluentd` or `fluentbit`) you run along the same task definition next to your application containers to route their logs to Loki.
    85  
    86  In this example we will use [fluentbit][fluentbit] with the [fluentbit output plugin][fluentbit loki] installed but if you prefer [fluentd][fluentd] make sure to check the [fluentd output plugin][fluentd loki] documentation.
    87  
    88  > We recommend you to use [fluentbit][fluentbit] as it's less resources consuming than [fluentd][fluentd].
    89  
    90  Our [task definition][task] will be made of two containers, the [Firelens][Firelens] log router to send logs to Loki (`log_router`) and a sample application to generate log with (`sample-app`).
    91  
    92  Let's download the task definition, we'll go through the most important parts.
    93  
    94  ```bash
    95  curl https://raw.githubusercontent.com/grafana/loki/master/docs/sources/clients/aws/ecs/ecs-task.json > ecs-task.json
    96  ```
    97  
    98  ```json
    99   {
   100      "essential": true,
   101      "image": "grafana/fluent-bit-plugin-loki:2.0.0-amd64",
   102      "name": "log_router",
   103      "firelensConfiguration": {
   104          "type": "fluentbit",
   105          "options": {
   106              "enable-ecs-log-metadata": "true"
   107          }
   108      },
   109      "logConfiguration": {
   110          "logDriver": "awslogs",
   111          "options": {
   112              "awslogs-group": "firelens-container",
   113              "awslogs-region": "us-east-2",
   114              "awslogs-create-group": "true",
   115              "awslogs-stream-prefix": "firelens"
   116          }
   117      },
   118      "memoryReservation": 50
   119  },
   120  ```
   121  
   122  The `log_router` container image is the [Fluent bit Loki docker image][fluentbit loki image] which contains the Loki plugin pre-installed. As you can see the `firelensConfiguration` type is set to `fluentbit` and we've also added `options` to enable ECS log metadata. This will be useful when querying your logs with Loki LogQL label matchers.
   123  
   124  > The `logConfiguration` is mostly there for debugging the fluent-bit container, but feel free to remove that part when you're done testing and configuring.
   125  
   126  ```json
   127   {
   128      "command": [
   129          "/bin/sh -c \"while true; do sleep 15 ;echo hello_world; done\""
   130      ],
   131      "entryPoint": ["sh","-c"],
   132      "essential": true,
   133      "image": "alpine:3.13",
   134      "logConfiguration": {
   135          "logDriver": "awsfirelens",
   136          "options": {
   137              "Name": "grafana-loki",
   138              "Url": "https://<userid>:<grafancloud apikey>@<grafanacloud host>/loki/api/v1/push",
   139              "Labels": "{job=\"firelens\"}",
   140              "RemoveKeys": "container_id,ecs_task_arn",
   141              "LabelKeys": "container_name,ecs_task_definition,source,ecs_cluster",
   142              "LineFormat": "key_value"
   143          }
   144      },
   145      "name": "sample-app"
   146  }
   147  ```
   148  
   149  The second container is our `sample-app`, a simple [alpine][alpine] container that prints to stdout welcoming messages. To send those logs to Loki, we will configure this container to use the log driver `awsfirelens`.
   150  
   151  Go ahead and replace the `Url` property with your [GrafanaCloud][GrafanaCloud] credentials, you can find them in your [account][grafanacloud account] in the Loki instance page. If you're running your own Loki instance replace completely the URL (e.g `http://my-loki.com:3100/loki/api/v1/push`).
   152  
   153  We include plain text credentials in `options` for simplicity. However, this exposes credentials in your ECS task definition and in any version-controlled configuration. Mitigate this issue by using a secret store such as [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html), combined with the `secretOptions` configuration option for [injecting sensitive data in a log configuration](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data-secrets.html#secrets-logconfig).
   154  
   155  All `options` of the `logConfiguration` will be automatically translated into [fluentbit ouput][fluentbit ouput]. For example, the above options will produce this fluent bit `OUTPUT` config section:
   156  
   157  ```conf
   158  [OUTPUT]
   159      Name grafana-loki
   160      Match awsfirelens*
   161      Url https://<userid>:<grafancloud apikey>@logs-prod-us-central1.grafana.net/loki/api/v1/push
   162      Labels {job="firelens"}
   163      RemoveKeys container_id,ecs_task_arn
   164      LabelKeys container_name,ecs_task_definition,source,ecs_cluster
   165      LineFormat key_value
   166  ```
   167  
   168  This `OUTPUT` config will forward logs to [GrafanaCloud][GrafanaCloud] Loki, to learn more about those options make sure to read the [fluentbit output plugin][fluentbit loki] documentation.
   169  We've kept some interesting and useful labels such as `container_name`, `ecs_task_definition` , `source` and `ecs_cluster` but you can statically add more via the `Labels` option.
   170  
   171  > If you want run multiple containers in your task, all of them needs a `logConfiguration` section, this give you the opportunity to add different labels depending on the container.
   172  
   173  ```json
   174  {
   175      "containerDefinitions": [
   176       ...
   177      ],
   178      "cpu": "256",
   179      "executionRoleArn": "arn:aws:iam::00000000:role/ecsTaskExecutionRole",
   180      "family": "loki-fargate-task-definition",
   181      "memory": "512",
   182      "networkMode": "awsvpc",
   183      "requiresCompatibilities": [
   184          "FARGATE"
   185      ]
   186  }
   187  ```
   188  
   189  Finally, you need to replace the `executionRoleArn` with the [ARN][arn] of the role we created in the [first section](#Setting-up-the-ECS-cluster).
   190  
   191  Once you've finished editing the task definition we can then run the command below to create the task:
   192  
   193  ```bash
   194  aws ecs register-task-definition --region us-east-2 --cli-input-json  file://ecs-task.json
   195  ```
   196  
   197  Now let's create and start a service.
   198  
   199  ## Running your service
   200  
   201  To run the service you need to provide the task definition name `loki-fargate-task-definition:1` which is the combination of task family plus the task revision `:1`. You also need your own subnet and security group, you can replace respectively `subnet-306ca97d` and `sg-02c489bbdeffdca1d` in the command below and start the your service:
   202  
   203  ```bash
   204  aws ecs create-service --cluster ecs-firelens-cluster \
   205  --service-name firelens-loki-fargate \
   206  --task-definition loki-fargate-task-definition:1 \
   207  --desired-count 1 --region us-east-2 --launch-type "FARGATE" \
   208  --network-configuration "awsvpcConfiguration={subnets=[subnet-306ca97d],securityGroups=[sg-02c489bbdeffdca1d],assignPublicIp=ENABLED}"
   209  ```
   210  
   211  > Make sure public (`assignPublicIp`) is enabled otherwise ECS won't connect to the internet and you won't be able to pull external docker images.
   212  
   213  You can now access the ECS console and you should see your task running. Now let's open Grafana and use explore with the Loki data source to explore our task logs. Enter the query `{job="firelens"}` and you should see our `sample-app` logs showing up as shown below:
   214  
   215  ![grafana logs firelens][grafana logs firelens]
   216  
   217  Using the `Log Labels` dropdown you should be able to discover your workload via the ECS metadata, which is also visible if you expand a log line.
   218  
   219  That's it ! Make sure to checkout LogQL to learn more about Loki powerful query language.
   220  
   221  [create an vpc]: https://docs.aws.amazon.com/vpc/latest/userguide/vpc-subnets-commands-example.html
   222  [ECS]: https://aws.amazon.com/ecs/
   223  [Fargate]: https://aws.amazon.com/fargate/
   224  [Firelens]: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html
   225  [GrafanaCloud]: https://grafana.com/signup/
   226  [security group]: https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html
   227  [aws cli]: https://aws.amazon.com/cli/
   228  [managing sg]: https://docs.aws.amazon.com/cli/latest/userguide/cli-services-ec2-sg.html
   229  [ecs cluster]: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html
   230  [ecs iam]: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html
   231  [arn]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
   232  [task]: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html
   233  [fluentd loki]: https://grafana.com/docs/loki/latest/clients/fluentd/
   234  [fluentbit loki]: https://grafana.com/docs/loki/latest/clients/fluentbit/
   235  [fluentbit]: https://fluentbit.io/
   236  [fluentd]: https://www.fluentd.org/
   237  [fluentbit loki image]: https://hub.docker.com/r/grafana/fluent-bit-plugin-loki
   238  [logql]: https://grafana.com/docs/loki/latest/logql/
   239  [alpine]:https://hub.docker.com/_/alpine
   240  [fluentbit ouput]: https://fluentbit.io/documentation/0.14/output/
   241  [routing]: https://fluentbit.io/documentation/0.13/getting_started/routing.html
   242  [grafanacloud account]: https://grafana.com/login
   243  [grafana logs firelens]: ./ecs-grafana.png
   244  [logql]: ../../../logql