0

I have created AWS Lambda python3.6 function to launch new windows ec2 instance. Additionally i have added powershell script as user data while launching new instance. But instance has been launched successfully. But user data is not executed.

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    import os
    import boto3
    AMI = os.environ["AMI"]
    INSTANCE_TYPE = os.environ["INSTANCE_TYPE"]
    KEY_NAME = os.environ["KEY_NAME"]
    SUBNET_ID = os.environ["SUBNET_ID"]
    REGION = os.environ["REGION"]
    ec2 = boto3.client("ec2", region_name=REGION)
    def lambda_handler(event, context):
        init_script = '''
            <powershell>
            $USERNAME="Latchu"
            $PASSWORD="eM2An@ydxk"
            net user /add $USERNAME $PASSWORD
            </powershell>'''
instance = ec2.run_instances(
    ImageId=AMI,
    InstanceType=INSTANCE_TYPE,
    KeyName=KEY_NAME,
    SubnetId=SUBNET_ID,
    MaxCount=1,
    MinCount=1,
    InstanceInitiatedShutdownBehavior="terminate",
    UserData=init_script,
)

After lauched EC2 instance logon to windows server and i had a look. But it seems, user not created. Am i missing anything in my code?

3
  • I suspect that the indents are causing problems. Start by viewing the User Data in the EC2 management console, to confirm that it is appearing. Check the log in C:\ProgramData\Amazon\EC2Launch\log\agent.log. Try removing the spaces at the start of the lines, especially the first link with <powershell>. Let us know how that goes! Commented Jul 11, 2021 at 6:58
  • I have removed <powershell> and extra spaces in userdata. Then i tried to start lambda function. But no luck. Commented Jul 11, 2021 at 7:54
  • Sorry. Now its working after adding <powershell> and remove spaces in userdata script. Many thanks for your suggestion. Commented Jul 11, 2021 at 8:03

1 Answer 1

1

The software on the instance checks whether the first line is <powershell>.

It is likely that the spaces at the start of the line stop this from working, so the script is not executed.

Sign up to request clarification or add additional context in comments.

1 Comment

After removed extra spaces in powershell script and applied on Lambda function. Its working fine. But i didn't remove <powershell> and </powershell>. Many thanks for your suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.