Manoj Paritala
Manoj Paritala

Reputation: 1

Sending parameters to SSM from Lambda function

I am trying to execute some commands on EC2 instance that copies files from EC2 to S3, I am using AWS Lambda to automate the process and powershell script via SSM document, In my lambda function I am trying to send parameters from AWS Lambda to SSM document using ssm.send_command. Below is my Code


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
    

Here is my SSM document

  "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"
        ]
      }
    }
  ]
}

To my Knowledge I can use the parameters in SSM document to assign s3folder . But the $s3folder is empty when doing this way, is this the right way of doing it if not any help will be higher appreciated. Is there a way to send tagvalues in the lambda function to ssm document parameters and assign it to $s3folder ?

Upvotes: 0

Views: 1012

Answers (1)

stijndepestel
stijndepestel

Reputation: 3564

You can write the value from your lambda function to a location in the SSM parameter store. Then, you have to reference the parameter store location as the default value for your parameter in the SSM document as seen in the following 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}}"
}

Upvotes: 0

Related Questions