Best Python code snippet using localstack_python
flask_api.py
Source:flask_api.py  
...7                    aws_secret_access_key='4t6MY645JSp0MkLgn0bRojCwq+Fd/5nCXmM/rinU'8)9app = Flask(__name__)10app.secret_key = 'somesecretkeythatonlyishouldknow'11def create_login_profile(user_name,password):12    iam.create_user( UserName=user_name)13    response = iam.create_login_profile(14    UserName= user_name,15    Password= password,16    PasswordResetRequired=False17    )18    iam.attach_user_policy(19        UserName = user_name,20        PolicyArn='arn:aws:iam::164466165486:policy/EC2_FamilyRestrict'21    )22    return "User Created"23def list_instances_by_tag_value(tagkey, tagvalue):24    client = boto3.client('ec2',25                      region_name="us-east-1",26                    aws_access_key_id='AKIASMSXSQ3XBAHGPEJT', 27                    aws_secret_access_key='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')28    # When passed a tag key, tag value this will return a list of InstanceIds that were found.29 30    response = client.describe_instances(31        Filters=[32            {33                'Name': 'tag:'+tagkey,34                'Values': [tagvalue]35            }36        ]37    )38    instancelist = []39    for reservation in (response["Reservations"]):40        for instance in reservation["Instances"]:41            instancelist.append(instance["InstanceId"])42    return instancelist43def delete_user(user_name):44    client = boto3.client('ec2',45                      region_name="us-east-1",46                    aws_access_key_id='AKIASMSXSQ3XBAHGPEJT', 47                    aws_secret_access_key='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')48    list = list_instances_by_tag_value('owner','user/'+user_name)49    for l in list:50        try:51            response = client.terminate_instances(InstanceIds=[l], DryRun=False)52            print(response)53        except ClientError as e:54            print(e)55    iam.detach_user_policy(56        UserName = user_name,57        PolicyArn='arn:aws:iam::164466165486:policy/EC2_FamilyRestrict'58    )59    iam.delete_login_profile(60        UserName= user_name61    )62    iam.delete_user(63        UserName= user_name64    )65@app.before_request66def before_request():67    print("session data: "+ str(session))68@app.route('/createuser', methods=['GET', 'POST'])69def createuser():70    userid = "yash"+str(randrange(100000, 999999))+"qyqyq"71    passwd = "Eric@123"72    session['user_name'] = userid73    session_start_time = dt.now()74    session['start_time'] = session_start_time75    create_login_profile(userid, passwd)76    return userid77@app.route('/deleteuser', methods=['GET', 'POST'])78def deleteuser():79    if request.method == 'POST':80        t_id = request.json['user']81        print('****************************************************************'+t_id)82        delete_user(t_id)83        return "User Deleted"84if __name__ == "__main__":85    app.run(debug=True)...main.py
Source:main.py  
...15    except IOError as error:16        print('The dictionary file {} could not be found, please ensure this file is present on your system'.format(dict_file))17        return error18     19def create_login_profile(client, username, password, reset=True):20    '''21        Provide console access for a user22        resource: i.e: `iam = boto3.resource('iam)`23        username: must be a valid IAM username24        password: must comply with the IAM password policy25        reset: boolean value denoting if a password reset is required26    '''27    response = client.create_login_profile(28        UserName=username,29        Password=password,30        PasswordResetRequired=reset31    )32    print(response)33    return 34def delete_user(client, username):35    '''36        Delete an IAM user37    '''38    response = client.delete_user(39        UserName=username40    )41    print(response)42def user_exists(client, username):43    '''44        Check if a given IAM user exists, output result45    '''46    try:47        resp = client.get_user(48            UserName=username49        )50        print("Username {} already exists. Please provide a unique username".format(username))51        return True52    except ClientError as error:53        if error.response['Error']['Code'] == 'NoSuchEntity':54            print("User {} does not exist".format(username))55            return False56        else:57            print(error)58def create_user(client, username, password):59    '''Create an IAM user'''60    if user_exists(client, username) == True:61        return62    elif user_exists(client, username) == False:63        response = client.create_user(64            UserName=username65            )66        create_login_profile(client, username, password)67        print()68        return69        70def main(test=True):71    '''Main function'''72    if test == True:73        test_password = generate_password()74        test_client =  boto3.client('iam')75        test_username = 'test123'76        if user_exists(test_client, test_username):77            delete_user(test_client, test_username)78        print(test_password)79        print(test_client.get_account_password_policy())80        create_user(test_client, test_username, test_password)...create_iam_user_from_csv.py
Source:create_iam_user_from_csv.py  
...2223    def create_user(self, username):24        return self.iam_con.create_user(UserName = username)2526    def create_login_profile(self, username, password):27        return self.iam_con.create_login_profile(UserName = username, Password = password, PasswordResetRequired = True)2829    def create_access_key(self, username):30        return self.iam_con.create_access_key(UserName = username)3132    def attach_policy(self, username, arn):33        return self.iam_con.attach_user_policy(UserName = username, PolicyArn = arn)3435def random_password(size = 16, chars = string.ascii_letters + string.digits + "!@#$%^&*()"):36    return ''.join(choice(chars) for each_char in range(size))3738def get_user_from_csv(csvfile):39    with open(csvfile, "r") as users:40        reader = csv.DictReader(users)41        user_list = list(reader)42        43    return user_list4445def main():46    user = IAM_User()47    user_list = get_user_from_csv("user.csv")48    for each_user in user_list:49        username = each_user["IAM_User_Name"]50        password = random_password()51        policy_arn = each_user["PolicyARN"]52        try:53            user.create_user(username)54            print(f"The user {username} is created")55        except Exception as e:56            print(e)57            sys.exit(0)58        59        if each_user["Console_Access"] == "Yes":60            user.create_login_profile(username, password)61            print(f"The console login password is {password}")6263        if each_user["Programatic_Access"] == "Yes":64            response = user.create_access_key(username)65            print(f"AccessKeyId = {response['AccessKey']['AccessKeyId']}\nSecretAccessKey = {response['AccessKey']['SecretAccessKey']}")66        67        user.attach_policy(username, policy_arn)68        print(f"This user has {policy_arn.split('/')[1]} permission")69        print("===========================================")7071if __name__ == "__main__":
...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
