LoginSignup
8
10

More than 3 years have passed since last update.

aws-cliをpythonスクリプトで自動化する

Last updated at Posted at 2019-08-18

前置き

gitにpushされたときにciで自動でAWS上リソースをバババッと作ってくれるスクリプトを書きたかった

最初はシェルでこのように書いていた

aws logs create-log-stream --log-group-name hoge-logs

aws ecs register-task-definition --family hogehoge-family ............

しかし、値を取得してパイプで渡したり一度処理してから他に渡したりした時に問題が発生


HOGE=$(aws ecs list-task-definitions --family-prefix hogehoge-family)

if [[ HOGE =~ arn:aws:ecs:us-west-2:123456789012:task-definition/hogehoge:1 ]]; then
# なんとかかんとか

原因はaws-cli側の出力がJSONなのでダブルクォーテーションが悪さをしてしまう。
↓例としてecsタスク定義を一覧取得するコマンドを実行時に返ってくる値


aws ecs list-task-definitions --family-prefix wordpress
{
    "taskDefinitionArns": [
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:3",
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:4",
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:5",
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:6"
    ]
}

このクォーテーションをエスケープしてなんとかするには?と調べてみたが、、

シェルだけで全てやらなくて良い

結論から、シェルだけで解決する方法もなくはないと思うが、PythonやRubyとかに移したほうが楽
aws-cliのインストールにPythonが必要なので、今回はPythonを選択した

Pythonでシェルコマンドの実行


import subprocess

cmd = []
cmd.append("aws")
cmd.append("ecs")
cmd.append("list-task-definitions")
cmd.append("--family-prefix")
cmd.append("hogehoge-family")

subprocess.call(cmd)

パイプで渡すような処理の場合、以下のように書ける


import subprocess

cmd = []
cmd.append("aws")
cmd.append("ecs")
cmd.append("list-task-definitions")
cmd.append("--family-prefix")
cmd.append("hogehoge-family")

push = subprocess.Popen(cmd, stdout = subprocess.PIPE)

if push.communicate() == hogehoge:
    # なんとかかんとか

全部Pythonでやってもいいし、シェル側から引数を取ってそれを処理して、ということもできるようになった

参照 https://qiita.com/caprest/items/0245a16825789b0263ad

8
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
10