DEV Community

Boto3 - Calling powershell scripts in EC2 Instance

Calling remove powershell scripts in EC2 Instance by Boto3

Permission : Make sure you have access for running AWS Lambda

  1. AmazonSSMFullAccess
  2. AmazonEc2FullAccess
  3. AWSLambdaExecute
import time
import json
import boto3

def lambda_handler(event, context):

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

    # getting ec2 instance information
    describeInstance = client.describe_instances()

    InstanceId = "i-0xxxxxxxxxxxx"

    # command to be executed on ec2 instance
    response = ssm.send_command(InstanceIds=[InstanceId],DocumentName="AWS-RunPowerShellScript", Parameters={"commands": ['& "C:\scripts\ec2_invoke_scripts.ps1"']})

    # 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=InstanceId)
    print(output)

    return {"statusCode": 200, "body": json.dumps("Scripts executed Successfully")}-
Enter fullscreen mode Exit fullscreen mode

Conclusion : Discussed about calling remote powershell scripts in Ec2 Instances using Boto3

Any suggestions/improvements for my blogs and if you like my blogs please share with your connections. Follow me in dev.to and linked in https://www.linkedin.com/in/srinivasuluparanduru/

Top comments (0)