简体   繁体   English

使用 aws sdk 在 EC2 实例上启动和安装应用程序

[英]Launch and install applications on EC2 instance using aws sdk

I don't know If this will be possible at the first place.我不知道这首先是否可能。

The requirement is to launch ec2 instance using aws sdk (I know this is possible) using based on some application login.要求是使用基于某些应用程序登录的 aws sdk(我知道这是可能的)启动 ec2 实例。

Then I wanted to install some application on the newly launched instance let's say docker.然后我想在新启动的实例上安装一些应用程序,比如 docker。

Is this possible using sdk?这可以使用 sdk 吗? Or My idea itself is wrong and there is a better solution to the scenario?或者我的想法本身是错误的,有更好的解决方案吗?

Can i run a command on a Running instance using SDK?我可以使用 SDK 在正在运行的实例上运行命令吗?

Yes you can install anything on EC2 when it is launched by providing script/commands in userdata section.是的,您可以通过在用户数据部分提供脚本/命令来在 EC2 上安装任何东西。 This is also possible from AWS SDK https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_UserData.html这也可以从 AWS SDK https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_UserData.ZFC35FDC70D5FC69D269883A822C7A5E

you can pass command like yum install docker in userdata您可以在 userdata 中传递类似 yum install docker 的命令

UserData='yum install docker' UserData='yum 安装 docker'

installing applications uysing cmd on a running command is possible using boto3.使用 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 client Runs commands on one or more managed instances. ssm 客户端Runs commands on one or more managed instances.

You can also optimize this using function您还可以使用 function 对此进行优化

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM