To create a cross-account role in Terraform, you need to perform the following steps:
1. Define the IAM role
Define the IAM role in the Terraform configuration
assume_role_policy section, replace
<ACCOUNT_ID> with the AWS account ID of the target account that will assume this role.
2. Attach the necessary policies
Attach the necessary policies to the role. Policies define the permissions granted to the role
"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess" with the ARN of the policy you want to attach to the role.
3. Create a role trust relationship
Create a role trust relationship in the target AWS account to allow the cross-account access. This step is performed outside of Terraform. You need to log in to the target AWS account and create a role trust policy for the role created in the previous steps.
Here’s an example of the trust policy in JSON format:
<SOURCE_ACCOUNT_ID> with the AWS account ID where the role is created.
4. Use the created cross-account role
Use the created cross-account role in other resources by specifying the ARN of the role:
Remember to execute terraform init, terraform plan, and terraform apply to initialize the Terraform configuration, plan the changes, and apply them to create the cross-account role.
5. What you have to do in the target account
In addition to creating the IAM role in the source account using Terraform, you also need to perform the following steps in the target account to establish the cross-account access:
- Log in to the AWS Management Console of the target account.
- Navigate to the IAM service.
- Create a new IAM role that will assume the cross-account role.
- Attach a trust policy to the newly created role to allow the source account to assume this role.
- Click on “Trust relationships” for the role.
- Click on “Edit trust relationship.”
- Specify the trust policy document with the necessary permissions. Here’s an example of the trust policy in JSON format:
<SOURCE_ACCOUNT_ID> with the AWS account ID where the cross-account role is created.
- Click on “Update Trust Policy” to save the changes.
- Once the trust policy is set up, you can use the ARN of the cross-account role in the source account to grant the necessary permissions to resources in the target account.
By configuring the trust policy in the target account, you allow the specified role in the source account to assume the cross-account role and access resources in the target account.