Setting Password Policies via CloudFormation

cloudformation

One of the first things you set up in any new account is an IAM password policy.  Ideally, you’d like to create as much as possible in your AWS account with CloudFormation templates. Particularly when you’d like to use multiple accounts for security or billing purposes, having to go through a bunch of manual steps every time you create an account is not ideal. Unfortunately, IAM password policies are one of those things you still can’t set up in CloudFormation natively.

This post demonstrates how to use a Custom Resource to extend CloudFormation via Lambda functions, automating the process of specifying your IAM password policy.

Custom Resources can get you into trouble, creating resources that are difficult to track and manage throughout the lifecycle of your stack. However, sometimes they’re the only available option. We have a simple security stack we create with every account, which defines an IAM password policy and sets a few initial security groups. To set the password policy, we use a simple Python/Boto-based Lambda, and the key function uses Boto to create or update an existing policy based on your parameters:

          def update_policy():
            try:

              response = iam.update_account_password_policy(
                  AllowUsersToChangePassword=True,
                  HardExpiry=False,
                  MaxPasswordAge=${MaxPasswordAge},
                  MinimumPasswordLength=${MinPasswordLength},
                  RequireLowercaseCharacters=${RequireLowercaseChars},
                  RequireNumbers=${RequireNumbers},
                  RequireSymbols=${RequireSymbols},
                  RequireUppercaseCharacters=${RequireUppercaseChars},
                  PasswordReusePrevention=${PasswordHistory})

              return(True, response)
            except Exception as e:
              return (False, "Cannot update policy: " + str(e))

As you can see, you can do some complex things with custom resources. As you can hopefully also see, you probably shouldn’t. Custom resources trust you to clean up after yourself, and good custom resource includes create, update and delete handlers. So, be careful.

Get the full template from our GitHub repo.

Add a Comment

Your email address will not be published. Required fields are marked *