【发布时间】:2021-08-12 02:00:19
【问题描述】:
我正在尝试在 EC2 实例上执行一些命令,将文件从 EC2 复制到 S3,我正在使用 AWS Lambda 通过 SSM 文档自动化流程和 powershell 脚本,在我的 lambda 函数中,我正在尝试从 AWS Lambda 发送参数使用 ssm.send_command 到 SSM 文档。以下是我的代码
import boto3
import time
import json
"""
A tool for retrieving basic information from the running EC2 instances.
"""
def lambda_handler(event, context):
# Connect to EC2
ec2 = boto3.client('ec2')
ssm = boto3.client('ssm')
describeInstance = ec2.describe_instances(Filters=[
{
'Name': 'tag:Type',
'Values': ['SQL']
}
])
InstanceId=[]
# fetchin instance id of the running instances
for i in describeInstance['Reservations']:
for instance in i['Instances']:
if instance["State"]["Name"] == "running":
InstanceId.append(instance['InstanceId'])
# looping through instance ids
for instanceid in InstanceId:
tagvalues = get_instance_name(instanceid)
params={
"keyvalue": [tagvalues],
}
print(params)
# command to be executed on instance
response = ssm.send_command(
InstanceIds=[instanceid],
DocumentName="Copy-tagvalues",
Parameters=params
)
# fetching command id for the output
command_id = response['Command']['CommandId']
# time.sleep(2)
# fetching command output
output = ssm.list_command_invocations(
CommandId=command_id,
InstanceId=instanceid
)
return {
'statusCode': 200,
'body': json.dumps(output),
'command_id': command_id
}
def get_instance_name(fid):
"""
When given an instance ID as str e.g. 'i-1234567', return the instance 'Name' from the name tag.
:param fid:
:return:
"""
ec2 = boto3.resource('ec2')
ec2instance = ec2.Instance(fid)
instancename = ""
for tags in ec2instance.tags:
if tags["Key"] == "Environment":
instancename = tags["Value"]
return instancename
这是我的 SSM 文档
"schemaVersion": "2.2",
"description": "SSM document to transfer SQL bak files from EC2 to S3",
"parameters": {
"keyvalue": {
"type": "String",
"description": "S3 bucket folder EX: PRO1"
}
},
"mainSteps": [
{
"action": "aws:runPowerShellScript",
"name": "example",
"inputs": {
"runCommand": [
"# Constants
$sourceDrive = "C:\"
$sourceFolder = "MSSQL\BACKUP"
$sourcePath = $sourceDrive + $sourceFolder
$s3Bucket = "transferec2tos3"
$s3Folder = "$keyvalue" #e.g. PRO1"
]
}
}
]
}
据我所知,我可以使用 SSM 文档中的参数来分配 s3folder 。但是这样做时 $s3 文件夹是空的,如果没有任何帮助,这是正确的做法吗?有没有办法将 lambda 函数中的标记值发送到 ssm 文档参数并将其分配给 $s3folder ?
【问题讨论】:
标签: amazon-web-services aws-lambda aws-ssm