【问题标题】:Sending parameters to SSM from Lambda function从 Lambda 函数向 SSM 发送参数
【发布时间】: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


    【解决方案1】:

    您可以将 lambda 函数中的值写入 SSM 参数存储中的某个位置。然后,您必须引用参数存储位置作为 SSM 文档中参数的默认值,如以下example from the documentation 所示:

    "AMI": {
      "type": "String",
      "description": "(Required) The AMI to use when launching the instance.",
      "default": "{{ssm:/aws/service/list/ami-windows-latest}}"
    }
    

    【讨论】:

    • 无论如何我可以在 ssm 文档中使用 lambda 函数中的 tagvalue 吗?
    • 我已将答案编辑得更准确。您可以将其从您的 lambda 函数写入 SSM 参数存储。
    猜你喜欢
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    相关资源
    最近更新 更多