代码
import boto3
import traceback
def sayHello(profile, region_name):
try:
session = boto3.session.Session(profile_name=profile, region_name=region_name)
ssm_client = session.client('ssm')
ec2 = session.resource('ec2')
command = 'echo hello world'
instances = ec2.instances.filters(Filters=[{'Name': 'State', 'Values': ['running']}])
document_name = 'AWS-RunShellScript'
for instance in instances:
targets = [{
'Key': 'InstanceIds',
'Values': [instance_id]}]
resp = ssm_client.send_command(
DocumentName=document_name,
Parameters={
'commands': [
command,
]
},
Targets=targets,
)
except:
errors = traceback.format_exc()
print("...Error...failed to send command in ec2 instance: %s" % errors)
if __name__ == '__main__':
profile = "default"
region_name = "us-west-1"
sayHello(profile=profile, region_name=region_name)
获取ec2正在运行的instance
session = boto3.session.Session(profile_name=profile, region_name=region_name)
ec2 = session.resource('ec2')
instances = ec2.instances.filters(Filters=[{'Name': 'State', 'Values': ['running']}])
在获取的instance上执行命令
session = boto3.session.Session(profile_name=profile, region_name=region_name)
ssm_client = session.client('ssm')
command = 'echo hello world'
document_name = 'AWS-RunShellScript'
for instance in instances:
targets = [{
'Key': 'InstanceIds',
'Values': [instance_id]}]
resp = ssm_client.send_command(
DocumentName=document_name,
Parameters={
'commands': [
command,
]
},
Targets=targets,
)
send_command:
- targets 运行位置 可通过instanceid tag等获取。
- documentname 要运行的SSM文档的名称。这可以是公共文档或自定义文档
- command