如何在属于自动缩放组的所有 Amazon EC2 实例上 运行 shell 脚本?

How to run a shell script on all amazon ec2 instances that are part of a autoscaling group?

任何人都可以告诉我如何在属于自动缩放组的所有 ec2 实例上 运行 shell 脚本吗?

场景是我有一个脚本,我想 运行 在作为自动缩放组的一部分自动打开的许多 ec2 实例上。本机方法是通过 SSH 连接到每个实例和 运行 脚本。我正在寻找一种方法,当我在其中一个 ec2 实例上 运行 时,它可以在所有实例上自动 运行 或任何更好的方法?

提前致谢。

您可以通过多种不同的方式实施...

  1. 使用awscli获取弹性伸缩组中的所有实例 aws autoscaling describe-auto-scaling-groups --auto-scaling-group-name myTestGroup

  2. SSHkit 是一个有趣的工具 运行 远程服务器上的命令

花时间在适当的工具(如 Puppet、Chef)中自动化基础设施。使用 puppet mcollective,您可以施展魔法,包括您所询问的内容。

更新:

当您将实例添加到自动缩放组时,新标签 name=aws:autoscaling:groupName 会添加 value=name_of_assigned_autoscaling_group,因此很容易通过搜索此标签找到它。

$ asgName=testASG

$ aws ec2 describe-instances --filters Name=tag-key,Values='aws:autoscaling:groupName' Name=tag-value,Values=$asgName --output text --query 'Reservations[*].Instances[*].[InstanceId,PublicIpAddress]'

您将从上面的命令获得的输出是实例名称和 public IP:

i-4c42aabc 52.1.x.y

您可以使用这是您的脚本...

我会用 Chef 来做。 Opsworks(一个 aws 产品)是 chef 加上很多东西,它们可以完全按照你的想法做,并给你更多的灵活性。

您需要将 shell 脚本添加到新启动配置中的用户数据,然后更新自动缩放组。

https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html#user-data-shell-scripts

更新启动配置

if you want to change the launch configuration for your Auto Scaling group, you must create a launch configuration and then update your Auto Scaling group with the new launch configuration. When you change the launch configuration for your Auto Scaling group, any new instances are launched using the new configuration parameters, but existing instances are not affected.

https://docs.aws.amazon.com/autoscaling/latest/userguide/LaunchConfiguration.html

Run Command 也许?

您也可以使用它来调用脚本:
*好作弊:Select 运行 EC2 部分左侧菜单上的命令。单击 "Run Command" 按钮。然后设置您的 AWS-运行ShellScript。输入您的代码。然后在底部有一个下拉菜单,标记为:"AWS Command Line Interface command"、select 正确的平台和 copy/paste 脚本中的命令。

$Command_Id = aws ssm send-command --document-name "AWS-RunPowerShellScript" --targets '{\"Key\":\"tag:Name\",\"Values\":[\"RunningTests\"]}' --parameters '{\"commands\":[\"Start-Process \\"C:\\path\\to\\scripts\\LOCAL_RUN.ps1\\"\"]}' --comment "Run Tests Locally" --timeout-seconds 3800 --region us-east-1 --query 'Command.CommandId' --output text | Out-String


根据问题: 使用您的 Auto Scaling 组名称而不是 "RunningTests." 或者,在控制台中:在您的 "Run Command"设置。 Select "Specifiying a Tag" 单选按钮,然后是 "Name" 和您的 Auto Scaling 组。


*注意: 上面的命令是 windows powershell,但您可以通过 select在 运行 命令设置中使用正确的平台。

**注意: 确保您在该实例上的用户具有对 运行 命令的 AmazonSSMFullAccess 权限设置。

***注意:SSM 代理默认安装在 Windows 个实例上。如果您 运行ning Linux 或其他,您可能需要 install the SSM Agent.

对于简单的实现,您可以使用 python 结构 (http://www.fabfile.org/)。它是从本地或 bashin 实例到服务器列表的 运行 命令的工具。

这是一个包含基本脚手架和示例的代码库。许多 CICD 工具都具有针对此要求的功能,但我发现 fabric 最容易实现简单设置。

https://github.com/techsemicolon/python-fabric-ec2-aws