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

     1  ---
     2  title: EC2
     3  ---
     4  # Running Promtail on AWS EC2
     5  
     6  In this tutorial we're going to setup [Promtail](../../promtail/) on an AWS EC2 instance and configure it to sends all its logs to a Grafana Loki instance.
     7  
     8  <!-- TOC -->
     9  
    10  - [Running Promtail on AWS EC2](#running-promtail-on-aws-ec2)
    11    - [Requirements](#requirements)
    12    - [Creating an EC2 instance](#creating-an-ec2-instance)
    13    - [Setting up Promtail](#setting-up-promtail)
    14    - [Configuring Promtail as a service](#configuring-promtail-as-a-service)
    15    - [Sending systemd logs](#sending-systemd-logs)
    16  
    17  <!-- /TOC -->
    18  
    19  ## Requirements
    20  
    21  Before we start you'll need:
    22  
    23  - An AWS account (with the `AWS_ACCESS_KEY` and `AWS_SECRET_KEY`)
    24  - A VPC that is routable from the internet. (Follow those [instructions][create an vpc] if you need to create one)
    25  - A SSH public key. (Follow those [instructions][create an ssh key] if you need a new one)
    26  - The [AWS CLI][aws cli] configured (run `aws configure`).
    27  - A Grafana instance with a Loki data source already configured, you can use [GrafanaCloud][GrafanaCloud] free trial.
    28  
    29  For the sake of simplicity we'll use a Grafana Cloud Loki and Grafana instances, you can get a free account for this tutorial at [Grafana Cloud], but all the steps are the same if you're running your own Open Source version of Loki and Grafana instances.
    30  
    31  To make it easy to learn all the following instructions are manual, however in a real setup we recommend you to use provisioning tools such as [Terraform][terraform], [CloudFormation][cloud formation], [Ansible][ansible] or [Chef][chef].
    32  
    33  ## Creating an EC2 instance
    34  
    35  As a first step we're going to import our SSH key to AWS so that we can SSH to our future EC2 instance, let's run our first command:
    36  
    37  ```bash
    38  aws ec2 import-key-pair --key-name "promtail-ec2" --public-key-material fileb://~/.ssh/id_rsa.pub
    39  ```
    40  
    41  Next we're going to create a [security group][security group], make sure to note the group id, we'll need it for the following command:
    42  
    43  ```bash
    44  aws ec2 create-security-group --group-name promtail-ec2  --description "promtail on ec2" --vpc-id vpc-668d120f
    45  {
    46      "GroupId": "sg-02c489bbdeffdca1d"
    47  }
    48  ```
    49  
    50  Now let's authorize inbound access for SSH and [Promtail](../../promtail/) server:
    51  
    52  ```bash
    53  aws ec2 authorize-security-group-ingress --group-id sg-02c489bbdeffdca1d --protocol tcp --port 22 --cidr 0.0.0.0/0
    54  aws ec2 authorize-security-group-ingress --group-id sg-02c489bbdeffdca1d --protocol tcp --port 3100 --cidr 0.0.0.0/0
    55  ```
    56  
    57  > You don't need to open those ports to all IPs as shown above you can use your own IP range.
    58  
    59  We're going to create an [Amazon Linux 2][Amazon Linux 2] instance as this is one of the most popular but feel free to use the AMI of your choice.
    60  
    61  To create the instance use the following command, make sure to note the instance id:
    62  
    63  ```bash
    64  aws ec2 run-instances --image-id ami-016b213e65284e9c9 --count 1 --instance-type t2.micro --key-name promtail-ec2 --security-groups promtail-ec2
    65  ```
    66  
    67  To make it more interesting later let's tag (`Name=promtail-demo`) our instance:
    68  
    69  ```bash
    70  aws ec2 create-tags --resources i-041b0be05c2d5cfad --tags Key=Name,Value=promtail-demo
    71  ```
    72  
    73  > Tags enable you to categorize your AWS resources in different ways, for example, by purpose, owner, or environment. This is useful when you have many resources of the same type—you can quickly identify a specific resource based on the tags that you've assigned to it. You'll see later, Promtail can transform those tags into [Loki labels][labels].
    74  
    75  Finally let's grab the public DNS of our instance:
    76  
    77  ```bash
    78  aws ec2 describe-instances --filters "Name=tag:Name,Values=promtail-demo" --query "Reservations[].Instances[].NetworkInterfaces[].Association.PublicDnsName"
    79  ```
    80  
    81  and start an SSH session:
    82  
    83  ```bash
    84  ssh ec2-user@ec2-13-59-62-37.us-east-2.compute.amazonaws.com
    85  ```
    86  
    87  ## Setting up Promtail
    88  
    89  First let's make sure we're running as root by using `sudo -s`.
    90  Next we'll download, install and give executable right to [Promtail](../../promtail/).
    91  
    92  ```bash
    93  mkdir /opt/promtail && cd /opt/promtail
    94  curl -O -L "https://github.com/grafana/loki/releases/download/v2.0.0/promtail-linux-amd64.zip"
    95  unzip "promtail-linux-amd64.zip"
    96  chmod a+x "promtail-linux-amd64"
    97  ```
    98  
    99  Now we're going to download the [Promtail configuration](../../promtail/) file below and edit it, don't worry we will explain what those means.
   100  The file is also available as a gist at [cyriltovena/promtail-ec2.yaml][config gist].
   101  
   102  ```bash
   103  curl https://raw.githubusercontent.com/grafana/loki/master/docs/sources/clients/aws/ec2/promtail-ec2.yaml > ec2-promtail.yaml
   104  vi ec2-promtail.yaml
   105  ```
   106  
   107  ```yaml
   108  server:
   109    http_listen_port: 3100
   110    grpc_listen_port: 0
   111  
   112  clients:
   113    - url: https://<user id>:<api secret>@logs-prod-us-central1.grafana.net/loki/api/v1/push
   114  
   115  positions:
   116    filename: /opt/promtail/positions.yaml
   117  
   118  scrape_configs:
   119    - job_name: ec2-logs
   120      ec2_sd_configs:
   121        - region: us-east-2
   122          access_key: REDACTED
   123          secret_key: REDACTED
   124      relabel_configs:
   125        - source_labels: [__meta_ec2_tag_Name]
   126          target_label: name
   127          action: replace
   128        - source_labels: [__meta_ec2_instance_id]
   129          target_label: instance
   130          action: replace
   131        - source_labels: [__meta_ec2_availability_zone]
   132          target_label: zone
   133          action: replace
   134        - action: replace
   135          replacement: /var/log/**.log
   136          target_label: __path__
   137        - source_labels: [__meta_ec2_private_dns_name]
   138          regex: "(.*)"
   139          target_label: __host__
   140  ```
   141  
   142  The **server** section indicates Promtail to bind his http server to 3100. Promtail serves HTTP pages for [troubleshooting](../../promtail/troubleshooting) service discovery and targets.
   143  
   144  The **clients** section allow you to target your loki instance, if you're using GrafanaCloud simply replace `<user id>` and `<api secret>` with your credentials. Otherwise just replace the whole URL with your custom Loki instance.(e.g `http://my-loki-instance.my-org.com/loki/api/v1/push`)
   145  
   146  [Promtail](../../promtail/) uses the same [Prometheus **scrape_configs**][prometheus scrape config]. This means if you already own a Prometheus instance the config will be very similar and easy to grasp.
   147  
   148  Since we're running on AWS EC2 we want to uses EC2 service discovery, this will allows us to scrape metadata about the current instance (and even your custom tags) and attach those to our logs. This way managing and querying on logs will be much easier.
   149  
   150  Make sure to replace accordingly you current `region`, `access_key` and `secret_key`, alternatively you can use an [AWS Role][role] ARN, for more information about this, see documentation for [`ec2_sd_config`][ec2_sd_config].
   151  
   152  Finally the [`relabeling_configs`][relabel] section has three purposes:
   153  
   154  1. Selecting the labels discovered you want to attach to your targets. In our case here, we're keeping `instance_id` as instance, the tag `Name` as name and the `zone` of the instance. Make sure to check out the Prometheus [`ec2_sd_config`][ec2_sd_config] documentation for the full list of available labels.
   155  
   156  2. Choosing where Promtail should find log files to tail, in our example we want to include all log files that exist in `/var/log` using the glob `/var/log/**.log`. If you need to use multiple glob, you can simply add another job in your `scrape_configs`.
   157  
   158  3. Ensuring discovered targets are only for the machine Promtail currently runs on. This is achieve by adding the label `__host__` using the incoming metadata `__meta_ec2_private_dns_name`. If it doesn't match the current `HOSTNAME` environnement variable, the target will be dropped.
   159  
   160  Alright we should be ready to fire up Promtail, we're going to run it using the flag `--dry-run`. This is perfect to ensure everything is correctly, specially when you're still playing around with the configuration. Don't worry when using this mode, Promtail won't send any logs and won't remember any file positions.
   161  
   162  ```bash
   163   ./promtail-linux-amd64 -config.file=./ec2-promtail.yaml --dry-run
   164  ```
   165  
   166  If everything is going well Promtail should print out log lines with their labels discovered instead of sending them to Loki, like shown below:
   167  
   168  ```bash
   169  2020-07-08T14:51:38-0700	{filename="/var/log/cloud-init.log", instance="i-041b0be05c2d5cfad", name="promtail-demo", zone="us-east-2c"}	Jul 07 21:37:24 cloud-init[3035]: util.py[DEBUG]: loaded blob returned None, returning default.
   170  ```
   171  
   172  Don't hesitate to edit the your config file and start Promtail again to try your config out.
   173  
   174  If you want to see existing targets and available labels you can reach Promtail server using the public dns assigned to your instance:
   175  
   176  ```bash
   177  open http://ec2-13-59-62-37.us-east-2.compute.amazonaws.com:3100/
   178  ```
   179  
   180  For example the page below is the service discovery page. It shows you all discovered targets, with their respective available labels and the reason it was dropped if it was the case.
   181  
   182  ![discovery page page][discovery page]
   183  
   184  This page is really useful to understand what labels are available to forward with the `relabeling` configuration but also why Promtail is not scraping your target.
   185  
   186  ## Configuring Promtail as a service
   187  
   188  Now that we have correctly configured Promtail. We usually want to make sure it runs as a [systemd service][systemd], so it can automatically restart on failure or when the instance restart.
   189  
   190  Let's create a new service using `vim /etc/systemd/system/promtail.service` and copy the service definition below:
   191  
   192  ```systemd
   193  [Unit]
   194  Description=Promtail
   195  
   196  [Service]
   197  User=root
   198  WorkingDirectory=/opt/promtail/
   199  ExecStartPre=/bin/sleep 30
   200  ExecStart=/opt/promtail/promtail-linux-amd64 --config.file=./ec2-promtail.yaml
   201  SuccessExitStatus=143
   202  TimeoutStopSec=10
   203  Restart=on-failure
   204  RestartSec=5
   205  
   206  [Install]
   207  WantedBy=multi-user.target
   208  ```
   209  
   210  Let's reload the systemd, enable then start the Promtail service:
   211  
   212  ```bash
   213  systemctl daemon-reload
   214  systemctl enable promtail.service
   215  systemctl start promtail.service
   216  ```
   217  
   218  You can verify that the service run correctly using the following command:
   219  
   220  ```bash
   221  systemctl status promtail.service -l
   222  
   223  ● promtail.service - Promtail
   224     Loaded: loaded (/etc/systemd/system/promtail.service; enabled; vendor preset: disabled)
   225     Active: active (running) since Wed 2020-07-08 15:48:57 UTC; 4s ago
   226   Main PID: 2732 (promtail-linux-)
   227     CGroup: /system.slice/promtail.service
   228             └─2732 /opt/promtail/promtail-linux-amd64 --config.file=./ec2-promtail.yaml
   229  
   230  Jul 08 15:48:57 ip-172-31-45-69.us-east-2.compute.internal systemd[1]: Started Promtail.
   231  Jul 08 15:48:57 ip-172-31-45-69.us-east-2.compute.internal systemd[1]: Starting Promtail...
   232  Jul 08 15:48:57 ip-172-31-45-69.us-east-2.compute.internal promtail-linux-amd64[2732]: level=warn ts=2020-07-08T15:48:57.559085451Z caller=filetargetmanager.go:98 msg="WARNING!!! entry_parser config is deprecated, please change to pipeline_stages"
   233  Jul 08 15:48:57 ip-172-31-45-69.us-east-2.compute.internal promtail-linux-amd64[2732]: level=info ts=2020-07-08T15:48:57.559869071Z caller=server.go:179 http=[::]:3100 grpc=[::]:35127 msg="server listening on addresses"
   234  Jul 08 15:48:57 ip-172-31-45-69.us-east-2.compute.internal promtail-linux-amd64[2732]: level=info ts=2020-07-08T15:48:57.56029474Z caller=main.go:67 msg="Starting Promtail" version="(version=1.6.0, branch=HEAD, revision=12c7eab8)"
   235  ```
   236  
   237  You can now verify in Grafana that Loki has correctly received your instance logs by using the [LogQL](../../../logql/) query `{zone="us-east-2"}`.
   238  
   239  ![Grafana Loki logs][ec2 logs]
   240  
   241  ## Sending systemd logs
   242  
   243  Just like we did with Promtail, you'll most likely manage your applications with [systemd][systemd] which usually store applications logs in [journald][journald]. Promtail actually support scraping logs from [journald][journald] so let's configure it.
   244  
   245  We will edit our previous config (`vi ec2-promtail.yaml`) and add the following block in the `scrape_configs` section.
   246  
   247  ```yaml
   248    - job_name: journal
   249      journal:
   250        json: false
   251        max_age: 12h
   252        path: /var/log/journal
   253        labels:
   254          job: systemd-journal
   255      relabel_configs:
   256        - source_labels: ['__journal__systemd_unit']
   257          target_label: 'unit'
   258  ```
   259  
   260  Note that you can use [relabeling][relabeling] to convert systemd labels to match what you want. Finally make sure that the path of journald logs is correct, it might be different on some systems.
   261  
   262  > You can download the final config example from our [GitHub repository][final config].
   263  
   264  That's it, save the config and you can `reboot` the machine (or simply restart the service `systemctl restart promtail.service`).
   265  
   266  Let's head back to Grafana and verify that your Promtail logs are available in Grafana by using the [LogQL](../../../logql/) query `{unit="promtail.service"}` in Explore. Finally make sure to checkout [live tailing][live tailing] to see logs appearing as they are ingested in Loki.
   267  
   268  [promtail]: ../../promtail/README
   269  [aws cli]: https://aws.amazon.com/cli/
   270  [create an vpc]: https://docs.aws.amazon.com/vpc/latest/userguide/vpc-subnets-commands-example.html
   271  [create an ssh key]: https://confluence.atlassian.com/bitbucketserver/creating-ssh-keys-776639788.html
   272  [GrafanaCloud]: https://grafana.com/signup/
   273  [terraform]: https://www.terraform.io/
   274  [cloud formation]: https://aws.amazon.com/fr/cloudformation/
   275  [ansible]: https://www.ansible.com/
   276  [chef]: https://www.chef.io/
   277  [security group]: https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html
   278  [Amazon Linux 2]: https://aws.amazon.com/amazon-linux-2/
   279  [promtail configuration]: ../../promtail/configuration
   280  [prometheus scrape config]: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#scrape_config
   281  [ec2_sd_config]: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#ec2_sd_config
   282  [role]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html
   283  [discovery page]: ./promtail-ec2-discovery.png "Service discovery"
   284  [relabel]: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#relabel_config
   285  [systemd]: https://www.freedesktop.org/software/systemd/man/systemd.service.html
   286  [logql]: ../../../logql
   287  [ec2 logs]: ./promtail-ec2-logs.png "Grafana Loki logs"
   288  [config gist]: https://gist.github.com/cyriltovena/d0881cc717757db951b642be48c01445
   289  [labels]: https://grafana.com/blog/2020/04/21/how-labels-in-loki-can-make-log-queries-faster-and-easier/
   290  [troubleshooting loki]: ../../../getting-started/troubleshooting#troubleshooting-targets
   291  [live tailing]: https://grafana.com/docs/grafana/latest/features/datasources/loki/#live-tailing
   292  [systemd]: ../../../installation/helm#run-promtail-with-systemd-journal-support
   293  [journald]: https://www.freedesktop.org/software/systemd/man/systemd-journald.service.html
   294  [final config]: https://github.com/grafana/loki/blob/master/docs/sources/clients/aws/ec2/promtail-ec2-final.yaml
   295  [relabeling]: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#relabel_config