awscli の profile 名を補完できるようにする patch
Command Completion - AWS Command Line Interface を参考にコマンドを実行すると、
aws コマンドの補完ができるようになります。
Configuring the AWS Command Line Interface - AWS Command Line Interface にあるように、
~/.aws/credentials か ~/.aws/config に複数の profile を設定できます。
profile を補完できるか質問されたので調べてみると、
できないようでしたので patch を書きました。
上記 patch を awscli-completer.py.patch と保存したとすると、
$ patch /path/to/awscli/completer.py < awscli-completer.py.patch
で patch を当てられます。
実行例
$ cat ~/.aws/config [default] region=ap-northeast-1 [profile test] region=ap-northeast-1 [profile text] region=ap-northeast-1
のような設定をしている場合、
以下のように入力すると、
$ aws --profile [TAB] default test text
profile 一覧が表示されます。
あとは profile 名が特定できるところまで入力してから[TAB] を押せば補完されます。
タイトルには 「profile 名を補完」と書きましたが、
ついでに --color と --output も補完できるようにしました。
以下のように表示されます。
$ aws --color [TAB] auto off on $ aws --output [TAB] json table text
patch の解説
以下の説明は全て awscli/completer.py 内に書かれているコードです。
def _complete_option(self, option_name): ... if option_name == '--profile': return self.driver.session.available_profiles return []
_complete_option に、profile 一覧を取得する記述があったのですが、
--profile を入力したあとに呼び出されるようになっていないようでしたので、
def _complete_provider(self): retval = [] if self.current_word.startswith('-'): cw = self.current_word.lstrip('-') if cw in ['color', 'endpoint-url', 'output', 'profile']: retval = self._complete_option('--' + cw) ... return retval
で、--profile が入力されたら return self.driver.session.available_profiles を呼び出すようにしました。
complete で各処理を呼び出しているので、
def complete(self, cmdline, point): ... if self.previous_word is not None and self.previous_word.startswith('-'): if self.previous_word in ['--color', '--output', '--profile']: options = self._complete_option(self.previous_word) retval = [] for opt in options: if opt.startswith(self.current_word): retval.append(opt) return retval
self.previous_word に --profile が入っている時にprofile 一覧を取ってきて、
そこから profile 名を補完できるようにしました。
まとめ
aws コマンドの --profile を補完する patch を紹介しました。
とりあえず動くようにしただけなので Pull Request は送っていませんが、
もう少しいい感じにできたら PR 送る予定です。