Use AttachPolicy with an AWS SDK or CLI - AWS SDK Code Examples

There are more AWS SDK examples available in the AWS Doc SDK Examples GitHub repo.

Use AttachPolicy with an AWS SDK or CLI

The following code examples show how to use AttachPolicy.

.NET
AWS SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

using System; using System.Threading.Tasks; using Amazon.Organizations; using Amazon.Organizations.Model; /// <summary> /// Shows how to attach an AWS Organizations policy to an organization, /// an organizational unit, or an account. /// </summary> public class AttachPolicy { /// <summary> /// Initializes the Organizations client object and then calls the /// AttachPolicyAsync method to attach the policy to the root /// organization. /// </summary> public static async Task Main() { IAmazonOrganizations client = new AmazonOrganizationsClient(); var policyId = "p-00000000"; var targetId = "r-0000"; var request = new AttachPolicyRequest { PolicyId = policyId, TargetId = targetId, }; var response = await client.AttachPolicyAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"Successfully attached Policy ID {policyId} to Target ID: {targetId}."); } else { Console.WriteLine("Was not successful in attaching the policy."); } } }
  • For API details, see AttachPolicy in AWS SDK for .NET API Reference.

CLI
AWS CLI

To attach a policy to a root, OU, or account

Example 1

The following example shows how to attach a service control policy (SCP) to an OU:

<userinput>aws organizations attach-policy --policy-id <replaceable>p-examplepolicyid111</replaceable> --target-id <replaceable>ou-examplerootid111-exampleouid111</replaceable></userinput>

Example 2

The following example shows how to attach a service control policy directly to an account:

<userinput>aws organizations attach-policy --policy-id <replaceable>p-examplepolicyid111</replaceable> --target-id <replaceable>333333333333</replaceable></userinput>
  • For API details, see AttachPolicy in AWS CLI Command Reference.

Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

def attach_policy(policy_id, target_id, orgs_client): """ Attaches a policy to a target. The target is an organization root, account, or organizational unit. :param policy_id: The ID of the policy to attach. :param target_id: The ID of the resources to attach the policy to. :param orgs_client: The Boto3 Organizations client. """ try: orgs_client.attach_policy(PolicyId=policy_id, TargetId=target_id) logger.info("Attached policy %s to target %s.", policy_id, target_id) except ClientError: logger.exception( "Couldn't attach policy %s to target %s.", policy_id, target_id ) raise
  • For API details, see AttachPolicy in AWS SDK for Python (Boto3) API Reference.