启动AWS EC2实例,运行命令,流日志以控制台并终止

时间:2019-07-18 21:13:24

标签: bash amazon-web-services amazon-ec2

尝试在EC2实例中运行CI / CD的几个步骤。请不要问原因。

需要: 1)使用AWS CLI启动实例。设置几个环境变量。 2)运行一些bash命令。 3)将上述命令中的命令流式传输到调用者脚本的控制台中。 4)如果任何命令失败,则也需要使调用脚本失败。 5)终止实例。

2 个答案:

答案 0 :(得分:1)

有一个SO线程指示输出输出不是那么容易。 [1] 如果必须执行此任务,我会怎么做:

  • 使用cli命令aws ec2 run-instances并使用预先安装了AWS SSM代理的AMI启动实例。 [2]

  • 使用AWS SSM运行命令。 [3]这样的好处是,您可以在需要时运行任意数量的命令(即,不得在实例启动时指定命令,但可以在以后选择)。您还将获得每个命令的状态码。[4]

  • 使用SSM中的CloudWatch集成将命令输出流式传输到CloudWatch日志。 [5]

  • 将日志从CloudWatch流式传输到您自己的实例。 [6]

注意:您也可以使用aws ssm get-command-invocation定期轮询SSM API,而不是通过CloudWatch传输命令输出。 [7]

参考

[1] How to check whether my user data passing to EC2 instance working or not?
[2] Working with SSM Agent - AWS Systems Manager
[3] Walkthrough: Use the AWS CLI with Run Command - AWS Systems Manager
[4] Understanding Command Statuses - AWS Systems Manager
[5] Streaming AWS Systems Manager Run Command output to Amazon CloudWatch Logs | AWS Management Tools Blog
[6] how to view aws log real time (like tail -f)
[7] get-command-invocation — AWS CLI 1.16.200 Command Reference

答案 1 :(得分:0)

方法1。

使用AWS CLI启动实例。

 aws ec2 start-instances --instance-ids i-1234567890abcdef0

设置一些环境变量。

Use user dat of ec2 to set env. & run commands 

.. 运行其他逻辑/脚本

要终止该实例,请在同一实例中运行以下命令。

instanceid=`curl http://169.254.169.254/latest/meta-data/instance-id`
aws ec2 terminate-instances --instance-ids $instanceid

方法2。

Use python boto3 or kitchen chef ci.
相关问题