簡體   English   中英

AWS-將EC2與SSM關聯以啟用ssm.client.send_command

[英]AWS - Associate EC2 with SSM to enable ssm.client.send_command

我想在新啟動的實例上通過boto3運行一系列bash命令。

從一些研究看來,需要將此新實例與SSM關聯才能實現此目的。

下面是否有任何明顯的錯誤或遺漏的步驟? 還有更好的方法來實現既定目標嗎?

步驟1-獲取客戶和資源

import boto3

ec2c = boto3.client('ec2')
ec2r = boto3.resource('ec2')
ssmc = boto3.client('ssm')

第2步-創建並等待實例

instances = ec2r.create_instances(
    ImageId = 'ami-####',
    InstanceType = 't2.micro',
    MinCount = 1,
    MaxCount = 1,
    SecurityGroupIds = ['sg-####'])

instance_ids = [i.id for i in instances]
instance = instances[0]

instance.wait_until_running()

步驟3-將實例與IAM配置文件關聯

“ RoleName”具有附加的AmazonEC2RoleforSSM策略

res = ec2c.associate_iam_instance_profile(
    IamInstanceProfile={
        'Arn': 'arn:aws:iam::###:instance-profile/RoleName',
        'Name': 'RoleName'
    },
    InstanceId = instance.id
)

步驟4-檢查關聯

print(ssmc.describe_instance_information()['InstanceInformationList'])

> []

(我認為此空列表是下一步失敗的原因)

第5步-運行命令

resp = ssmc.send_command(
    DocumentName = "AWS-RunShellScript",
    Parameters = {'commands': [mkdir app]},
    InstanceIds = instance_ids
)

> botocore.errorfactory.InvalidInstanceId: An error occurred ...
> ... (InvalidInstanceId) when calling the SendCommand operation:

您正在收到InvalidInstanceId異常,因為ssm代理未在您的實例上運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM