forked from cloud-custodian/cloud-custodian
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
aws - ec2 - Infracost integration, add cost filter
- Loading branch information
Showing
7 changed files
with
773 additions
and
52 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
import os | ||
|
||
from c7n.cache import NullCache | ||
from gql import Client, gql | ||
from gql.transport.requests import RequestsHTTPTransport | ||
|
||
from .core import OPERATORS, Filter | ||
|
||
|
||
class Cost(Filter): | ||
"""Annotate resource monthly cost with Infracost pricing API. | ||
It aims to provide an approximate cost for a generic case. | ||
For example, it only grabs price of on-demand, no pre-installed softwares for EC2 instances. | ||
Please use INFRACOST_API_ENDPOINT and INFRACOST_API_KEY to specify API config. | ||
.. code-block:: yaml | ||
policies: | ||
- name: ec2-cost | ||
resource: ec2 | ||
filters: | ||
- type: cost | ||
op: greater-than | ||
value: 4 | ||
quantity: 730 | ||
reference: https://www.infracost.io/docs/cloud_pricing_api/overview/ | ||
""" | ||
|
||
schema = { | ||
'type': 'object', | ||
'additionalProperties': False, | ||
'required': ['type'], | ||
'properties': { | ||
'api_endpoint': {'type': 'string'}, | ||
'api_key': {'type': 'string'}, | ||
# 'currency': {'type': 'number'}, | ||
'quantity': {'type': 'number'}, | ||
'op': {'$ref': '#/definitions/filters_common/comparison_operators'}, | ||
'type': {'enum': ['cost']}, | ||
'value': {'type': 'number'}, | ||
}, | ||
} | ||
schema_alias = True | ||
ANNOTATION_KEY = "c7n:Cost" | ||
|
||
def __init__(self, data, manager=None): | ||
super().__init__(data, manager) | ||
self.cache = manager._cache or NullCache({}) | ||
self.api_endpoint = data.get( | ||
"api_endpoint", | ||
os.environ.get("INFRACOST_API_ENDPOINT", "https://pricing.api.infracost.io"), | ||
) | ||
self.api_key = data.get("api_key", os.environ.get("INFRACOST_API_KEY")) | ||
|
||
def get_permissions(self): | ||
return ("ec2:DescribeInstances",) | ||
|
||
def validate(self): | ||
name = self.__class__.__name__ | ||
if self.api_endpoint is None: | ||
raise ValueError("%s Filter requires Infracost pricing_api_endpoint" % name) | ||
|
||
if self.api_key is None: | ||
raise ValueError("%s Filter requires Infracost api_key" % name) | ||
return super(Cost, self).validate() | ||
|
||
def process_resource(self, resource, client, query): | ||
params = self.get_params(resource) | ||
cache_key = str(params) | ||
|
||
with self.cache: | ||
price = self.cache.get(cache_key) | ||
if not price: | ||
price = self.get_infracost(client, query, params) | ||
# TODO support configurable currency | ||
price["USD"] = float(price["USD"]) * self.data.get("quantity", 1) | ||
self.cache.save(cache_key, price) | ||
|
||
resource[self.ANNOTATION_KEY] = price | ||
op = self.data.get('operator', 'ge') | ||
value = self.data.get('value', -1) | ||
return OPERATORS[op](price["USD"], value) | ||
|
||
def get_infracost(self, client, query, params): | ||
result = client.execute(query, variable_values=params) | ||
self.log.info(f"Infracost {params}: {result}") | ||
return result["products"][0]["prices"][0] | ||
|
||
def process(self, resources, event=None): | ||
transport = RequestsHTTPTransport( | ||
url=self.api_endpoint + "/graphql", | ||
headers={'X-Api-Key': self.api_key}, | ||
verify=True, | ||
retries=3, | ||
) | ||
client = Client(transport=transport, fetch_schema_from_transport=True) | ||
query = gql(self.get_query()) | ||
return [r for r in resources if self.process_resource(r, client, query)] | ||
|
||
def get_query(self): | ||
raise NotImplementedError("use subclass") | ||
|
||
def get_params(self, resource): | ||
raise NotImplementedError("use subclass") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.