繁体   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