2016-11-08 83 views
0

我正在使用具有实例配置文件的ec2实例配置文件启动服务器。AWS:如何确保在启动ec2服务器时初始化和传播实例配置文件

问题是档案有时是不是“有”创建后,即使我等待如10秒内:

# Create new Instance Profile 
    instanceProfile = self.iam.create_instance_profile(InstanceProfileName=instProfName) 
    instanceProfile.add_role(RoleName="...") 

    time.sleep(10) 

    # Create the Instance 
    instances = self.ec2.create_instances(
    # ... 
    IamInstanceProfile={ 
     "Name":instanceProfile.instance_profile_name 
    } 
) 

有没有办法来等待它被传播?

我第一次尝试是:

error = 30 
    dryRun = True 

    while error > 0: 
    try: 
     # Create the Instance 
     instances = self.ec2.create_instances(
      DryRun=dryRun 
      # ...    
      IamInstanceProfile={ 
       "Name":instanceProfile.instance_profile_name 
      } 
     ) 
     if not dryRun: 
      break; 

     dryRun = False 

    except botocore.exceptions.ClientError as e: 
     error = error - 1; 

,但我怎么只得到IAM配置文件错误?

回答

0

AWS的大部分工作使用“最终一致性”。这意味着在你做出改变之后,在系统中传播需要一些时间。

在创建实例简介:

  1. 延迟5秒或10秒(或你舒服一些其他时间),
  2. 呼叫iam.get_instance_profile与您的实例配置文件名称。
  3. 重复延迟并检查,直到get_instance_profile返回您的信息。

您可以做的另一件事是在ec2.create_instances调用期间捕获“实例配置文件未找到错误”,如果出现该错误,则延迟并重复。

+0

我该如何捕捉一个只有“ClientError”的错误? – Tobi

+0

您需要检查'e'来查看是否有任何可区分的数据。否则,你只需要重新尝试任何这样的错误。 –

+0

嗯...问题是我不能检查'E'没有真正尝试启动一个实例 – Tobi