【问题标题】:Launch and install applications on EC2 instance using aws sdk使用 aws sdk 在 EC2 实例上启动和安装应用程序
【发布时间】:2021-07-04 23:36:00
【问题描述】:

我不知道一开始这是否可能。

要求是基于某些应用程序登录使用 aws sdk(我知道这是可能的)using 启动 ec2 实例。

然后我想在新启动的实例上安装一些应用程序,比如说 docker。

这可以使用 sdk 吗?或者我的想法本身是错误的,有更好的方案解决方案?

我可以使用 SDK 在 Running 实例上运行命令吗?

【问题讨论】:

  • 如果您可以向我们提供有关您使用的语言类型的详细信息,我们可以为您提供帮助,aws sdk 可用于多种语言aws.amazon.com/tools
  • 我只是在寻找是否可能,任何语言都可以,我想如果一种语言可以,我想其他语言也可以,对吧?跨度>
  • 是的,这是 100% 可能的,发布了一个解决方案,其中包含适用于 python (boto3) 的 aws sdk 示例。如果它对您有帮助,您能否接受它作为答案,以便将来对其他人有所帮助:)

标签: amazon-web-services amazon-ec2 aws-sdk


【解决方案1】:

是的,您可以在 EC2 启动时通过在 userdata 部分提供脚本/命令来安装任何东西。这也可以通过 AWS SDK https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_UserData.html

你可以在用户数据中传递类似 yum install docker 的命令

UserData='yum install docker'

【讨论】:

  • 我知道 userData,它实际上提供的控制较少,因为我以后无法使用 sdk 运行命令,只能在启动/重新启动时运行。
【解决方案2】:

使用 boto3 可以在运行命令上安装使用 cmd 的应用程序。

ssm_client = boto3.client('ssm')
response = ssm_client.send_command(
            InstanceIds=['i-xxxxxxx'],
            DocumentName="AWS-RunShellScript",
            Parameters={'commands': ['echo "abc" > 1.txt']}, )

command_id = response['Command']['CommandId']
output = ssm_client.get_command_invocation(
      CommandId=command_id,
      InstanceId='i-xxxxxxxx',
    )
print(output)

ssm clientRuns commands on one or more managed instances.

你也可以使用函数优化这个

def execute_commands(ssm_client, command, instance_id):
   

    response = client.send_command(
        DocumentName="AWS-RunShellScript", #preconfigured documents
        Parameters={'commands': commands},
        InstanceIds=instance_ids,
    )
    return resp

ssm_client = boto3.client('ssm') 
commands = ['ifconfig']
instance_ids = ['i-xxxxxxxx']
execute_commands_on_linux_instances(ssm_client, commands, instance_ids)

【讨论】:

  • 使用 sdk 创建实例是可能的,并且在问题本身中写入/引用。问题是我可以使用 sdk 在正在运行的实例上运行命令吗?
  • 对不起,我用文档参考更新了我的答案,希望它能解决问题。
猜你喜欢
  • 2023-04-05
  • 1970-01-01
  • 2017-05-03
  • 2018-09-26
  • 1970-01-01
  • 2019-10-04
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多