skip to Main Content

Please Help i want to add more instance under instance_id.I have Two more instance where i want to run the commands.Instance ID like i-0e946552448dgsd , i-0e946258789itrs.How to add both the IDs under instance_id So that the command can be run on both the instances as well.

here is my Lambda function.

import time
import json
import boto3


def lambda_handler(event, context):

    # boto3 client
    client = boto3.client("ec2")
    ssm = boto3.client("ssm")

    instance_id = 'i-0e94623888f942c48'
    response = ssm.send_command(
            InstanceIds=[instance_id],
            DocumentName="AWS-RunShellScript",
            Parameters={
                "commands": ["sh /root/test.sh"]
            },  
        )

        # fetching command id for the output
    command_id = response["Command"]["CommandId"]

    time.sleep(3)

        # fetching command output
    output = ssm.get_command_invocation(CommandId=command_id, InstanceId=instance_id)
    print(output)

    return {"statusCode": 200, "body": json.dumps("Thanks!")}

2

Answers


  1. The InstanceIds is a list. You can provide multiple IDs, for example:

        response = ssm.send_command(
                InstanceIds=['i-0e946552448dgsd', 'i-0e946258789itrs'],
                DocumentName="AWS-RunShellScript",
                Parameters={
                    "commands": ["sh /root/test.sh"]
                },  
            )
    
    Login or Signup to reply.
  2. Change your instance_ids as a list and specify it directly. Also handle fetching command invocation from each instance.

    import time
    import json
    import boto3
    
    
    def lambda_handler(event, context):
    
        # boto3 client
        client = boto3.client("ec2")
        ssm = boto3.client("ssm")
    
        instance_ids = ['i-0e94623888f942c48', 'second_instance_id'] 
        response = ssm.send_command(
                InstanceIds=instance_ids,
                DocumentName="AWS-RunShellScript",
                Parameters={
                    "commands": ["sh /root/test.sh"]
                },  
            )
    
            # fetching command id for the output
        command_id = response["Command"]["CommandId"]
    
        time.sleep(3)
    
            # fetching command output
        for instance_id in instance_ids:
            output = ssm.get_command_invocation(CommandId=command_id, InstanceId=instance_id)
            print(output)
    
        return {"statusCode": 200, "body": json.dumps("Thanks!")}
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search