From a6d5656dd83ad55e9ab633afbd9c65bc2714399f Mon Sep 17 00:00:00 2001 From: Julien Vey Date: Wed, 4 Apr 2018 16:21:44 +0200 Subject: [PATCH] ec2_instance: add a retry to run_instance to help with ec2 consistency --- .../modules/cloud/amazon/ec2_instance.py | 17 ++++++++++++++++- .../ec2_instance/tasks/iam_instance_role.yml | 3 --- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/lib/ansible/modules/cloud/amazon/ec2_instance.py b/lib/ansible/modules/cloud/amazon/ec2_instance.py index 4436ab856d0..77cc1a8277f 100644 --- a/lib/ansible/modules/cloud/amazon/ec2_instance.py +++ b/lib/ansible/modules/cloud/amazon/ec2_instance.py @@ -622,6 +622,7 @@ import re import uuid import string import textwrap +import time from collections import namedtuple try: @@ -1378,7 +1379,7 @@ def ensure_present(existing_matches, changed, ec2, state): ) try: instance_spec = build_run_instance_spec(module.params) - instance_response = AWSRetry.jittered_backoff()(ec2.run_instances)(**instance_spec) + instance_response = run_instances(ec2, **instance_spec) instances = instance_response['Instances'] instance_ids = [i['InstanceId'] for i in instances] @@ -1405,6 +1406,20 @@ def ensure_present(existing_matches, changed, ec2, state): module.fail_json_aws(e, msg="Failed to create new EC2 instance") +@AWSRetry.jittered_backoff() +def run_instances(ec2, **instance_spec): + try: + return ec2.run_instances(**instance_spec) + except botocore.exceptions.ClientError as e: + if e.response['Error']['Code'] == 'InvalidParameterValue' and "Invalid IAM Instance Profile ARN" in e.response['Error']['Message']: + # If the instance profile has just been created, it takes some time to be visible by ec2 + # So we wait 10 second and retry the run_instances + time.sleep(10) + return ec2.run_instances(**instance_spec) + else: + raise e + + def main(): global module argument_spec = ec2_argument_spec() diff --git a/test/integration/targets/ec2_instance/tasks/iam_instance_role.yml b/test/integration/targets/ec2_instance/tasks/iam_instance_role.yml index b8654ed2869..9617f403a5e 100644 --- a/test/integration/targets/ec2_instance/tasks/iam_instance_role.yml +++ b/test/integration/targets/ec2_instance/tasks/iam_instance_role.yml @@ -30,9 +30,6 @@ <<: *aws_connection_info register: iam_role_2 - - name: Wait for IAM role to be available, otherwise the next step will fail (Invalid IAM Instance Profile name) - command: sleep 10 - - name: Make instance with an instance_role ec2_instance: name: "{{ resource_prefix }}-test-default-vpc"