When I launch an EC2 instance from a particular AMI via the web console, it works just fine and I can RDP into it no problems.
But when I launch another (identical) instance via an aws lambda, I cannot RDP into the instance
Here is the lambda used to launch the instance
import boto3
REGION = 'ap-southeast-2'
AMI = 'ami-08e9ad7d527e4e95c'
INSTANCE_TYPE = 't2.small'
def lambda_handler(event, context):
EC2 = boto3.client('ec2', region_name=REGION)
init_script = """<powershell>
powershell "C:\\Users\\Administrator\\Desktop\\ScriptToRunDaily.ps1"
aws ec2 terminate-instances --instance-ids 'curl http://169.254.169.254/latest/meta-data/instance-id'
</powershell>"""
instance = EC2.run_instances(
ImageId=AMI,
InstanceType=INSTANCE_TYPE,
MinCount=1,
MaxCount=1,
InstanceInitiatedShutdownBehavior='terminate',
UserData=init_script
)
I can see the instance start up in the AWS console. Everything looks normal until I go to remote in, where a prompt says 'Initiating remote session' takes ~15 seconds and returns
We couldn't connect to the remote PC. Make sure the PC is turned on and connected to the network, and that remote access is enabled.
Error code: 0x204
When I click try to connect to the instance through the AWS console, it lets me download an RDP file, however, it doesn't display the option to 'Get Password' as it does if I start the exact same AMI through the console (as opposed to via a lambda)
I suspect I may need to associate the instance with a keypair at launch?
Before creating this particular AMI, I logged in and changed the password, so I really have no need to generate one using the .pem
file.
It turns out I needed to add SecurityGroupIds
Note that it's an array of up to 5 values, rather than a single value, so it's specified like ['first', 'second', 'etc']
rather than just 'first'
. Hence the square brackets around ['launch-wizard-29']
below
I also specified a key.
The following is what worked for me
import boto3
REGION = 'ap-southeast-2'
AMI = 'ami-08e9ad7d527e4e95c'
INSTANCE_TYPE = 't2.small'
def lambda_handler(event, context):
EC2 = boto3.client('ec2', region_name=REGION)
init_script = """<powershell>
powershell "C:\\Users\\Administrator\\Desktop\\ScriptToRunDaily.ps1"
aws ec2 terminate-instances --instance-ids 'curl http://169.254.169.254/latest/meta-data/instance-id'
</powershell>"""
instance = EC2.run_instances(
ImageId=AMI,
InstanceType=INSTANCE_TYPE,
MinCount=1,
MaxCount=1,
InstanceInitiatedShutdownBehavior='terminate',
UserData=init_script,
KeyName='aws', # Name of a key - I used a key (i.e. pem file) that I used for other instances
SecurityGroupIds=['launch-wizard-29'] # I copied this from another (running) instance
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.