Example #1
0
  def Run(self, args):
    """Gets the (effective) organization policy.

    If --effective is not specified, then the policy is retrieved using
    GetPolicy.

    If --effective is specified, then the effective policy is retrieved using
    GetEffectivePolicy.

    Args:
      args: argparse.Namespace, An object that contains the values for the
        arguments specified in the Args method.

    Returns:
       The retrieved policy.
    """
    policy_service = org_policy_service.PolicyService()
    org_policy_messages = org_policy_service.OrgPolicyMessages()

    policy_name = utils.GetPolicyNameFromArgs(args)

    if args.effective:
      get_request = org_policy_messages.OrgpolicyPoliciesGetEffectivePolicyRequest(
          name=policy_name)
      return policy_service.GetEffectivePolicy(get_request)

    get_request = org_policy_messages.OrgpolicyPoliciesGetRequest(
        name=policy_name)
    return policy_service.Get(get_request)
Example #2
0
  def Run(self, args):
    policy_service = org_policy_service.PolicyService()
    constraint_service = org_policy_service.ConstraintService()
    org_policy_messages = org_policy_service.OrgPolicyMessages()

    parent = utils.GetResourceFromArgs(args)

    list_policies_request = org_policy_messages.OrgpolicyPoliciesListRequest(
        parent=parent)
    list_policies_response = policy_service.List(list_policies_request)
    policies = list_policies_response.policies

    if args.show_unset:
      list_constraints_request = org_policy_messages.OrgpolicyConstraintsListRequest(
          parent=parent)
      list_constraints_response = constraint_service.List(
          list_constraints_request)
      constraints = list_constraints_response.constraints

      existing_policy_names = {policy.spec.name for policy in policies}
      for constraint in constraints:
        policy_name = org_policy_utils.GetPolicyNameFromConstraintName(
            constraint.name)
        if policy_name not in existing_policy_names:
          stubbed_policy = org_policy_messages.GoogleCloudOrgpolicyV2alpha1Policy(
              spec=org_policy_messages.GoogleCloudOrgpolicyV2alpha1PolicySpec(
                  name=policy_name))
          policies.append(stubbed_policy)

    return policies
Example #3
0
    def Run(self, args):
        """Creates or updates a policy from a JSON or YAML file.

    This first converts the contents of the specified file into a policy object.
    It then fetches the current policy using GetPolicy. If it does not exist,
    the policy is created using CreatePolicy. If it does, the retrieved policy
    is checked to see if it needs to be updated. If so, the policy is updated
    using UpdatePolicy.

    Args:
      args: argparse.Namespace, An object that contains the values for the
        arguments specified in the Args method.

    Returns:
      The created or updated policy.
    """
        policy_service = org_policy_service.PolicyService()
        org_policy_messages = org_policy_service.OrgPolicyMessages()

        input_policy = utils.GetMessageFromFile(
            args.policy_file,
            org_policy_messages.GoogleCloudOrgpolicyV2alpha1Policy)

        if not input_policy.name:
            raise exceptions.InvalidInputError(
                'Name field not present in the organization policy.')

        get_request = org_policy_messages.OrgpolicyPoliciesGetRequest(
            name=input_policy.name)
        try:
            policy = policy_service.Get(get_request)
        except api_exceptions.HttpNotFoundError:
            constraint = org_policy_utils.GetConstraintFromPolicyName(
                input_policy.name)
            parent = org_policy_utils.GetResourceFromPolicyName(
                input_policy.name)

            create_request = org_policy_messages.OrgpolicyPoliciesCreateRequest(
                constraint=constraint,
                parent=parent,
                googleCloudOrgpolicyV2alpha1Policy=input_policy)
            create_response = policy_service.Create(create_request)
            log.CreatedResource(input_policy.name, 'policy')
            return create_response

        if policy == input_policy:
            return policy

        update_request = org_policy_messages.OrgpolicyPoliciesPatchRequest(
            name=input_policy.name,
            forceUnconditionalWrite=False,
            googleCloudOrgpolicyV2alpha1Policy=input_policy)
        update_response = policy_service.Patch(update_request)
        log.UpdatedResource(input_policy.name, 'policy')
        return update_response
Example #4
0
    def Run(self, args):
        """Deletes a whole policy or removes rules containing the specified condition from the policy.

    If --condition is not specified, then the policy is deleted using
    DeletePolicy.

    If --condition is specified, then the policy is fetched using GetPolicy. It
    then searches for and removes the rules that contain the specified condition
    from the policy. If the policy is empty after this operation and
    inheritFromParent is False, the policy is deleted using DeletePolicy. If
    not, the policy is updated using UpdatePolicy.

    Args:
      args: argparse.Namespace, An object that contains the values for the
        arguments specified in the Args method.

    Returns:
       If the policy is deleted, then messages.GoogleProtobufEmpty. If only
       a partial delete is issued, then the updated policy.
    """
        policy_service = org_policy_service.PolicyService()
        org_policy_messages = org_policy_service.OrgPolicyMessages()

        policy_name = utils.GetPolicyNameFromArgs(args)

        if args.IsSpecified('condition') and args.IsSpecified('label_parent'):
            utils.TransformLabelDisplayNameConditionToLabelNameCondition(args)

        if args.condition is not None:
            get_request = org_policy_messages.OrgpolicyPoliciesGetRequest(
                name=policy_name)
            policy = policy_service.Get(get_request)

            new_policy = copy.deepcopy(policy)
            new_policy.spec.rules = org_policy_utils.GetNonMatchingRulesFromPolicy(
                policy, args.condition)

            if policy == new_policy:
                return policy

            if new_policy.spec.rules or new_policy.spec.inheritFromParent:
                update_request = org_policy_messages.OrgpolicyPoliciesPatchRequest(
                    name=policy_name,
                    forceUnconditionalWrite=False,
                    googleCloudOrgpolicyV2alpha1Policy=new_policy)
                update_response = policy_service.Patch(update_request)
                log.UpdatedResource(policy_name, 'policy')
                return update_response

        delete_request = org_policy_messages.OrgpolicyPoliciesDeleteRequest(
            name=policy_name)
        delete_response = policy_service.Delete(delete_request)
        log.DeletedResource(policy_name, 'policy')
        return delete_response
    def __init__(self, cli, context):
        """Extends superclass method and add shared properties as well as a new property to toggle creation behavior.

    The new `disable_create` toggle controls behavior for when a policy cannot
    be found. If set to False (the default), the resource in question is
    created. If set to True, an exception is thrown.

    Args:
      cli: calliope.cli.CLI, The CLI object representing this command line tool.
      context: {str:object}, A set of key-value pairs that can be used for
        common initialization among commands.
    """
        super(OrgPolicyGetAndUpdateCommand, self).__init__(cli, context)

        self.policy_service = org_policy_service.PolicyService()
        self.constraint_service = org_policy_service.ConstraintService()
        self.org_policy_messages = org_policy_service.OrgPolicyMessages()

        self.disable_create = False
Example #6
0
  def Run(self, args):
    policy_service = org_policy_service.PolicyService()
    constraint_service = org_policy_service.ConstraintService()
    org_policy_messages = org_policy_service.OrgPolicyMessages()
    output = []

    parent = utils.GetResourceFromArgs(args)

    list_policies_request = org_policy_messages.OrgpolicyPoliciesListRequest(
        parent=parent)
    list_policies_response = policy_service.List(list_policies_request)
    policies = list_policies_response.policies
    for policy in policies:
      spec = policy.spec
      list_policy_set = HasListPolicy(spec)
      boolean_policy_set = HasBooleanPolicy(spec)
      output.append({
          'constraint': policy.name.split('/')[-1],
          'listPolicy': 'SET' if list_policy_set else '',
          'booleanPolicy': 'SET' if boolean_policy_set else '',
          'etag': spec.etag
      })
    if args.show_unset:
      list_constraints_request = org_policy_messages.OrgpolicyConstraintsListRequest(
          parent=parent)
      list_constraints_response = constraint_service.List(
          list_constraints_request)
      constraints = list_constraints_response.constraints

      existing_policy_names = {row['constraint'] for row in output}
      for constraint in constraints:
        constraint_name = constraint.name.split('/')[-1]
        if constraint_name not in existing_policy_names:
          output.append({'constraint': constraint_name})

    return output