2016-11-17 1 views
0

Ich versuche ein Python-Skript auszuführen, das eine Instanz starten und dann einige Befehle ausführen kann. Ich weiß, dass es übergeben werden kann, wenn ich versuche, eine Instanz in Form von Userdata zu erstellen. Was ich herausfinden möchte, ist, wie ich es weitergeben soll, wenn ich eine bereits erstellte Instanz starte. Im Folgenden finden Sie den Code boto3 mit einfacher Hallo Welt passieren, während eine Instanz zu schaffen:Wie übergebe ich Befehle an ec2, nachdem ich eine Instanz aus dem Python-Skript gestartet habe?

import boto3 
userdata = """#cloud-config 

repo_update: true 
repo_upgrade: all 

packages: 
- s3cmd 

runcmd: 
- echo 'Hello S3!' > /tmp/hello.txt 
- aws --region YOUR_REGION s3 cp /tmp/hello.txt s3://YOUR_BUCKET/hello.txt 
""" 

ec2 = boto3.resource('ec2') 
instances = ec2.create_instances(
    ImageId='ami-f5f41398',   # default Amazon linux 
    InstanceType='t2.micro', 
    KeyName='YOUR_SSH_KEY_NAME', 
    MinCount=1, 
    MaxCount=1, 
    IamInstanceProfile={ 
     'Arn': 'YOUR_ARN_ID' 
    }, 
    SecurityGroupIds=['YOUR_SECURITY_GROUP_NAME'], 
    UserData=userdata 
) 

So etwas wie

i = ec2.Instance(id='i-5fea4d42') 
i.start('pass commands here: eg echo xx, mv a b/ etc') 
+0

Sie möchten jedes Mal einen anderen Befehl ausführen oder denselben Befehl in den Benutzerdaten? – helloV

+0

Ich versuche Befehle auf dem ec2 shel auszuführen. Sie werden anders sein, ich versuche, boto und command shell zu verwenden, was nicht auf boto3 link übertragen wurde. Wahrscheinlich werde ich eine Kombination aus Paramiko und Boto3 verwenden. –

Antwort

0

Ich konnte paramiko zusammen mit boto3 und awscli verwenden, um alles auf der Cloud automatisiert auszuführen.

import paramiko 
import boto3 
import time 
import subprocess 
import awscli 
import os 

# Starting instance, copying data to instance, running model, copying output to s3 
print ("\nCreating ssh session") 
session = boto3.Session() 
ec2 = session.resource('ec2', region_name='us-east-1') 
i = ec2.Instance(id='instance id') # instance id 


print('\nstarting deeplearning_ami instance') 
i.start() 
i.wait_until_running() 
i.load() 
print ("Waiting for the checks to finish..") 
time.sleep(45) 

k = paramiko.RSAKey.from_private_key_file(key_path) #your private key for ssh 
c = paramiko.SSHClient() 
c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
print ("\nConnecting to shell using ssh") 
c.connect(hostname = i.public_dns_name, username = "ec2-user", pkey = k) 

print ("\nExecuting commands on EC2 instance\n") 

stdin , stdout, stderr = c.exec_command(""" mkdir -p model; 
             printf 'Creating directory structure, if it does not exists \n'; 
             cd model; 
             mkdir -p data out cp; 
             printf '\nCopying code from s3 bucket to ec2 instance \n'; 
             aws s3 cp {0} .; 
             printf '\nDownloading data from s3 bucket to ec2 instance'; 
             aws s3 sync {1} data; 
             printf '\n Download complete, running model..\n\n'; 
             python theano_test.py; 
             echo 'Hello S3!' > out/hello.txt; 
             printf '\n Copying output to s3 bucket \n'; 
             aws s3 sync out {2} """.format(s3_code,s3_data,s3_out), get_pty=True) 

for line in iter(lambda: stdout.readline(2048), ""): print(line, end="") 
print ("\n \n Processingfinished") 

#print ('Stopping instance') 
i.stop() 


print ('Copying output from s3 bucket to local') 
os.system('aws s3 sync ' + s3_out + ' ' + local_out) 
0

Sie können die Userdata gesetzt und die Instanz starten und es wird die Änderung abholen: http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.modify_instance_attribute

sind jedoch Userdata-Skripte in der Regel nur einmal ausführen gesetzt, so werden Sie es ändern müssen bei jedem Start auszuführen: How do I make cloud-init startup scripts run every time my EC2 instance boots?

Eine andere Möglichkeit wäre, SSH einzurichten und ein Skript nach dem Booten auszuführen, aber das Verschieben in UserData ist meiner Meinung nach sauberer.

+0

Ich versuche, Boto und Kommando-Shell zu verwenden, die nicht auf boto3 übertragen wurde [link] (http://stackoverflow.com/questions/34028219/how-to-execute-commands-on-aws-instance-using-use- boto3). Wahrscheinlich werde ich eine Kombination aus Paramiko und Boto3 verwenden. –

Verwandte Themen