我尝试执行一个简单的AWS CLI命令,该命令可以对多个实例运行shell命令。
我首先知道我需要获取实例ID列表:
aws ec2 describe-instances --filter "Name=tag:Group,Values=Development" --query 'Reservations[].Instances[].[InstanceId]' --output text
然后我必须将它们分配给一个数组。然后遍历每个实例id并发送命令。
我们是否有选项让aws将shell命令发送到具有特定ID的实例?
这样的事情:
aws ssm send-command --instance-ids "i-xxxxxxxxxxxxxxxx" --document-name "shellscript"
我一直收到这个错误:
调用SendCommand操作时发生错误(InvalidInstanceId):
我确保SSM代理正在该特定实例上运行,并根据these docs pages确保一切正确。
答案 0 :(得分:3)
您可以使用ssm send-command
。
查看实例的IP地址的示例命令:
aws ssm send-command --instance-ids "your id's" --document-name "AWS-RunShellScript" --comment "IP config" --parameters "commands=ifconfig" --output text
根据您的需要修改命令。
如果您遇到错误,当您尝试访问的实例上没有SSM设置时,可能会发生这种情况。有关可以运行SSM命令的实例列表,请运行:
aws ssm describe-instance-information --output text
请参阅:InvalidInstanceId: An error occurred (InvalidInstanceId) when calling the SendCommand operation。
答案 1 :(得分:0)
我能够使用Boto3使用Python创建脚本。
import boto3
import botocore
import paramiko
tagkey = 'Environment'
tagvalue = 'DEV'
# list_instances functions returns a list of ip addresses containing a set of tags
def list_instances(tagkey, tagvalue):
ec2client = boto3.client('ec2')
response = ec2client.describe_instances(
Filters=[
{
'Name': 'tag:'+tagkey,
'Values': [tagvalue]
}
]
)
instancelist = []
for reservation in (response["Reservations"]):
for instance in reservation["Instances"]:
instancelist.append(instance["PublicDnsName"])
return instancelist
# Results of the function get stored in a list.
list = list_instances(tagkey, tagvalue)
key = paramiko.RSAKey.from_private_key_file("/home/ec2-user/key.pem")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Looping through all the instannces in the list
for instance_ip in list[:]:
# Connect/ssh to an instance
try:
# Here 'ec2-user' is user name and 'instance_ip' is public IP of EC2
client.connect(hostname=instance_ip, username="ec2-user", pkey=key)
# Execute a command after connecting/ssh to an instance
stdin, stdout, stderr = client.exec_command("touch test")
# close the client connection once the job is done
print "Command sent:",instance_ip
except Exception, e:
print e