Showing posts with label AWS. Show all posts
Showing posts with label AWS. Show all posts

Tuesday, October 4, 2022

 

EKS change ownership of cluster.

Issue:
Your current user or role does not have access to Kubernetes objects on this EKS cluster

This may be due to the current user or role not having Kubernetes RBAC permissions to describe cluster resources or not having an entry in the cluster’s auth config map.

Root Cause:
When an EKS cluster created by an IAM user, the auth config map only recorded by that specific IAM user name. In such kind of scenario any other IAM user will not be able, read, write cluster properties even the account administrator.

Best practice:
AWS EKS best practice is the using separate IAM user/role to create or operate clusters to avoid such kind of scenarios.

Fix:


Please note that, you should have AWS administrator access to perform this.

Step 1: Get cluster creation role.

Either, we should know the cluster creation role or it should be retrieved by aws internal-control-plane. But none of AWS user do not have permission for this, hence, we have to get AWS technical support for this action.

Step 2: Generate new access key for cluster owner.

Please note that, this can be done only if cluster owner still exist in AWS IAM accounts,
Otherwise, create a new IAM user with the same name and proceed to next steps.

Goto AWS IAM service and select the cluster owner. Then select “Security Credentials tab“ below over there create new access key.

Step 3: Define cluster owner access ID to aws cli.

Edit ~/.aws/credentials file and include cluster owner programmatic access credentials over there.
First, backup your credentials as another profile and add cluster owner credentials as default.

Step 4: Verify active user.

aws sts get-caller-identity

Output should be like this, you should get the cluster owner arn in the ARN field :

{

"UserId": "AIDAQDUJLDNY5HP6BVNL5",

"Account": "007804230513",

"Arn": "arn:aws:iam::007804230513:user/kavishka"

}

Step 5: Change to kubeconfig to related cluster.

You need to update cluster config to the related cluster. In order to do that change name and region in following command.

aws eks update-kubeconfig --name bahasanlp --region ap-southeast-1

Step 6: Verify the cluster and nodes.

kubectl get nodes

Sample output:
NAME STATUS ROLES AGE VERSION

ip-192-168-17-164.ap-southeast-1.compute.internal Ready <none> 28d v1.19.6-eks-49a6c0

ip-192-168-182-188.ap-southeast-1.compute.internal Ready <none> 76d v1.19.6-eks-49a6c0

Step 7: Change the owner to the current user.

In following command define the cluster name, region and user arn of new user accordingly and execute the command.

eksctl create iamidentitymapping --cluster bahasanlp --region=ap-southeast-1 --arn arn:aws:iam::007804230513:user/kavishka --group system:masters --username admin

Step 8: Revert back aws auth config.

Edit ~/.aws/credentials file again and remove previous cluster owner credentials.

Step 9: Verify active user.

aws sts get-caller-identity

Output should be like this, you should get the cluster owner arn in the ARN field :

{

"UserId": "AIDAQDUJLDNY5HP6BVNL5",

"Account": "007804230513",

"Arn": "arn:aws:iam::007804230513:user/kavishka"

}

Step 6: Verify the access cluster and nodes.

kubectl describe cm aws-auth -n kube-system
If you have change the cluster owner successfully, the output must be like following,

Name: aws-auth
Namespace: kube-system
Labels: <none>
Annotations: <none>

Data

mapRoles:

  • groups:

    • system:bootstrappers

    • system:nodes
      rolearn: arn:aws:iam::007804230513:role/eksctl-airflow-nodegroup-workers-NodeInstanceRole-74NMVN4R9NC2
      username: system:node:{{EC2PrivateDNSName}}

mapUsers:

  • groups:

    • system:masters
      userarn: arn:aws:iam::007804230513:user/kavishka
      username: admin

Events: <none>


 

Thursday, May 12, 2022

AWS Firewall Manager

 

AWS Firewall Manager is a security management service which allows you to centrally configure and manage firewall rules across your accounts and applications in AWS Organizations. As new applications are created, Firewall Manager makes it easy to bring new applications and resources into compliance by enforcing a common set of security rules. Now you have a single service to build firewall rules, create security policies, and enforce them in a consistent, hierarchical manner across your entire infrastructure, from a central administrator account.
Using AWS Firewall Manager, you can easily roll out AWS WAF rules for your Application Load Balancers, API Gateways, and Amazon CloudFront distributions. You can create AWS Shield Advanced protections for your Application Load Balancers, ELB Classic Load Balancers, Elastic IP Addresses and CloudFront distributions. You can also configure new Amazon Virtual Private Cloud (VPC) security groups and audit any existing VPC security groups for your Amazon EC2, Application Load Balancer (ALB) and ENI resource types. You can deploy AWS Network Firewalls across accounts and VPCs in your organization. Finally, with AWS Firewall Manager, you can also associate your VPCs with Amazon Route 53 Resolvers DNS Firewall rules.


Benefits


Firewall Manager provides these benefits:
  • Helps to protect resources across accounts
  • Helps to protect all resources of a particular type, such as all Amazon CloudFront distributions
  • Helps to protect all resources with specific tags
  • Automatically adds protection to resources that are added to your account
  • Allows you to subscribe all member accounts in an AWS Organizations organization to AWS Shield Advanced, and automatically subscribes new in-scope accounts that join the organization
  • Allows you to apply security group rules to all member accounts or specific subsets of accounts in an AWS Organizations organization, and automatically applies the rules to new in-scope accounts that join the organization
  • Lets you use your own rules, or purchase managed rules from AWS Marketplace
Firewall Manager is particularly useful when you want to protect your entire organization rather than a small number of specific accounts and resources, or if you frequently add new resources that you want to protect. Firewall Manager also provides centralized monitoring of DDoS attacks across your organization.

AWS Firewall Manager handles five types of protection policies - AWS WAF, AWS Shield Advanced, Amazon VPC security groups, AWS Network Firewall, and Amazon Route 53 Resolver DNS Firewall. AWS Firewall Manager protection policies are priced with a monthly fee per region (prorated hourly).


For AWS Network Firewall protection policies, AWS Firewall Manager has these main pricing components:
  • AWS Firewall Manager protection policy - Monthly fee per Region.
  • AWS Network Firewall endpoints - Those created by Firewall Manager will be charged based on current pricing. For more details, see AWS Network Firewall pricing.
  • AWS Config Rules - Those rules created by Firewall Manager to monitor changes in resource configurations are charged based on current pricing. For more details, see AWS Config pricing.
You only pay for what you use, as you use it; there are no minimum fees and no upfront commitments


For AWS WAF protection policies, AWS Firewall Manager has these main pricing components:
  • AWS Firewall Manager protection policy - Monthly fee per Region.
  • AWS WAF WebACLs or Rules - Those created by Firewall Manager will be charged based on current pricing. For more details, see AWS WAF pricing.
  • AWS Config Rules - Those rules created by Firewall Manager to monitor changes in resource configurations are charged based on current pricing. For more details, see AWS Config pricing.
If you are an AWS Shield Advanced customer:
For AWS Shield Advanced customers, AWS Firewall Manager protection policy is included at no additional charge. Shield Advanced customers will be charged for the AWS Config rules created to monitor any changes in resource configurations. For more details, check the AWS Shield pricing and AWS Config pricing.

AWS Shield protection policies can be created using AWS Firewall Manager only for Shield Advanced users. The price is included in the AWS Shield Advanced subscription at no additional cost. In addition, the pricing components are as follows:
• AWS Shield Advanced Data Transfer Out Usage Fees: For more details, see AWS Shield pricing
• AWS Config Rules - Those rules created by Firewall Manager to monitor changes in resource configurations are charged based on current pricing. For more details, see AWS Config pricing


For Amazon VPC security group protection policies, AWS Firewall Manager has these main pricing components:
• AWS Firewall Manager protection policy - Monthly fee per Region.
• AWS Config Rules - Those rules created by Firewall Manager to monitor changes in resource configurations are charged based on current pricing. For more details, see AWS Config pricing.
You only pay for what you use, as you use it; there are no minimum fees and no upfront commitments.

For Amazon Route 53 Resolver DNS Firewall protection policies, AWS Firewall Manager has these main pricing components:
  • AWS Firewall Manager protection policy - Monthly fee per Region.
  • Route 53 Resolver DNS Firewall charges- Rule groups created by Firewall Manager will be charged based on current pricing. For more details, see Route 53 Resolver DNS Firewall pricing.
  • AWS Config Rules - Those rules created by Firewall Manager to monitor changes in resource configurations are charged based on current pricing. For more details, see AWS Config pricing.
You only pay for what you use, as you use it; there are no minimum fees and no upfront commitments.


AWS Firewall Manager pricing for customers


AWS Network Firewall protection policy

All public regions


AWS WAF protection policy

All public regions
$100.00 per policy per Region
Global (Amazon CloudFront locations)
$100.00 per policy per Region


AWS Shield Advanced protection policy

All public regions
Included for Shield Advanced customers. No charge per policy per Region
Global (Amazon CloudFront locations)
Included for Shield Advanced customers. No charge per policy per Region
  • AWS WAF WebACLs or Rules created by Firewall Manager - Included. No additional charge.
  • AWS Config rules created by Firewall Manager - See AWS Config pricing
  • AWS Shield Advanced - See AWS Shield pricing


Amazon VPC security group protection policy

All public regions


Amazon Route 53 Resolver DNS Firewall protection policy

All public regions


AWS Firewall Manager prerequisites


This topic shows you how to get ready to administer AWS Firewall Manager. You use one Firewall Manager administrator account to manage all Firewall Manager security policies for your organization in AWS Organizations. Except where noted, perform the prerequisite steps using the account that you will use as the Firewall Manager administrator.
Before you use Firewall Manager for the first time, perform the following steps in sequence.
Topics
After you follow these steps, you can configure Firewall Manager to begin protecting your resources. For more information, see Getting started with AWS Firewall Manager AWS WAF policies.

Step 1: Join and configure AWS Organizations


To use Firewall Manager, your account must be a member of the organization in the AWS Organizations service where you want to use your Firewall Manager policies.
Note
For information about Organizations, see AWS Organizations User Guide.

To establish the required AWS Organizations membership and configuration
  1. Choose an account to use as the Firewall Manager administrator for the organization in Organizations.
  2. If your chosen account isn't already a member of the organization, have it join. Follow the guidance at Inviting an AWS account to join your organization.
  3. AWS Organizations has two available feature sets: consolidated billing features and all features. To use Firewall Manager, your organization must be enabled for all features. If your organization is configured only for consolidated billing, follow the guidance at Enabling All Features in Your Organization.

Step 2: Set the AWS Firewall Manager administrator account


This procedure uses the account and organization that you chose and configured in the preceding step.
When you set the Firewall Manager administrator account, Firewall Manager automatically sets it as the AWS Organizations Delegated Administrator for Firewall Manager. This allows Firewall Manager to access information about the organizational units (OUs). You can use OUs to specify the scope of your Firewall Manager policies. For more information about setting policy scope, see the guidance for the individual policy types under Creating an AWS Firewall Manager policy. For more information about Organizations and management accounts, see Managing the AWS Accounts in Your Organization.
To set the Firewall Manager administrator account
  1. Sign in to the AWS Management Console using an existing AWS Organizations management account. You can sign in using the account's root user (not recommended) or another IAM user or IAM role within the account that has equivalent permissions.
  2. Open the Firewall Manager console at https://console.aws.amazon.com/wafv2/fmsv2
.
Choose Get started.
Type the ID of the account that you've chosen to use as the Firewall Manager administrator.
Note
This account is given permission to create and manage Firewall Manager policies across all accounts within your organization.
Choose Set administrator.

Step 3: Enable AWS Config


To use Firewall Manager, you must enable AWS Config.
Note
You incur charges for your AWS Config settings, according to AWS Config pricing. For more information, see Getting Started with AWS Config.
To enable AWS Config for Firewall Manager
  1. Enable AWS Config for each of your AWS Organizations member accounts, including the Firewall Manager administrator account. For more information, see Getting Started with AWS Config.
  2. Enable AWS Config for each AWS Region that contains the resources that you want to protect. You can enable AWS Config manually, or you can use the AWS CloudFormation template "Enable AWS Config" at AWS CloudFormation StackSets Sample Templates.
  3. If you don't want to enable AWS Config for all resources, then you must enable the following according to the type of Firewall Manager policies that you use:
    • WAF policy – Enable Config for the resource types CloudFront Distribution, Application Load Balancer (choose ElasticLoadBalancingV2 from the list), API Gateway, WAF WebACL, WAF Regional WebACL, and WAFv2 WebACL. To enable AWS Config to protect a CloudFront distribution, you must be in the US East (N. Virginia) Region. Other Regions don't have CloudFront as an option.
    • Shield policy – Enable Config for the resource types Shield Protection, ShieldRegional Protection, Application Load Balancer, EC2 EIP, WAF WebACL, WAF Regional WebACL, and WAFv2 WebACL.
    • Security group policy – Enable Config for the resource types EC2 SecurityGroup, EC2 Instance, and EC2 NetworkInterface.
    • Network Firewall policy – Enable Config for the resource types NetworkFirewall FirewallPolicy, NetworkFirewall RuleGroup, EC2 VPC, EC2 InternetGateway, EC2 RouteTable, and EC2 Subnet.
    • DNS Firewall policy – Enable Config for the resource types DNSFirewall RuleGroup and EC2 VPC.


Step 4: For Network Firewall and DNS Firewall policies, enable resource sharing


To manage Firewall Manager Network Firewall and DNS Firewall policies, you must enable sharing with AWS Organizations in AWS Resource Access Manager. This allows Firewall Manager to deploy protections across your accounts when you create these policy types.
To enable sharing with AWS Organizations in AWS Resource Access Manager
If you run into problems with resource sharing, see the guidance at Resource sharing for Network Firewall and DNS Firewall policies.

Step 5: To use AWS Firewall Manager in Regions that are disabled by default


To use Firewall Manager in a Region that's disabled by default, you must enable the Region for both the management account of your AWS organization and the Firewall Manager administrator account.
For information about Regions that are disabled by default and how to enable them, see Managing AWS Regions in the AWS General Reference.
To enable a disabled Region
  • For both the Organizations management account and the Firewall Manager administrator account, follow the guidance at Enabling a Region in the AWS General Reference.


Managing the AWS Firewall Manager administrator


You use your Firewall Manager administrator account to manage your Firewall Manager policies. When you set the Firewall Manager administrator account, Firewall Manager automatically sets it as the AWS Organizations Delegated Administrator for Firewall Manager. This allows Firewall Manager to access information about the organizational units (OUs) that you use to specify the scope of your Firewall Manager policies. For more information about Organizations and management accounts, see Managing the AWS Accounts in Your Organization.
To begin using Firewall Manager, you set up your Firewall Manager administrator account and perform other required steps. To do this, follow the guidance under AWS Firewall Manager prerequisites.
This topic provides information and guidance for managing your existing administrator account.
Required settings for the Firewall Manager administrator
The Firewall Manager administrator account must have the following settings:
  • It must be a member of the organization in AWS Organizations where you want to apply your Firewall Manager policies.
  • It must be designated as the Firewall Manager administrator by the Organizations management account for the organization.


Prometheus high availability setup


Infrastructure design 


Why Auto scaling?


There are no in built availability solutions in Prometheus except prometheus operator and Thanos which are using in Kubernetes. Also since, Prometheus is a pull-based monitoring system it is more easy and suitable for setting up a ASG.

How do we backup running Prometheus data?


As Prometheus fundamentally runs on one machine, some may wish to take backups of their data. With Prometheus 1.x this was a slow and disruptive process, requiring Prometheus to be completely restarted. The good news is that, due to its new storage engine, Prometheus 2.1 has a much better way of doing this.
To use it, you must enable the Admin API endpoints when running Prometheus:

$ ./prometheus --storage.tsdb.path=data/ --web.enable-admin-api

Then you can use a simple HTTP POST request to ask for a snapshot:

 curl -XPOST http://localhost:9090/api/v1/admin/tsdb/snapshot
 
Here a few seconds later it has returned the name of the new snapshot in a JSON object. If you look under the snapshots directory of your data directory you'll see this snapshot:

$ cd data/snapshots
$ ls
20180119T172548Z-78ec94e1b5003cb


Then copy the snapshot to s3 using aws cli. This process is executing by every 5 minutes, via a crontab.

In the ASG ami we have setup another script to copy s3 data when the server is starting.
And prometheus will restore the backup it self by using following command in the crontab script.
 --storage.tsdb.path 

Challenges:


  1. Point push gateway metrics to backup metrics.
  2. Avoid alert conflictions. 

Solutions: 


  1. Setup dns and lamda function for push gateway or IP pool

IP Pool
DNS with lambda function
Easy to install
Complex 
Simple
Recommended method
Costing is High
Cost optimized
Need to setup alerting separatly
Alerting when auto scale

IP pool

IP
Server
10.200.6.122
asg-inc-prometheus-master
10.200.7.115
asg-inc-prometheus-master
10.200.6.168
asg-inc-prometheus-backup
10.200.7.156
asg-inc-prometheus-backup

  1. Use prometheus alertmanager for avoid false alerts.


SLAs, SLOs, SLIs word soup

There's a lot already written about topics:
If you are not familiar with these terms, I would strongly recommend reading the article from Google's SRE book on Service Level Objectives first.
In summary:
  • SLAs: Service Level Agreement
    • What service you commit to provide to users, with possible penalties if you are not able to meet it.
    • Example: "99.5%" availability.
    • Keyword: contract
  • SLOs: Service Level Objective
    • What you have internally set as a target, driving your measuring threshold (for example, on dashboards and alerting). In general, it should be stricter than your SLA.
    • Example: "99.9%" availability (the so called "three 9s").
    • Keyword: thresholds
  • SLIs: Service Level Indicators
    • What you actually measure, to assertain whether your SLOs are on/off-target.
    • Example: error ratios, latency
    • Keyword: metrics

SLOs are about time

So what does 99% availability mean? - It's not 1% of error ratio (percentage of failed http responses), but instead the percentage of time over a predefined period the service has been available.
In the dashboard above, the service went above 0.1% error ratio (0.001 in the y-axis) for 1 hour (the small red horizontal segment on top of the errors spike), thus giving a 99.4% availability over a 7 day period:
A key factor in this result is the time span you choose to measure availability (7 days in above example). Shorter periods are typically used as checkpoints for the engineering teams involved (for example, SRE and SWE) to track how the service is doing, while longer periods are usually used for review purposes by the organization / wider-team.
For example, if you set a 99.9% SLO, then the total time the service can be down would be the following:
  • during 30 days: 43 min (3/4 hours)
  • during 90 days: 129 min (~2 hours)
Another trivial "numbers fact" is that adding extra 9s to the SLO has an obvious exponential impact. See the following time fractions for a total 1 year period span:
  • 2×9s: 99%: 5250min (87hrs or 3.64days)
  • 3×9s: 99.9%: 525min (8.7hrs)
  • 4×9s: 99.99%: 52.5min
  • 5×9s: 99.999%: 5min <- rule of approximation: 5× 9s -> 5 mins (per year)
Enter error budgets
The above numbers for the allowed time a service can be down may be thought of as an error budget, which you consume from events such as the following:
  • planned maintenance
  • failed upgrades
  • unexpected outages
The practical outcome is that any of above will consume error budget from your service, for example, an unexpected outage may deplete it to the point of blocking further maintenance work during that time period.
SLIs are about metrics
From the above, it's clear that we must have service metrics to tell us when the service is considered (un)available. There are several approaches for this:

Example SLO implementation

Let's take a specific example, following the RED method (as the metrics we already have available are a better match for this approach): create alerts and dashboards to support a target SLO for the Kubernetes API, via tools commonly used for monitoring purposes: [Prometheus] and [Grafana].
Additionally we'll use [jsonnet] to build our rules and dashboards files, taking advantage of existing library helpers.
Rather than explaining how to signal when your service is out of the thresholds, this article focuses on how to record the time the service has been under this condition, as discussed in SLOs are about time section.
The rest of the article will focus on creating Prometheus rules to capture "time out of SLO", based on thresholds for specific metrics (SLIs).
Define the SLO target and metrics thresholds
Let's define a simple target:
  • SLO: 99%, from the following:
  • SLIs:
    • error ratio under 1%
    • latency under 200ms for 90th percentile of requests
Writing above spec as jsonnet (see [spec-kubeapi.jsonnet]):
slo:: {
  target: 0.99,
  error_ratio_threshold: 0.01,
  latency_percentile: 90,
  latency_threshold: 200,
},

Finding the SLIs

The Kubernetes API exposes several metrics we can use as SLIs, using the Prometheus rate() function over a short period (here we choose 5min, this number should be a few times your scraping interval):
  • apiserver_request_count: counts all the requests by verb, code, resource, e.g. to get the total error ratio for the last 5min:
sum(rate(apiserver_request_count{code=~"5.."}[5m]))
 /
sum(rate(apiserver_request_count[5m]))
  • The formula above discards all metrics labels (for example, by http verb, code). If you want to keep some labels, you'd need to do something similar to the following:
sum by (verb, code) (rate(apiserver_request_count{code=~"5.."}[5m]))
  / ignoring (verb, code) group_left
sum (rate(apiserver_request_count[5m]))
  • apiserver_request_latencies_bucket: latency histogram by verb. For example, to get the 90th latency quantile in milliseconds: (note that the le "less or equal" label is special, as it sets the histogram buckets intervals, see [Prometheus histograms and summaries][promql-histogram]):
histogram_quantile (
  0.90,
  sum by (le, verb, instance)(
    rate(apiserver_request_latencies_bucket[5m])
  )
) / 1e3
Learn more at:

Writing Prometheus rules to record the chosen SLIs

PromQL is a very powerful language, although as of October 2018, it doesn't yet support nested sub queries for ranges (see Prometheus issue 1227 for details), a feature we'll need to be able to compute time ratio for error ratio or latency outside their thresholds.
Also, as good practice, to lower query-time Prometheus resource usage, it is recommended to always add recording rules to precompute expressions such as sum(rate(...)) anyway.
As an example of how to do this, the following set of recording rules are built from our [bitnami-labs/kubernetes-grafana-dashboards] repository to capture the above time ratio:
  • Create a new kubernetes:job_verb_code_instance:apiserver_requests:rate5m metric to record requests rates:
record: kubernetes:job_verb_code_instance:apiserver_requests:rate5m
expr: |
  sum by(job, verb, code, instance) (rate(apiserver_request_count[5m]))
  • Using above metric, create a new kubernetes:job_verb_code_instance:apiserver_requests:ratio_rate5m for the requests ratios (over total):
record: kubernetes:job_verb_code_instance:apiserver_requests:ratio_rate5m
expr: |
  kubernetes:job_verb_code_instance:apiserver_requests:rate5m
    / ignoring(verb, code) group_left()
  sum by(job, instance) (
    kubernetes:job_verb_code_instance:apiserver_requests:rate5m
  )
  • Using above ratio metrics (for every http code and verb), create a new one to capture the error ratios:
record: kubernetes:job:apiserver_request_errors:ratio_rate5m
expr: |
  sum by(job) (
    kubernetes:job_verb_code_instance:apiserver_requests:ratio_rate5m
      {code=~"5..",verb=~"GET|POST|DELETE|PATCH"}
  )
  • Using above error ratios (and other similarly created kubernetes::job:apiserver_latency:pctl90rate5m one for recorded 90th percentile latency over the past 5mins, not shown above for simplicity), finally create a boolean metric to record our SLO complaince:
record: kubernetes::job:slo_kube_api_ok
expr: |
  kubernetes:job:apiserver_request_errors:ratio_rate5m < bool 0.01
    *
  kubernetes::job:apiserver_latency:pctl90rate5m < bool 200

Writing Prometheus alerting rules

The above kubernetes::job:slo_kube_api_ok final metric is very useful for dashboards and accounting for SLO compliance, but we should alert on which of above metrics is driving the SLO off, as shown the following Prometheus alert rules:
  • Alert on high API error ratio:
alert: KubeAPIErrorRatioHigh
expr: |
  sum by(instance) (
    kubernetes:job_verb_code_instance:apiserver_requests:ratio_rate5m
      {code=~"5..",verb=~"GET|POST|DELETE|PATCH"}
  ) > 0.01
for: 5m
  • Alert on high API latency
alert: KubeAPILatencyHigh
expr: |
  max by(instance) (
    kubernetes:job_verb_instance:apiserver_latency:pctl90rate5m
      {verb=~"GET|POST|DELETE|PATCH"}
  ) > 200
for: 5m
Note that the Prometheus rules are taken from the already manifested jsonnet output, which can be found in [our sources][bitnami-labs/kubernetes-grafana-dashboards] and the thresholds are evaluated from $.slo.error_ratio_threshold and $.slo.latency_threshold respectively.

Programmatically creating Grafana dashboards

Creating Grafana dashboards is usually done by interacting with the UI. This is fine for simple and/or "standard" dashboards (as for example, downloaded from https://grafana.com/dashboards), but becomes cumbersome if you want to implement best devops practices, especially for gitops workflows.
The community is addressing this issue via efforts, such as Grafana libraries for jsonnet, python, and Javascript. Given our jsonnet implementation, we chose grafonnet-lib.
One very useful outcome of using jsonnet to set our SLO thresholds and code our Prometheus rules, is that we can re-use these to build our Grafana dashboards, without having to copy and paste them, that is, we keep a single source of truth for these.
For example:
  • referring to $.slo.error_ratio_threshold in our Grafana dashboards to set Grafana graph panel's thresholds property, as we did above for our Prometheus alert rules.
  • referring to created Prometheus recorded rules via jsonnet, an excerpt from [spec-kubeapi.jsonnet], note the metric.rules.requests_ratiorate_job_verb_code.record usage (instead of verbatim 'kubernetes:job_verb_code_instance:apiserver_requests:ratio_rate5m'):
// Graph showing all requests ratios
req_ratio: $.grafana.common {
  title: 'API requests ratios',
  formula: metric.rules.requests_ratiorate_job_verb_code.record,
  legend: '{{ verb }} - {{ code }}',
},
You can read our implementation at dash-kubeapi.jsonnet, the following is a screenshot of the resulting dashboard:

Putting it all together

We implemented above ideas in our bitnami-labs/kubernetes-grafana-dashboards repository, under the jsonnet folder.
Our built Prometheus rules and Grafana dashboard files get produced from the jsonnet sources as the following:
  • [spec-kubeapi.jsonnet]\: as much data-only specification as possible (thresholds, rules and dashboards formulas)
Since we started this project, many other useful Prometheus rules have been created by the community. Check srecon17_americas_slides_wilkinson.pdf for more information on this. If we had to start from scratch again, we'd likely be using the kubernetes-mixin together with jsonnet-bundler.

Alert Manager


The Alertmanager handles alerts sent by client applications such as the Prometheus server. It takes care of deduplicating, grouping, and routing them to the correct receiver integration such as email, PagerDuty, or OpsGenie. It also takes care of silencing and inhibition of alerts.
The following describes the core concepts the Alertmanager implements. Consult the configuration documentation to learn how to use them in more detail.

Grouping

Grouping categorizes alerts of similar nature into a single notification. This is especially useful during larger outages when many systems fail at once and hundreds to thousands of alerts may be firing simultaneously.
Example: Dozens or hundreds of instances of a service are running in your cluster when a network partition occurs. Half of your service instances can no longer reach the database. Alerting rules in Prometheus were configured to send an alert for each service instance if it cannot communicate with the database. As a result hundreds of alerts are sent to Alertmanager.
As a user, one only wants to get a single page while still being able to see exactly which service instances were affected. Thus one can configure Alertmanager to group alerts by their cluster and alertname so it sends a single compact notification.
Grouping of alerts, timing for the grouped notifications, and the receivers of those notifications are configured by a routing tree in the configuration file.

Inhibition

Inhibition is a concept of suppressing notifications for certain alerts if certain other alerts are already firing.
Example: An alert is firing that informs that an entire cluster is not reachable. Alertmanager can be configured to mute all other alerts concerning this cluster if that particular alert is firing. This prevents notifications for hundreds or thousands of firing alerts that are unrelated to the actual issue.
Inhibitions are configured through the Alertmanager's configuration file.

Silences

Silences are a straightforward way to simply mute alerts for a given time. A silence is configured based on matchers, just like the routing tree. Incoming alerts are checked whether they match all the equality or regular expression matchers of an active silence. If they do, no notifications will be sent out for that alert.
Silences are configured in the web interface of the Alertmanager.

Client behavior

The Alertmanager has special requirements for behavior of its client. Those are only relevant for advanced use cases where Prometheus is not used to send alerts.

High Availability

Alertmanager supports configuration to create a cluster for high availability. This can be configured using the --cluster-* flags.
It's important not to load balance traffic between Prometheus and its Alertmanagers, but instead, point Prometheus to a list of all Alertmanagers.

Push Gateway Configurations


Install Pushgateway

Get the latest version of pushgateway from prometheus.io, then download and extract:
Create the pushgateway user:
$ useradd --no-create-home --shell /bin/false pushgateway
Move the binary in place and update the permissions to the user that we created:
$ cp pushgateway-0.8.0.linux-amd64/pushgateway /usr/local/bin/pushgateway
$ chown pushgateway:pushgateway /usr/local/bin/pushgateway
Create the systemd unit file:
$ cat > /etc/systemd/system/pushgateway.service << EOF
[Unit]
Description=Pushgateway
Wants=network-online.target
After=network-online.target

[Service]
User=pushgateway
Group=pushgateway
Type=simple
ExecStart=/usr/local/bin/pushgateway \
    --web.listen-address=":9091" \
    --web.telemetry-path="/metrics" \
    --persistence.file="/tmp/metric.store" \
    --persistence.interval=5m \
    --log.level="info" \
    --log.format="logger:stdout?json=true"

[Install]
WantedBy=multi-user.target
EOF
Reload systemd and restart the pushgateway service:
$ systemctl daemon-reload
$ systemctl restart pushgateway
Ensure that pushgateway has been started:
$ systemctl status pushgateway
  pushgateway.service - Pushgateway
   Loaded: loaded (/etc/systemd/system/pushgateway.service; disabled; vendor preset: enabled)
   Active: active (running) since Tue 2019-05-07 09:05:57 UTC; 2min 33s ago
 Main PID: 6974 (pushgateway)
    Tasks: 6 (limit: 4704)
   CGroup: /system.slice/pushgateway.service
           └─6974 /usr/local/bin/pushgateway --web.listen-address=:9091 --web.telemetry-path=/metrics --persistence.file=/tmp/metric.store --persistence.interval=5m --log.level=info --log.format=logger:st

May 07 09:05:57 ip-172-31-41-126 systemd[1]: Started Pushgateway.

Configure Prometheus

Now we want to configure prometheus to scrape pushgateway for metrics, then the scraped metrics will be injected into prometheus’s time series database:
At the moment, I have prometheus, node-exporter and pushgateway on the same node so I will provide my complete prometheus configuration, If you are just looking for the pushgateway config, it will be the last line:
$ cat /etc/prometheus/prometheus.yml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'prometheus'
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:9090']

  - job_name: 'node_exporter'
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:9100']

  - job_name: 'pushgateway'
    honor_labels: true
    static_configs:
      - targets: ['localhost:9091']
Restart prometheus:
$ systemctl restart prometheus

Push metrics to pushgateway

First we will look at a bash example to push metrics to pushgateway:
Have a look at pushgateway’s metrics endpoint:
# TYPE cpu_utilization untyped
cpu_utlization{instance="10.20.0.1:9000",job="my_custom_metrics",provider="hetzner"} 20.25
Springboot pushgateway documentation

With this method, you can push any custom metrics (bash, lambda function, etc) to pushgateway and allow prometheus to consume that data into it’s time series database.

Update openSSL to latest 1.1.1 version (1.1.1w)

  By the time(2024) one our system use this old OpenSSL version 1.1.1g and we are going to update it to latest version of 1.1.1 openSSL v...