起こったこと
- boto3でEC2リソースへのタグ付けをDryRun実行したとき以下の例外が発生した。
- RDS等も同じことが起こるかは確認していません。
Traceback (most recent call last):
File "main.py", line 29, in <module>
Tags=[{'Key': 'isDefaultVpc', 'Value': 'true'}]
File "/Users/Saori_/.anyenv/envs/pyenv/versions/3.7.3/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/Users/Saori_/.anyenv/envs/pyenv/versions/3.7.3/lib/python3.7/site-packages/botocore/client.py", line 661, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set.
- 最後の行に注目
- 「リクエストは成功するだろうけどDryRunフラグが付いてるよ」
botocore.exceptions.ClientError: An error occurred (DryRunOperation) when calling the CreateTags operation: Request would have succeeded, but DryRun flag is set.
なぜコケたか
- DryRunのリクエストを受けたEC2のAPIは、リクエストそのものが成功してもHTTPStatusCode:412を返す
- botocoreはAPIリクエストに対するレスポンスのHTTPStatusCodeが2xx以外だと例外が発生する仕様になっている
対処
- よしなに例外処理する
python3
import boto3
from botocore.exceptions import ClientError
try:
boto3.client('ec2').create_tags(
DryRun=True,
Resources=['vpc-xxxxxxxx'],
Tags=[{'Key': 'isDefaultVpc', 'Value': 'true'}]
)
except ClientError as e:
if 'DryRunOperation' != e.response['Error']['Code']:
raise
ちなみに帰ってくるレスポンスの中身(e.response)は以下のようなものでした。
{'Error': {'Code': 'DryRunOperation', 'Message': 'Request would have succeeded, but DryRun flag is set.'}, 'ResponseMetadata': {'RequestId': 'hoge-703b-4928-9402-da2b5e9d2b5f', 'HTTPStatusCode': 412, 'HTTPHeaders': {'transfer-encoding': 'chunked', 'date': 'Fri, 03 Jan 2020 13:55:23 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0}}