Sub topic 14
Automating with the AWS CLI and CloudFormation
This chapter assumes you know basic IAM (roles, policies, policy JSON), AWS Organizations (management account, member accounts, OUs), and how to run AWS CLI commands. It also assumes you have met permission sets, groups, and account assignments in earlier chapters. Here you will script the same setup, then declare it as code.
Why automate
Clicking through the console works for three accounts. It does not work for sixty. Automation gives you:
- Repeatable results. The same permission set looks the same in every environment.
- Review. Changes go through pull requests instead of happening unseen.
- Recovery. You can rebuild the setup from source.
Identity Center exposes two APIs for this. The sso-admin service manages permission sets and assignments. The identitystore service manages users and groups. The organizations service lists the accounts you assign to.
Run these commands in the management account, or in a delegated administrator account if you have set one up. Identity Center has a home Region, so use that Region for every call.
The shape of the workflow
Every automated setup follows the same order.
Step 1: Create a permission set with the CLI
Most sso-admin calls need the instance ARN. Look it up once and reuse it. The script below creates a permission set named ReadOnlyAuditor with a four-hour session and attaches the AWS managed ReadOnlyAccess policy.
INSTANCE_ARN=$(aws sso-admin list-instances --query 'Instances[0].InstanceArn' --output text)
PS_ARN=$(aws sso-admin create-permission-set \
--instance-arn "$INSTANCE_ARN" \
--name ReadOnlyAuditor \
--description "Read-only access for auditors" \
--session-duration PT4H \
--query 'PermissionSet.PermissionSetArn' --output text)
aws sso-admin attach-managed-policy-to-permission-set \
--instance-arn "$INSTANCE_ARN" \
--permission-set-arn "$PS_ARN" \
--managed-policy-arn arn:aws:iam::aws:policy/ReadOnlyAccessNotes on this script:
--session-durationuses ISO 8601 format.PT4Hmeans four hours. The allowed range is one to twelve hours.create-permission-setonly creates the definition. No role exists in any account yet.- The
--queryand--output textoptions pull one value into a shell variable, so later commands can use it.
Other policy types use sibling commands. These include put-inline-policy-to-permission-set, attach-customer-managed-policy-reference-to-permission-set, and put-permissions-boundary-to-permission-set.
Step 2: Assign a group to accounts
An assignment ties together three things: a principal (user or group), a permission set, and one account. The API takes one account at a time. It does not accept an OU as a target. To cover an OU, loop over its accounts.
IDENTITY_STORE_ID=$(aws sso-admin list-instances --query 'Instances[0].IdentityStoreId' --output text)
GROUP_ID=$(aws identitystore get-group-id \
--identity-store-id "$IDENTITY_STORE_ID" \
--alternate-identifier '{"UniqueAttribute":{"AttributePath":"DisplayName","AttributeValue":"Auditors"}}' \
--query 'GroupId' --output text)
for ACCOUNT_ID in $(aws organizations list-accounts-for-parent \
--parent-id ou-xxxx-xxxxxxxx \
--query 'Accounts[?Status==`ACTIVE`].Id' --output text); do
aws sso-admin create-account-assignment \
--instance-arn "$INSTANCE_ARN" \
--target-id "$ACCOUNT_ID" \
--target-type AWS_ACCOUNT \
--permission-set-arn "$PS_ARN" \
--principal-type GROUP \
--principal-id "$GROUP_ID"
doneThings to know about this loop:
- Groups are looked up by display name, then referenced by ID. The API requires the ID.
list-accounts-for-parentreturns only accounts directly under that parent. Accounts in child OUs are not included. Recurse withlist-organizational-units-for-parentif you need them.- The filter on
Status==ACTIVEskips suspended accounts. - Replace
ou-xxxx-xxxxxxxxwith your own OU ID.
Assignments are asynchronous
create-account-assignment returns a request status, not a finished result. The role is created in the background. The response includes a RequestId that you can check with describe-account-assignment-creation-status. In scripts that must know the outcome, poll until the status is SUCCEEDED or FAILED.
Creating an assignment that already exists is not harmful, but the call may report a conflict or failure for that request. Make your scripts tolerant: list existing assignments with list-account-assignments first, or treat the "already exists" case as success.
Also watch for throttling. A loop over hundreds of accounts can hit API rate limits. Add a short sleep or retry with backoff.
Step 3: Re-provision after a change
Changing a permission set that is already assigned updates its definition, but the roles in the accounts do not change on their own. Some changes are applied automatically through the API, but you should not rely on that. Run provision-permission-set to push the update.
aws sso-admin provision-permission-set \
--instance-arn "$INSTANCE_ARN" \
--permission-set-arn "$PS_ARN" \
--target-type ALL_PROVISIONED_ACCOUNTSThe target type ALL_PROVISIONED_ACCOUNTS updates every account where the permission set is already in use. Use AWS_ACCOUNT with --target-id to update a single account. This is useful when testing a change on one account before rolling it out.
Like assignment creation, provisioning is asynchronous. Check it with describe-permission-set-provisioning-status. The list-accounts-for-provisioned-permission-set command, with the filter --provisioning-status LATEST_PERMISSION_SET_NOT_PROVISIONED, shows accounts that are behind.
| Command | What it does |
|---|---|
| `create-permission-set` | Creates the definition only |
| `create-account-assignment` | Creates the assignment and provisions the role |
| `provision-permission-set` | Re-applies the current definition to existing roles |
| `delete-account-assignment` | Removes the assignment and the role |
Step 4: Declare it in CloudFormation
Scripts describe actions. CloudFormation describes the desired end state. It tracks what it created, so removing a resource from the template removes it from AWS. The template below declares the same permission set and one assignment.
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
InstanceArn:
Type: String
AuditorsGroupId:
Type: String
TargetAccountId:
Type: String
Resources:
ReadOnlyAuditor:
Type: AWS::SSO::PermissionSet
Properties:
InstanceArn: !Ref InstanceArn
Name: ReadOnlyAuditor
SessionDuration: PT4H
ManagedPolicies:
- arn:aws:iam::aws:policy/ReadOnlyAccess
AuditorsAssignment:
Type: AWS::SSO::Assignment
Properties:
InstanceArn: !Ref InstanceArn
PermissionSetArn: !GetAtt ReadOnlyAuditor.PermissionSetArn
PrincipalId: !Ref AuditorsGroupId
PrincipalType: GROUP
TargetId: !Ref TargetAccountId
TargetType: AWS_ACCOUNTDeploy it in the management account or a delegated administrator account, in the Identity Center home Region:
aws cloudformation deploy \
--template-file identity-center.yaml \
--stack-name identity-center-auditors \
--parameter-overrides \
InstanceArn="$INSTANCE_ARN" \
AuditorsGroupId="$GROUP_ID" \
TargetAccountId=111122223333Points to understand:
!GetAtt ReadOnlyAuditor.PermissionSetArnmakes the assignment depend on the permission set, so CloudFormation creates them in the right order.- Changing a permission set property in the template and updating the stack also provisions the change to assigned accounts. You do not run
provision-permission-setyourself. - One
AWS::SSO::Assignmentresource covers one principal, one permission set, and one account. For many accounts you need many resources.
Scaling the template
Writing sixty assignment resources by hand is error-prone. Options include:
- Generate the template from a list with a script or a tool such as the AWS CDK or a template preprocessor.
- Use the
AWS::LanguageExtensionstransform withFn::ForEachto loop over a list of account IDs inside the template. - Split the stack by purpose, for example one stack for permission sets and one per team for assignments.
A common pattern keeps permission sets in one stack and exports their ARNs. Assignment stacks then import them, so a permission set change and an assignment change have separate review paths.
CLI or CloudFormation?
| Question | CLI scripts | CloudFormation |
|---|---|---|
| Handles drift and removal | You write the logic | Built in |
| Good for one-off fixes | Yes | Heavy |
| Loops over OUs dynamically | Easy | Needs generation |
| Review history | Depends on your repo | Template diff and change sets |
Many teams use CloudFormation for the stable core and the CLI for investigation and bulk operations.
Common problems
- Wrong account or Region. The
sso-adminAPI works only in the account hosting the instance (management or delegated administrator) and in the home Region. Calls elsewhere fail or return no instance. - Mixing manual and stack changes. If someone edits a CloudFormation-managed permission set in the console, the next stack update may overwrite the edit, or fail. Pick one owner for each resource.
- Group not found.
get-group-idfails if the display name does not match exactly. Groups synced from an external identity provider appear only after the first sync. - Forgetting to re-provision. A policy change that is not pushed leaves some accounts with the old role. Check provisioning status after scripted changes.
- Deleting a permission set in use. You must remove its account assignments first. The delete call is rejected otherwise.
Exercise
You changed the inline policy on a permission set that is assigned to 40 accounts by running a CLI call. Two days later, users report the old permissions in several accounts. What command do you run, and how do you find the accounts that are behind?
Show answer
Run aws sso-admin provision-permission-set with --target-type ALL_PROVISIONED_ACCOUNTS for that permission set, so the updated definition reaches the existing roles. To find the lagging accounts, run aws sso-admin list-accounts-for-provisioned-permission-set with --provisioning-status LATEST_PERMISSION_SET_NOT_PROVISIONED. Check progress of the provisioning request with describe-permission-set-provisioning-status.
Exercise
Your script must give the Auditors group access to every active account directly under one OU. Why can't you pass the OU ID to create-account-assignment, and what do you do instead?
Show answer
The TargetType accepts only AWS_ACCOUNT, so the target must be an account ID. List the accounts with aws organizations list-accounts-for-parent, filter to ACTIVE, and call create-account-assignment once per account. Accounts in child OUs need an extra recursive listing.
Exercise
In the CloudFormation template, why does the assignment use !GetAtt ReadOnlyAuditor.PermissionSetArn rather than a hard-coded ARN?
Show answer
The ARN is only known after the permission set is created. !GetAtt supplies it and also makes CloudFormation create the permission set before the assignment.