def user(template, user_name, policies=None, generate_key_serial=False): user = User(template=template, title=user_name.replace('_', '')) user.UserName = user_name if policies: if not isinstance(policies, list): policies = [policies] user.Policies = policies if generate_key_serial is not False: key(template=template, user=user, serial=generate_key_serial) return user
def user(self) -> User: """User.""" user = User( "User", template=self.template, ManagedPolicyArns=["arn:aws:iam::aws:policy/AdministratorAccess"], PermissionsBoundary=self.variables["PermissionsBoundary"], UserName=self.username or NoValue, ) self.add_output(user.title, user.ref()) self.add_output(f"{user.title}Arn", user.get_att("Arn")) return user
def add_user(c, UserName, model, named=False): cfn_name = scrub_name(UserName + "User") kw_args = { "Path": "/", "Groups": [], "ManagedPolicyArns": [], "Policies": [], } if named: kw_args["UserName"] = UserName if "groups" in model: kw_args["Groups"] = parse_imports(c, model["groups"]) if "managed_policies" in model: kw_args["ManagedPolicyArns"] = parse_managed_policies( c, model["managed_policies"], UserName) if "password" in model: kw_args["LoginProfile"] = LoginProfile(Password=model["password"], PasswordResetRequired=True) if "retain_on_delete" in model: if model["retain_on_delete"] is True: kw_args["DeletionPolicy"] = "Retain" c.template[c.current_account].add_resource(User(cfn_name, **kw_args)) if c.config['global']['template_outputs'] == "enabled": c.template[c.current_account].add_output([ Output(cfn_name + "Arn", Description="User " + UserName + " ARN", Value=GetAtt(cfn_name, "Arn"), Export=Export(Sub("${AWS::StackName}-" + cfn_name + "Arn"))) ])
def create_iam_user(stack, name, groups=()): """Add IAM User Resource.""" return stack.stack.add_resource(User( '{0}User'.format(name), Groups=groups, UserName=name ))
def generate_user_with_creds(self, username, password=True, accesskey=True): ## Generate a random password as 8-byte hexadecimal string data = {} assert password == True or accesskey == True 'Must have some credentials' ## Now we declare a user, as we need to reference a user to generate access keys. user = User(self.affiliatename + 'user' + str(username), UserName=Join("", [username, Ref(AWS_REGION)])) user_t = self.template.add_resource(user) if password == True: ## User can reset if desired ResetRequired = False default_password = secrets.token_hex(8) lp = LoginProfile(Password=default_password, PasswordResetRequired=ResetRequired) data['password'] = [] data['password'].append({'password': default_password}) self.template.add_output( Output('Password' + str(self.usercount), Value=default_password, Description='Default password of new user ' + username)) user_t.LoginProfile = lp ## Now we generate access keys: if accesskey == True: key = AccessKey('userkey' + str(self.usercount), UserName=Ref(user)) self.template.add_resource(key) accesskey = Ref(key) secretkey = GetAtt(key, 'SecretAccessKey') self.template.add_output( Output('AccessKey' + str(self.usercount), Value=accesskey, Description='Access Key of user: '******'SecretAccessKey' + str(self.usercount), Value=secretkey, Description='Secret Key of new user: ' + username)) self.users.append(user_t) self.usercount += 1
def render(self, app_name=None, stage_name=None, username=None, function_bucket=None, static_bucket=None, aws_region_name='us-east-1'): self.app_name = app_name self.stage_name = stage_name self.username = username self.function_bucket = function_bucket self.static_bucket = static_bucket self.aws_region_name = aws_region_name self.t = Template() self.t.add_description( "Zappa Template for {app_name}-{stage_name} ".format( app_name=self.app_name, stage_name=self.stage_name)) zappa_user = self.t.add_resource(User(self.username)) zappa_user_keys = self.t.add_resource( AccessKey("ZappaUserKeys", Status="Active", UserName=Ref(zappa_user))) self.t.add_resource( PolicyType( alpha_num_pattern.sub( '', "{app_name}{stage_name}".format( app_name=self.app_name, stage_name=self.stage_name)), Users=[Ref(zappa_user)], PolicyName="zappa-{app_name}-{stage_name}".format( app_name=self.app_name, stage_name=self.stage_name), PolicyDocument=Policy( Version="2012-10-17", Statement=self.get_statement_list(), ), )) self.t.add_output( Output( "AccessKey", Value=Ref(zappa_user_keys), Description="AWSAccessKeyId of new user", )) self.t.add_output( Output( "SecretKey", Value=GetAtt(zappa_user_keys, "SecretAccessKey"), Description="AWSSecretKey of new user", )) return self.t.to_json()
def add_user(c, UserName, model, named=False): cfn_name = c.scrub_name(UserName + "User") kw_args = { "Path": "/", "Groups": [], "ManagedPolicyArns": [], "Policies": [], } if named: kw_args["UserName"] = UserName if "groups" in model: kw_args["Groups"] = c.parse_imports(model["groups"]) if "managed_policies" in model: kw_args["ManagedPolicyArns"] = parse_managed_policies( c, model["managed_policies"], UserName) if "password" in model: kw_args["LoginProfile"] = LoginProfile(Password=model["password"], PasswordResetRequired=True) if "retain_on_delete" in model: if model["retain_on_delete"] is True: kw_args["DeletionPolicy"] = "Retain" fixed_pw = hashlib.md5(UserName.encode('utf-8')).hexdigest() _LOGGER.debug("UserName: {}".format(UserName)) _LOGGER.debug("FixedPW: {}".format(fixed_pw)) c.template[c.current_account].add_resource( User(cfn_name, LoginProfile=LoginProfile(PasswordResetRequired="true", Password=fixed_pw), **kw_args)) if c.config['global']['template_outputs'] == "enabled": c.template[c.current_account].add_output([ Output(cfn_name + "Arn", Description="User " + UserName + " ARN", Value=GetAtt(cfn_name, "Arn"), Export=Export(Sub("${AWS::StackName}-" + cfn_name + "Arn"))) ])
from troposphere import Template, Ref, Output, GetAtt from troposphere.iam import AccessKey, User tpl = Template() tpl.add_version('2010-09-09') tpl.add_description( "Create a superadmin user with all required privileges for this project. " ) # Resources superuser = tpl.add_resource(User( title='czpycon2015', )) access_keys = tpl.add_resource(AccessKey( "Troposphere", Status="Active", UserName=Ref(superuser)) ) # Outputs tpl.add_output(Output( "AccessKey", Value=Ref(access_keys), Description="AWSAccessKeyId of superuser", )) tpl.add_output(Output( "SecretKey", Value=GetAtt(access_keys, "SecretAccessKey"), Description="AWSSecretKey of superuser",
User("myuser", Path="/", LoginProfile=LoginProfile(Password="******"), Policies=[ Policy(PolicyName="giveaccesstoqueueonly", PolicyDocument=awacs.aws.PolicyDocument(Statement=[ awacs.aws.Statement( Effect=awacs.aws.Allow, Action=[awacs.aws.Action("sqs", "*")], Resource=[GetAtt("myqueue", "Arn")], ), awacs.aws.Statement( Effect=awacs.aws.Deny, Action=[awacs.aws.Action("sqs", "*")], NotResource=[GetAtt("myqueue", "Arn")], ), ], )), Policy(PolicyName="giveaccesstotopiconly", PolicyDocument=awacs.aws.PolicyDocument(Statement=[ awacs.aws.Statement( Effect=awacs.aws.Allow, Action=[awacs.aws.Action("sns", "*")], Resource=[Ref("mytopic")], ), awacs.aws.Statement( Effect=awacs.aws.Deny, Action=[awacs.aws.Action("sns", "*")], NotResource=[Ref("mytopic")], ), ], )), ]))
from troposphere.iam import ( AccessKey, Group, LoginProfile, PolicyType, User, UserToGroupAddition, ) t = Template() t.set_description("AWS CloudFormation Sample Template: This template " "demonstrates the creation of IAM User/Group.") cfnuser = t.add_resource( User("CFNUser", LoginProfile=LoginProfile(Password="******"))) cfnusergroup = t.add_resource(Group("CFNUserGroup")) cfnadmingroup = t.add_resource(Group("CFNAdminGroup")) cfnkeys = t.add_resource( AccessKey("CFNKeys", Status="Active", UserName=Ref(cfnuser))) users = t.add_resource( UserToGroupAddition( "Users", GroupName=Ref(cfnusergroup), Users=[Ref(cfnuser)], )) admins = t.add_resource(
# Converted from IAM_Users_Groups_and_Policies.template located at: # http://aws.amazon.com/cloudformation/aws-cloudformation-templates/ from troposphere import GetAtt, Output, Ref, Template from troposphere.iam import AccessKey, Group, LoginProfile, PolicyType from troposphere.iam import User, UserToGroupAddition t = Template() t.add_description("AWS CloudFormation Sample Template: This template " "demonstrates the creation of IAM User/Group.") cfnuser = t.add_resource(User("CFNUser", LoginProfile=LoginProfile("Password"))) cfnusergroup = t.add_resource(Group("CFNUserGroup")) cfnadmingroup = t.add_resource(Group("CFNAdminGroup")) cfnkeys = t.add_resource(AccessKey("CFNKeys", UserName=Ref(cfnuser))) users = t.add_resource( UserToGroupAddition( "Users", GroupName=Ref(cfnusergroup), Users=[Ref(cfnuser)], )) admins = t.add_resource( UserToGroupAddition( "Admins", GroupName=Ref(cfnadmingroup),
"""Creates the bucket user and policies""" from troposphere.iam import User merch_cube_user = User( "merchcubeuser" )
from troposphere.iam import User, Policy, LoginProfile from awacs.aws import Allow, Statement, PolicyDocument, Action t = Template() t.add_resource( User( "ec2user", UserName="******", Path="/", LoginProfile=LoginProfile(Password="******"), Policies=[ Policy( PolicyName="ec2Policy", PolicyDocument=PolicyDocument( Statement=[ Statement( Effect=Allow, Action=[Action("ec2", "RunInstances")], Resource=["*"] ) ] ) ) ] ) ) print(t.to_json())
User('GitHub', UserName=Ref(AWS_STACK_NAME), Policies=[ Policy( PolicyName='AllowCloudFormation', PolicyDocument=PolicyDocument(Statement=[ Statement( Effect=Allow, Action=[Action(prefix='cloudformation', action='*')], Resource=['*'], ) ])), Policy(PolicyName='AllowACM', PolicyDocument=PolicyDocument(Statement=[ Statement( Effect=Allow, Action=[ Action(prefix='acm', action='*'), Action(prefix='route53', action='*'), ], Resource=['*'], ) ])), Policy(PolicyName='AllowS3', PolicyDocument=PolicyDocument(Statement=[ Statement( Effect=Allow, Action=[Action(prefix='s3', action='*')], Resource=['*'], ) ])), Policy(PolicyName='AllowCloudFront', PolicyDocument=PolicyDocument(Statement=[ Statement( Effect=Allow, Action=[Action(prefix='cloudfront', action='*')], Resource=['*'], ) ])) ]))
)) PerforceHelixIAMUser = t.add_resource( User("PerforceHelixIAMUser", Path="/", Policies=[ Policy(PolicyName="PerforceHelixR53DNSPolicy", PolicyDocument=awacs.aws.Policy(Statement=[ awacs.aws.Statement( Effect=awacs.aws.Allow, Action=[ awacs.aws.Action("route53", "ChangeResourceRecordSets") ], Resource=["arn:aws:route53:::change/*"], ), ], )), Policy(PolicyName="PerforceHelixDescribeStackResource", PolicyDocument=awacs.aws.Policy(Statement=[ awacs.aws.Statement( Effect=awacs.aws.Allow, Action=[ awacs.aws.Action("cloudformation", "DescribeStackResource") ], Resource=["*"], ), ], )), ])) WaitHandle = t.add_resource(WaitConditionHandle("WaitHandle", ))