[英]Retrieving command invocation in AWS SSM
我正在嘗試將命令發送到正在運行的 ubuntu ec2 實例。 我已經配置了適當的角色,並且在 ec2 實例上運行了一個 ssm 代理。 使用 boto3 SDK 我能夠使用 client.send_command client.send_command()
function 成功發送 shell 命令,隨后能夠獲取命令 ID。 現在的挑戰是輪詢結果。 我正在嘗試使用client.get_command_invocation()
function 但不斷收到InvocationDoesNotExist
錯誤。 我確信我使用的是正確的命令 ID 和實例 ID,因為我已經使用 AWS CLI 測試了它們,如aws ssm list-command-invocations --command-id #### --instance-id i-#####
這有效。 這是我的代碼片段:
`ssm_client = boto3.client('ssm')
target_id = "i-####"
response = ssm_client.send_command(
InstanceIds=[
target_id
],
DocumentName="AWS-RunShellScript",
Comment="Code to run" ,
Parameters={
"commands": ["ls -l"]
}
)
cmd_id= response['Command']['CommandId']
response = ssm_client.get_command_invocation(CommandId=cmd_id,
InstanceId=target_id)
print(response)`
這是返回的錯誤: botocore.errorfactory.InvocationDoesNotExist: An error occurred (InvocationDoesNotExist) when calling the GetCommandInvocation operation
提前致謝。
我有同樣的問題,我通過在調用 get_command_invocation() 之前添加 time.sleep() 調用來修復它。 短暫的延遲應該就足夠了。
只需添加這兩行。
import time
time.sleep(2)
然后它會正常工作,通常只需要 0.65 秒,但最好給 2 秒。 為了讓它變得更好,你可以在 for 循環中添加一些很酷的東西,比如一些打印語句,然后在里面睡覺。
以下對我有用。 查看 API 文檔,了解如何在https://boto3.amazonaws.com更新默認延遲和最大嘗試次數。
from botocore.exceptions import WaiterError
ssm_client = boto3.client(
"ssm",
region_name=REGION,
aws_access_key_id=KEY,
aws_secret_access_key=SECRET,
)
waiter = ssm_client.get_waiter("command_executed")
try:
waiter.wait(
CommandId=commands_id,
InstanceId=instance_id,
)
except WaiterError as ex:
logging.error(ex)
return
time.sleep
在 99% 的時間里完成這項工作。 這是執行此操作的更好方法:
MAX_RETRY = 10
get_command_invocation_params = {
'CommandId': 'xxx',
'InstanceId': 'i-xxx'
}
for i in range(MAX_RETRY):
try:
command_executed_waiter.wait(**get_command_invocation_params)
break
except WaiterError as err:
last_resp = err.last_response
if 'Error' in last_resp:
if last_resp['Error']['Code'] != 'InvocationDoesNotExist' or i + 1 == MAX_RETRY:
raise err
else:
if last_resp['Status'] == 'Failed':
print(last_resp['StandardErrorContent'], file=sys.stderr)
exit(last_resp['ResponseCode'])
continue
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.