ATTACH A CUSTOMER MANAGED POLICY TO AN IAM ROLE
This guide shows you how to give an IAM role permissions from a customer managed
policy. Both the role and the policy are Swamp behaviors from @swamp/aws/iam.
The policy is attached to the role through its own Roles argument.
Prerequisites
- AWS credentials allowed to create IAM roles and policies, available through the AWS environment variables or profile, or wired from a vault (see Use AWS Secrets Manager)
- A Swamp repository
Pull the extension
swamp extension pull @swamp/aws/iamThe output looks like:
INF extension·pull: Pulling "@swamp/aws/iam"@"2026.10.13.1"
INF extension·pull: Identity verified: "@swamp/aws/iam"@"2026.10.13.1"
INF extension·pull: Pulled "@swamp/aws/iam"@"2026.10.13.1"
INF extension·pull: Extracted 30 files:Define the role
If the role already exists as a behavior, skip this step and use its RoleName
in the policy below. If not, create a behavior named app-role of type
@swamp/aws/iam/role (see
Create and Run a Behavior)
with a trust policy for the service that will assume it. This example uses
Lambda:
globalArguments:
RoleName: app-role
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRoleDefine the managed policy
Create a behavior named app-s3-read of type @swamp/aws/iam/managed-policy.
The required arguments are name and PolicyDocument. List the role in Roles
by its name, not its ARN:
globalArguments:
name: app-s3-read
ManagedPolicyName: app-s3-read
Description: Read access to the app artifacts bucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:ListBucket
Resource:
- arn:aws:s3:::app-artifacts
- arn:aws:s3:::app-artifacts/*
Roles:
- app-roleTo attach the same policy to users or groups as well, add their names to Users
or Groups.
Create the role, then the policy
The policy refers to the role by name, so create the role in AWS first:
swamp behavior run app-role createThis command creates app-role in AWS and writes its IAM Role resource state.
Then create the policy:
swamp behavior run app-s3-read createThis command creates the customer managed policy app-s3-read, attaches it to
app-role, and writes its IAM ManagedPolicy resource state.
Confirm the attachment
swamp behavior run app-s3-read syncThis command reads the policy back from AWS and writes its current state, including the roles it is attached to, to the IAM ManagedPolicy resource state.
To attach an AWS managed policy instead of your own, add its ARN to the role's
ManagedPolicyArns argument and run the role's update method. Do not create a
managed policy behavior for it. Each policy attachment should belong to only one
behavior.
Understanding AWS IAM automation in Swamp
explains why. Refer to the
extensions reference for every
argument of both types.