AWS将EC2与SSM关联以启用ssm.client.send_命令

2024-05-16 15:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个新启动的实例上通过boto3运行一系列bash命令。在

从一些研究看来,要实现这一点,需要将这个新实例与SSM关联起来。在

下面有没有明显的错误或遗漏的步骤?还有没有更好的方法来实现既定目标?

步骤1-获取客户机和资源

import boto3

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

步骤2-创建并等待实例

^{pr2}$

步骤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:

Tags: 实例instance命令bashclient步骤boto3ec2