かべぎわブログ

ブログです

Terraformで最新版のAmazonLinux2を取得する

概要

Terraformで最新版のAmazonLinux2をつかってEC2インスタンスを作成します。

こんなかんじ

filterでしぼっています。

provider "aws" {
  region = "ap-northeast-1"
}

data "aws_ami" "recent_amazon_linux2" {
    most_recent = true
    owners = ["amazon"]

    filter {
        name = "state"
        values = ["available"]
    }
    filter {
        name = "name"
        values = ["amzn2-ami-hvm-2.0.*"]
    }
}

resource "aws_instance" "wawawa" {
    ami = data.aws_ami.recent_amazon_linux2.image_id
    instance_type = "t3.micro"
}

おわりに

べんりですね

Terraform: Up & Running: Writing Infrastructure as Code (English Edition)

Terraform: Up & Running: Writing Infrastructure as Code (English Edition)

  • 作者:Yevgeniy Brikman
  • 出版社/メーカー: O'Reilly Media
  • 発売日: 2019/09/06
  • メディア: Kindle版

Terraformで変数をつかう

概要

Terraformで変数をつかってみます。
variableを使うと変数が定義できます。

きほんのかたち

インスタンスタイプをt3.microの変数を設定している。

provider "aws" {
  region = "ap-northeast-1"
}
variable "instance_type" {
    default = "t3.micro"
}
resource "aws_instance" "wawawa" {
    ami = "ami-068a6cefc24c301d2"
    instance_type = var.instance_type
}

こうなる

$ terraform plan | grep instance_type
      + instance_type                = "t3.micro"

-varオプションで上書き

-var オプションで上書きできます。

$ terraform plan -var 'instance_type=t3.medium' | grep instance_type
      + instance_type                = "t3.medium"

TF_VAR_wawawa環境変数で上書き

環境変数で上書きできます。
TF_VAR_wawawaという名前の環境変数を定義してあげると、それを読み込んでくれます。

$ export TF_VAR_instance_type=t3.large
$ echo ${TF_VAR_instance_type}
t3.large

$ terraform plan | grep instance_type
      + instance_type                = "t3.large"

ローカル変数で上書きされないようにする

ローカル変数をつかうと、上書きできないようになります。
こんなかんじで定義してあげます。

provider "aws" {
  region = "ap-northeast-1"
}
locals {
    instance_type = "t3.micro"
}
resource "aws_instance" "wawawa" {
    ami = "ami-068a6cefc24c301d2"
    instance_type = local.instance_type
}

おわりに

いろいろありますね

Terraform: Up and Running: Writing Infrastructure as Code

Terraform: Up and Running: Writing Infrastructure as Code

  • 作者:Yevgeniy Brikman
  • 出版社/メーカー: O'Reilly Media
  • 発売日: 2017/04/04
  • メディア: ペーパーバック

Pythonでコンソールのサイズを取得する

概要

Pythonを利用してコンソールのサイズを取得してみたいと思います。

こんなかんじ

こんなかんじです

import os
columns,lines = os.get_terminal_size() 

ゆーすけーす

こんなかんじでぼくはつかっている
こうすることでコンソールサイズがどんなかんじであろうと1行分*を出してくれる。
人間にみやすくなってよいです。

import os

columns,lines = os.get_terminal_size() 
print('*' * columns) 

こんなかんじでprintされる。

*******************************************************************************************************************************

Ansibleみ

みたいな

import os

columns,lines = os.get_terminal_size() 

title = 'PLAY [localhost]'
length = columns - len(title) - 1

print(title,'*' * length)

こんなかんじでprintされる。

PLAY [localhost] **************************************************************************************************************

おわりに

べんりですね

Excel×Python最速仕事術

Excel×Python最速仕事術

S3バケットの中のオブジェクトを数えてくれるPythonをかきました

概要

S3バケットの中にあるオブジェクトを数えてくれるPythonをかきました。

これです

これです
値はCloudWatchメトリクスから持ってきています。
github.com

つかいかた

こうやってつかうのだ

$ python get_object_count.py --help
usage: get_object_count.py [-h] --bucket BUCKET [--profile [PROFILE]]

optional arguments:
  -h, --help           show this help message and exit
  --profile [PROFILE]  Use a specific profile from your credential file.

required arguments:
  --bucket BUCKET      The name of the bucket name.
$ python ./get_object_count.py --bucket mybucket
12 Count

おわりに

aws s3 ls s3://mybucket --recursive --human --sumとかやらなくていいです。

Amazon Web Servicesインフラサービス活用大全 システム構築/自動化、データストア、高信頼化 (impress top gear)

Amazon Web Servicesインフラサービス活用大全 システム構築/自動化、データストア、高信頼化 (impress top gear)

  • 作者: Michael Wittig,Andreas Wittig,株式会社クイープ
  • 出版社/メーカー: インプレス
  • 発売日: 2019/09/05
  • メディア: 単行本(ソフトカバー)
  • この商品を含むブログを見る

CloudWatch Logs InsightsでLambdaの実行時間の長いものを取得する

関数

CloudWatch Logs InsightsをつかってLambda関数の実行時間の長いものを取得してみたいと思います。

やってみる

やってみる。

クエリ

クエリはこんなかんじです。

filter @type = "REPORT"
| fields @requestId, @billedDuration, @duration
| sort by @duration desc
| limit 10

実行時間を確認したいLambdaのロググループを選択して [クエリの実行]すると以下のように結果がでてきます。
f:id:kabegiwakun:20191122065053p:plain

おわりに

べんりですね

AWS認定資格試験テキスト AWS認定 ソリューションアーキテクト-アソシエイト

AWS認定資格試験テキスト AWS認定 ソリューションアーキテクト-アソシエイト

  • 作者: NRIネットコム株式会社,佐々木拓郎,林晋一郎,金澤圭
  • 出版社/メーカー: SBクリエイティブ
  • 発売日: 2019/04/20
  • メディア: 単行本
  • この商品を含むブログを見る

DockerでCentOS8のAWSCLI環境を作成する

概要

DockerでCentOS8のイメージをつかってAWSCLIの動作環境を作ってみたいと思います。

Dockerfile

こんなかんじ。

FROM centos:8

RUN dnf install -y wget python3

RUN wget https://bootstrap.pypa.io/get-pip.py
RUN python3 get-pip.py

RUN pip install awscli

ENV PATH $PATH:/root/.local/bin

CentOS8ではPythonがインストールされていないため、そのインストールからはじめている。
インストールはyumではなくdnfをつかっています。

やってみる

やってみます。

buildする

buildします。

$ ls
Dockerfile

$ docker build -t awscli .

runして中にはいってみる

起動して中に入ってみます

$ docker run -it awscli

AWSCLIがはいっていることがわかります。

$ aws --version
aws-cli/1.16.287 Python/3.6.8 Linux/4.9.184-linuxkit botocore/1.13.23

おわりに

おわり

Docker実践ガイド 第2版 impress top gearシリーズ

Docker実践ガイド 第2版 impress top gearシリーズ

S3バケットのサイズを取得してくれるPythonをかいた

概要

S3バケットのサイズ(オブジェクトのサイズの合計)を取得してくれます。
CloudWatchメトリクスの値をもとにしています。

コード

これです。 github.com

つかいかた

usage: 'get_bucket_size.py [-h] --bucket BUCKET [--profile [PROFILE]]

optional arguments:
  -h, --help           show this help message and exit
  --profile [PROFILE]  Use a specific profile from your credential file.

required arguments:
  --bucket BUCKET      The name of the bucket name.

こんなかんじで表示されます。

$ python ./get_bucket_size.py --bucket mybucket
6487.0 Bytes

おわりに

おわり

Amazon Web Services パターン別構築・運用ガイド 改訂第2版

Amazon Web Services パターン別構築・運用ガイド 改訂第2版

  • 作者: NRIネットコム株式会社,佐々木拓郎,林晋一郎,小西秀和,佐藤瞬
  • 出版社/メーカー: SBクリエイティブ
  • 発売日: 2018/03/23
  • メディア: Kindle版
  • この商品を含むブログを見る

AWSマネジメントコンソールのヘッダーに色をつけるChrome/Firefox拡張

概要

AWSのマネジメントコンソールのヘッダーに色つけてくれるChrome/Firefox拡張です。
AWS console regions colorです。
リージョンがわかりやすくなります。

まねこんポチポチしてたらオレゴンにインスタンスつくってたわみたいなことがたぶんなくなります。

Chrome

chrome.google.com

Firefox

addons.mozilla.org

こんなかんじ

こんなかんじになります。
デフォルトだと東京はこうで
f:id:kabegiwakun:20191112064428p:plain

オレゴンがこうです。
f:id:kabegiwakun:20191112090902p:plain
わかりやすいですね

カスタマイズもできる

いろがきにいらなければ変更できます。
f:id:kabegiwakun:20191112064639p:plain

おわりに

わかりやすいですね

徹底攻略 AWS認定 ソリューションアーキテクト ? アソシエイト教科書 徹底攻略シリーズ

徹底攻略 AWS認定 ソリューションアーキテクト ? アソシエイト教科書 徹底攻略シリーズ

オブジェクトをすべて削除してからS3バケットを削除してくれるPythonをかきました

概要

かんたんにS3バケットを削除してくれるPythonをかきました。

バケットを削除するときはすべてのオブジェクトを削除してからじゃないと削除できなくてめんどくさいなーってかんじだったのでかいた。

スクリプト

これです。
github.com

import boto3, argparse

class s3():
    def __init__(self, bucket_name, profile='default'):
        self.session = boto3.Session(profile_name=profile)
        self.s3 = self.session.resource('s3')
        self.bucket = self.s3.Bucket(bucket_name)

    def delete_all_object(self):
        self.s3_objects = list(self.bucket.objects.all())
        for self.s3_object in self.s3_objects:
            self.s3_object.delete()

    def delete_all_object_versions(self):
        self.s3_object_versions = list(self.bucket.object_versions.all())
        for self.s3_object_version in self.s3_object_versions:
            self.s3_object_version.delete()

    def delete_bucket(self):
        self.bucket.delete()

    def delete(self):
        self.delete_all_object()
        self.delete_all_object_versions()
        self.delete_bucket()


def main():
    s3(bucket_name, profile).delete()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(prog=__file__)
    required = parser.add_argument_group('required arguments')
    optional = parser.add_argument_group('optional arguments')
    required.add_argument('--bucket',required=True, help='The name of the bucket name.')
    optional.add_argument('--profile',nargs='?',default='default',help='Use a specific profile from your credential file.')
    
    args = parser.parse_args()
    bucket_name = args.bucket
    profile = args.profile

    main()

こんなかんじでつかう

$ python delete_bucket.py --bucket mybucket

おわりに

間違ったバケットを消さないよう注意

Amazon Web Services エンタープライズ基盤設計の基本

Amazon Web Services エンタープライズ基盤設計の基本

S3上のアーカイブファイルの中身を展開して出力してくれるPythonを書きました

概要

S3上のアーカイブファイルの中身を展開して出力してくれるPythonを書きました。

github.com

つかいかた

$ python uncomp_s3.py --help

usage: uncomp_s3.py [-h] [--profile [PROFILE]] path

required arguments:
  path                 example s3://mybucket/archive.zip

optional arguments:
  --profile [PROFILE]  Use a specific profile from your credential file.

こんなかんじでつかう

tarfile

$ ls archive.tar.gz
archive.tar.gz

$ tar tvfz archive.tar.gz
-rw-rw-rw- kabegiwa/kabegiwa 7 2019-01-12 14:46 wawawa.txt
-rw-rw-rw- kabegiwa/kabegiwa 0 2019-11-07 07:15 sasasa.txt

$ aws s3 cp archive.tar.gz s3://mybucket/archive.tar.gz
$ aws s3 ls s3://mybucket/archive.tar.gz
2019-11-07 07:21:34        119 archive.tar.gz

$ python uncomp_s3.py s3://mybucket/archive.tar.gz
wawawa.txt
sasasa.txt

zipfile

$ ls archive.zip
archive.zip

$ unzip -Z archive.zip
Archive:  archive.zip
Zip file size: 325 bytes, number of entries: 2
-rw-rw-rw-  3.0 unx        7 tx stor 19-Jan-12 14:46 wawawa.txt
-rw-rw-rw-  3.0 unx        0 bx stor 19-Nov-07 07:15 sasasa.txt
2 files, 7 bytes uncompressed, 7 bytes compressed:  0.0%

$ aws cp archive.tar.gz s3://mybucket/archive.zip
$ aws s3 ls s3://mybucket/archive.zip
2019-11-07 07:21:34        119 archive.zip

$ python uncomp_s3.py s3://mybucket/archive.zip
wawawa.txt
sasasa.txt

おわりに

べんりですね

東京大学のデータサイエンティスト育成講座

東京大学のデータサイエンティスト育成講座

CLIでうごくAuthenticatorをつくりました

概要

CLIでうごくAuthenticatorをつくりました
これです

github.com

つかいかた

こんなかんじ

$ python ./auth.py --help
usage: ./auth.py [-h] [--name NAME]

optional arguments:
  --name NAME  Name of AWS account (default: ALL)

オプションを指定しないと設定ファイル(keys.yml)に指定したキーをすべて出力します。

$ python ./auth.py
DNS 646248
WEB 396959
DX 920731

指定してあげるとそのキーのみ出力してくれます。

$ python ./auth.py --name DNS
031876

こんなかんじでコマンドにわたしてあげることもできます。

$ scripts_require_MFA.sh < python ./auth.py --name DNS

設定ファイルは名前とキーをしていしてあげるだけです。

$ cat keys.yml
---
DNS:
  name: DNS
  key: MfaSecretKeyDNS
WEB:
  name: WEB
  key: MfaSecretKeyWEB
DX:
  name: DX
  key: MfaSecretKeyDXX

おわりに

べんりですね

AZIDを確認する方法

概要

AZIDを確認する方法まとめです。

マネジメントコンソール

Resource Access Managerから確認することができます。
f:id:kabegiwakun:20191025065956p:plain

AWSCLI

こんなかんじで確認できます。

aws ec2 describe-availability-zones
{
    "AvailabilityZones": [
        {
            "State": "available",
            "Messages": [],
            "RegionName": "ap-northeast-1",
            "ZoneName": "ap-northeast-1a",
            "ZoneId": "apne1-az4"
        },
        {
            "State": "available",
            "Messages": [],
            "RegionName": "ap-northeast-1",
            "ZoneName": "ap-northeast-1c",
            "ZoneId": "apne1-az1"
        },
        {
            "State": "available",
            "Messages": [],
            "RegionName": "ap-northeast-1",
            "ZoneName": "ap-northeast-1d",
            "ZoneId": "apne1-az2"
        }
    ]
}

この1冊で合格! AWS認定ソリューションアーキテクト - アソシエイト テキスト&問題集

この1冊で合格! AWS認定ソリューションアーキテクト - アソシエイト テキスト&問題集

  • 作者: アクセンチュア株式会社,青柳雅之,飯田敏樹,柿沼力,門畑顕博,他
  • 出版社/メーカー: KADOKAWA
  • 発売日: 2019/07/20
  • メディア: 単行本
  • この商品を含むブログを見る

motoでboto3のテストをする

概要

motoをつかってboto3のテストをしてみたいと思います。

そもそもmotoとは

AWSサービスのモックをつくることができるやつです。
mock botoでmotoです(たぶん)

motoでテストしてみる

実際にやってみます。
こんかいはS3にオブジェクトを置くスクリプトのテストをしてみます。

motoのインストール

pipでできます。

pip install moto

テストされる.py

S3にオブジェクトを置くだけのスクリプトです。

import boto3

class s3(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

    def put(self):
        s3 = boto3.client('s3', region_name='ap-northeast-1')
        s3.put_object(Bucket='mybucket', Key=self.name, Body=self.value)

テストする.py

オブジェクトをGETして中身が正しいかどうかを確かめています。
kabegiwa_blogという名前のオブジェクトの中身がawesomeであればOKです。

import boto3
from moto import mock_s3
from put_object import s3


@mock_s3
def test_put_object():
    conn = boto3.resource('s3', region_name='ap-northeast-1')
    conn.create_bucket(Bucket='mybucket')

    model_instance = s3('kabegiwa_blog', 'is awesome')
    model_instance.put()

    body = conn.Object('mybucket', 'kabegiwa_blog').get()['Body'].read().decode("utf-8")

    assert body == 'is awesome'

test_put_object()

実際にテストしてみる

テストしてみます。
テストする.pyを実行します。
わかりやすくするためにpytestを利用します。

pytestについてはまえにかきました。

www.kabegiwablog.com

テストがとおっていることがわかる。

pytest -v test_put_object.py

=== test session starts ===
platform win32 -- Python 3.7.4, pytest-5.2.1, py-1.8.0, pluggy-0.13.0 -- c:\users\takak\appdata\local\programs\python\python37-32\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\takak\Downloads\moto_test
collected 1 item

test_put_object.py::test_put_object PASSED                                                                       [100%]

テストする.pyのassertの部分を以下のように変えてもう一度テストしてみます。

    assert body == 'is not awesome'

テスト実行するとエラーになっていることがわかります。

pytest -v .\test_put_object.py

=== test session starts ===
platform win32 -- Python 3.7.4, pytest-5.2.1, py-1.8.0, pluggy-0.13.0 -- c:\users\takak\appdata\local\programs\python\python37-32\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\takak\Downloads\moto_test
collected 0 items / 1 errors

=== ERRORS ===
____ ERROR collecting test_put_object.py ___
test_put_object.py:18: in <module>
    test_put_object()
..\..\appdata\local\programs\python\python37-32\lib\site-packages\moto\core\models.py:80: in wrapper
    result = func(*args, **kwargs)
test_put_object.py:16: in test_put_object
    assert body == 'is not awesome'
E   AssertionError: assert 'is awesome' == 'is not awesome'

結局なにこれ?

mockなのでmybucketというAWSサービスはつくられていないです。
そしてオブジェクトも作成されていないです。
というかそんなバケット名はたぶんもうすでにつかわれているのでつくれないです。

でもなぜテストがとおったか(バケットからオブジェクトをGETできたか)というとmotoが仮想的にmockをつくって応答してくれているからです。

boto3のテストを実施するときはだいたいスクリプトを動かしてはAWSリソースを消してーとか、既存のものに影響がないように気をつけなくちゃーとかやっていたけれど、これを使うことでそういうことを気にしなくて良くなります。

注意点

すべてのAWSリソースがテストできるわけではないです
以下にいろいろかいてあります。
github.com

おわりに

kabegiwa_blog is awesome.

テスト駆動開発

テスト駆動開発

PowerShellでhistoryを表示する

概要

PowerShellでコマンド履歴を表示します。

コマンド

こうすればみれる

PS1> Get-History

  Id CommandLine
  -- -----------
   1 echo 'wawawa'
   2 echo 'sasasa'
   3 echo 'dadada'

おわりに

わすれがち

Windows PowerShellクックブック

Windows PowerShellクックブック

  • 作者: Lee Holmes,マイクロソフト株式会社ITプロエバンジェリストチーム(監訳),菅野良二
  • 出版社/メーカー: オライリージャパン
  • 発売日: 2008/10/23
  • メディア: 大型本
  • 購入: 4人 クリック: 72回
  • この商品を含むブログ (15件) を見る

pytestでPythonスクリプトをテストする

概要

PythonのテストツールのpytestをつかってPythonスクリプトのテストをしてみたいと思います。

インストール

pytestはpipでインストールできます。

$ pip install pytest

テストしてみる

実際にpytestでテストしてみます。

前提

こんなかんじのスクリプトたちがあるとする。

テストされる.py

たしざんするだけのやつ

def addition(a, b):
    result = a + b
    return(result)

テストする.py

そしてそれのテストコードがあるとするとこう(本当はこんなケース必要ないけれど)
1+2=3だよねー
2+2=4だよねーってかんじ。

def test_addtion_3()はまちがっているのでエラーになるはず

import wawawa
def test_addtion_1():
    assert wawawa.addition(1,2) == 3

def test_addtion_2():
    assert wawawa.addition(2,2) == 4

def test_addtion_3():
    assert wawawa.addition(2,2) == 99

pytest でテストしてみる

テストしてみます。
いい忘れていたけどディレクトリ構成はこんなかんじ。

$ ls -l .
-a----        2019/10/21     7:44            141 test_wawawa.py
-a----        2019/10/21     7:41             61 wawawa.py

テストしてみます。
わかりやすくするためにオプションに-vを指定して実行してあげています。

$ pytest -v ./test_wawawa.py
====================================== test session starts =======================================
platform win32 -- Python 3.7.4, pytest-5.2.1, py-1.8.0, pluggy-0.13.0 -- c:\users\takak\appdata\local\programs\python\python37-32\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\takak\test_test
collected 3 items

test_wawawa.py::test_addtion_1 PASSED                                                       [ 33%]
test_wawawa.py::test_addtion_2 PASSED                                                       [ 66%]
test_wawawa.py::test_addtion_3 FAILED                                                       [100%]

============================================ FAILURES ============================================
_________________________________________ test_addtion_3 _________________________________________

    def test_addtion_3():
>       assert wawawa.addition(2,2) == 99
E       assert 4 == 99
E         -4
E         +99

test_wawawa.py:10: AssertionError
================================== 1 failed, 2 passed in 0.03s ===================================

3つ目のテストケースでFAILEDとなっていることがわかる。

おわりに

べんりですね。

独学プログラマー Python言語の基本から仕事のやり方まで

独学プログラマー Python言語の基本から仕事のやり方まで