Use AttachPolicy
with an Amazon SDK or CLI
The following code examples show how to use AttachPolicy
.
- .NET
-
- Amazon SDK for .NET
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon 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 Amazon SDK for .NET API Reference.
-
- CLI
-
- Amazon 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:
aws organizations attach-policy --policy-id
p-examplepolicyid111
--target-idou-examplerootid111-exampleouid111
Example 2
The following example shows how to attach a service control policy directly to an account:
aws organizations attach-policy --policy-id
p-examplepolicyid111
--target-id333333333333
-
For API details, see AttachPolicy
in Amazon 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 Amazon 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 Amazon SDK for Python (Boto3) API Reference.
-
For a complete list of Amazon SDK developer guides and code examples, see Using Amazon Organizations with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.