2017-02-16 5 views
8

EC2 인스턴스에서 ssh 명령을 실행하는 데 boto3을 사용하려고합니다. 나는이 가이드 읽어 http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/troubleshooting-remote-commands.html 을 나는 그러나 나는 오류 메시지가 그들이 거기에 쓴의 모든 것을 유지 않았다SSM에서 EC2 인스턴스로 명령을 보내지 못했습니다.

>>>import boto3 
>>> ec2 = boto3.client('ssm') 
>>> a = ec2.send_command(InstanceIds=['i-0d5e16f6'], DocumentName='AWS-RunShellScript', Comment='abcdabcd', Parameters={"commands":["ifconfig"]}) 

출력 :

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 253, in _api_call 
    return self._make_api_call(operation_name, kwargs) 
    File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 543, in _make_api_call 
    raise error_class(parsed_response, operation_name) 
    botocore.errorfactory.InvalidInstanceId: An error occurred (InvalidInstanceId) when calling the SendCommand operation: 

내가 함께 명령을 보내려고하는 경우 awscli 나는 같은 문제가 발생합니다 :

aws ssm send-command --instance-ids "i-0d5e16f6" --document-name "AWS-RunShellScript" --comment "IP config" --parameters commands=ifconfig --output text 

An error occurred (InvalidInstanceId) when calling the SendCommand operation: 

어떤 사람은 그것을 해결하는 방법을 알고 있습니까?

+0

인스턴스가 다른 지역에 있습니까?SDK 및/또는 CLI 도구로 올바른 AWS 계정 및 지역을 구성했는지 확인하십시오. –

답변

7

액세스하려는 인스턴스에 SSM agent이 설치되어 있지 않은 경우 이러한 현상이 발생할 수 있습니다. 당신이 SSM 명령을 실행할 수있는 인스턴스의 목록은 실행

aws ssm describe-instance-information --output text 

여기에서, 당신은 그 인스턴스와 send_command 명령을 실행 한 후 인스턴스 ID를 잡을 수 있습니다.

2

설명 된 바와 같이 here in AWS' troubleshooting guide에는이 오류의 가능한 원인이 다양합니다.

수용된 대답 aws ssm describe-instance-information 유효한 상태에서 유효한 SSM 에이전트가 설치되어 있으므로 한 줄에 몇 가지 문제 해결 단계가 포함됩니다 (nice;)).

ssm.client.describe_instance_information() 

내가 권한을 확인 여부를 확실하지 않다하지만 그렇게 추정 :

같은 boto3를 사용하는 경우가 달성 될 수있다. instance_id가 목록에서 누락 된 경우 here 단계의 단계를 수행하여 올바른 사용 권한을 확인할 수 있습니다. (이것은 분명 아니다으로 마지막으로 확실히 적어도)

그러나, 또 다른 원인이있다 :

갓 생성 된 인스턴스는 describe_instance_information 목록에 표시하기 위해 약간의 시간이 걸릴.

인스턴스는 대기 후 작성 후 완료됩니다. 입니다. 예를 들면 다음과 같습니다.

# Key names are the same as the keyword arguments required by boto 
    params = { 
      'ImageId': image_id_to_use, 
      'InstanceType': instance_type_to_launch, 
      'MinCount': 1, 
      'MaxCount': 1, 
      'UserData': user_data_script, 
      'SecurityGroups': ['your groups'], 
      'KeyName': 'yourkeyname', 
      } 

    # Run the instance and wait for it to start 
    reservation = ec2.client.run_instances(**params) 
    instance = ec2.resource.Instance(reservation['Instances'][0]['InstanceId']) 
    instance.wait_until_running() 

    # Also wait status checks to complete 
    waiter = ec2.client.get_waiter('instance_status_ok') 
    waiter.wait(InstanceIds=[instance.id]) 

    # Apply the IAM roles required (this instance will need access to, e.g., S3) 
    response = ec2.client.associate_iam_instance_profile(
     IamInstanceProfile={ 
      'Arn': 'your_arn', 
      'Name': 'ApplicableRoleEGAdministratorAccess' 
     }, 
     InstanceId=instance.id 
    ) 

    print('Instance id just created:', instance.id) 
    print('Instances in the SSM instances list right now:') 
    print(ssm.client.describe_instance_information()['InstanceInformationList']) 

(해당되는 경우, 분명히 저에게 맞았습니다). UserData를 스크립트를 실행하는 데 걸리는 시간 (this SO post for a possibly-related discussion on waiting for user data to complete 참조) 때문에

수 있지만, 나는 (내가 취할! ​​기꺼이보다 더 많은 노력없이)는 것을인지 말해, 아니면 그냥 수 없습니다 AWS가 서비스 데이터베이스를 업데이트하는 데 걸리는 시간.

이 문제를 해결하기 위해 인스턴스 ID가 목록에 나타날 때까지 반복적으로 describe_instance_information()을 호출 한 짧은 웨이터 (다른 실패 모드를 처리하기위한 시간 초과 예외가 있음)를 작성했습니다.

관련 문제