Skip to content

Instantly share code, notes, and snippets.

@chrolis
Last active May 7, 2019 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrolis/ce534e8c5717b372328930f6f3096635 to your computer and use it in GitHub Desktop.
Save chrolis/ce534e8c5717b372328930f6f3096635 to your computer and use it in GitHub Desktop.
EC2 インスタンス価格表を sqlite3 するやつ
import re
import sqlite3
from contextlib import closing
from typing import List
import requests
def insert(conn: sqlite3.Connection, prices: List):
c = conn.cursor()
for e in prices:
price = e['price']['USD']
attr = e['attributes']
# if attr['aws:ec2:currentGeneration'] != 'Yes':
# continue
# if attr['aws:ec2:ecu'] == 'Variable':
# continue
values = {
'type': attr['aws:ec2:instanceType'],
'ecu': attr['aws:ec2:ecu'],
'memory': re.match(r'([\d.]+)', attr['aws:ec2:memory']).group(1),
'ebs': -1,
'price': price,
}
if attr.get('aws:ec2:dedicatedEbsThroughput') is not None:
values['ebs'] = float(re.match(r'[^\d]*([\d.]+)', attr['aws:ec2:dedicatedEbsThroughput']).group(1))
values['ebs'] /= 8
c.execute('INSERT INTO ec2(type, ecu, memory, ebs_throughput, price) VALUES (?, ?, ?, ?, ?)',
tuple(values[k] for k in ('type', 'ecu', 'memory', 'ebs', 'price')))
conn.commit()
def main():
endpoints = [
'https://a0.p.awsstatic.com/pricing/1.0/ec2/region/ap-northeast-1/ondemand/linux/index.json',
'https://a0.p.awsstatic.com/pricing/1.0/ec2/region/ap-northeast-1/previous-generation/ondemand/linux/index.json',
]
with closing(sqlite3.connect('ec2-prices.sqlite3')) as conn:
conn.execute('DROP TABlE IF EXISTS ec2')
conn.execute('''
CREATE TABLE IF NOT EXISTS ec2 (
type varchar(64),
ecu float,
memory float,
ebs_throughput float,
price float
)
''')
conn.execute('DELETE FROM ec2')
for endpoint in endpoints:
r = requests.get(endpoint)
j = r.json()
insert(conn, j['prices'])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment