Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute commands on AWS Instance using Boto3

Can anyone tell me if we can execute Shell Commands using Boto3 on Launched AWS instance.

I read at few places about "boto.manage.cmdshell" but it is deprecated in Boto3.

Appreciate any help.

Regards, Saurabh

like image 444
sdeshpande Avatar asked Dec 01 '15 19:12

sdeshpande


2 Answers

ssm_client = boto3.client('ssm')
response = ssm_client.send_command(
            InstanceIds=['i-03#####'],
            DocumentName="AWS-RunShellScript",
            Parameters={'commands': ['start ecs']}, )

command_id = response['Command']['CommandId']
output = ssm_client.get_command_invocation(
      CommandId=command_id,
      InstanceId='i-03######',
    )
print(output)
like image 180
Joe Mantil Avatar answered Sep 28 '22 07:09

Joe Mantil


ssm = boto3.client('ssm' )    
testCommand = ssm.send_command( InstanceIds=[ 'i-123123123123' ], DocumentName='AWS-RunShellScript', Comment='la la la', OutputS3BucketName='myOutputS3Bucket', OutputS3KeyPrefix='i-123123123123', Parameters={ "commands":[ "ip config" ]  } )

i-123123123123 is a pretend ec2 instance id. I put that in the OutputS3KeyPrefix to get a unique place to store logs in the bucket.

You can install the ssm agent like this;

ec2r = boto3.resource('ec2' )
userdata = """#cloud-config
    runcmd:
     - /home/ec2-user/sudo npm run prod
     - cd /tmp
     - curl https://amazon-ssm-%s.s3.amazonaws.com/latest/linux_amd64/amazon-ssm-agent.rpm -o amazon-ssm-agent.rpm
     - yum install -y amazon-ssm-agent.rpm
""" % region   

if ssm == "on":
    instance = ec2r.create_instances( ImageId=ami, MinCount=1, MaxCount=1, KeyName=keyname, InstanceType=instancetype, 
        NetworkInterfaces=[{
        'DeviceIndex': 0,
        'AssociatePublicIpAddress': False,
        'SubnetId': mySub,
        'Groups': secGroupList,
        'AssociatePublicIpAddress': AssociatePublicIpAddress
    }],
        Monitoring={ 'Enabled': False },

        UserData=userdata,
        IamInstanceProfile={
            'Name': rolename
        },
        EbsOptimized=False
    )
like image 30
ddtraveller Avatar answered Sep 28 '22 05:09

ddtraveller