【问题标题】:AWS - Associate EC2 with SSM to enable ssm.client.send_commandAWS - 将 EC2 与 SSM 关联以启用 ssm.client.send_command
【发布时间】:2018-06-23 16:07:24
【问题描述】:

我想在新启动的实例上通过 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:

【问题讨论】:

  • SSM 需要在实例上运行代理。您的实例是否正在运行代理?如果您只需要在启动实例时运行一次命令,则应该使用用户数据脚本。否则,您也可以使用 ssh 或任何类型的编排系统,例如 mcollective 或 rundeck。

标签: python amazon-ec2 cloud boto3 aws-ssm


【解决方案1】:

您收到 InvalidInstanceId 异常,因为 ssm 代理未在您的实例上运行。

【讨论】:

    猜你喜欢
    • 2021-12-11
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2021-10-12
    • 2019-08-25
    • 2021-10-04
    • 2016-09-02
    • 2014-10-07
    相关资源
    最近更新 更多