def Run(self, args):
        """Creates or updates a custom constraint from a JSON or YAML file.

    This first converts the contents of the specified file into a custom
    constraint object. It then fetches the current custom constraint using
    GetCustomConstraint. If it does not exist, the custom constraint is created
    using CreateCustomConstraint. If it does, the retrieved custom constraint is
    checked to see if it needs to be updated. If so, the custom constraint is
    updated using UpdateCustomConstraint.

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

    Returns:
      The created or updated custom constraint.
    """
        org_policy_api = org_policy_service.OrgPolicyApi(self.ReleaseTrack())
        input_custom_constraint = utils.GetCustomConstraintMessageFromFile(
            args.custom_constraint_file, self.ReleaseTrack())
        if not input_custom_constraint.name:
            raise exceptions.InvalidInputError(
                'Name field not present in the custom constraint.')
        if not input_custom_constraint.name.startswith('organizations/'):
            raise exceptions.InvalidInputError(
                'Name field contains invalid resource type: ' +
                input_custom_constraint.name +
                '. Custom constraints can be created only on organization resources.'
            )
        try:
            custom_constraint = org_policy_api.GetCustomConstraint(
                input_custom_constraint.name)
        except api_exceptions.HttpNotFoundError:
            create_response = org_policy_api.CreateCustomConstraint(
                input_custom_constraint)
            log.CreatedResource(input_custom_constraint.name,
                                'custom constraint')
            return create_response
        if custom_constraint == input_custom_constraint:
            return custom_constraint
        update_response = org_policy_api.UpdateCustomConstraint(
            input_custom_constraint)
        log.UpdatedResource(input_custom_constraint.name, 'custom constraint')
        return update_response
コード例 #2
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
コード例 #3
0
def _GetPolicyNameTokens(policy_name):
    """Returns the individual tokens from the policy name.

  Args:
    policy_name: The name of the policy. A policy name has the following syntax:
      [organizations|folders|projects]/{resource_id}/policies/{constraint_name}.
  """
    policy_name_tokens = policy_name.split('/')
    if len(policy_name_tokens) != 4:
        raise exceptions.InvalidInputError(
            "Invalid policy name '{}': Name must be in the form [projects|folders|organizations]/{{resource_id}}/policies/{{constraint_name}}."
            .format(policy_name))
    return policy_name_tokens
コード例 #4
0
def _GetConstraintNameTokens(constraint_name):
    """Returns the individual tokens from the constraint name.

  Args:
    constraint_name: The name of the constraint. A constraint name has the
      following syntax:
        [organizations|folders|projects]/{resource_id}/constraints/{constraint_name}.
  """
    constraint_name_tokens = constraint_name.split('/')
    if len(constraint_name_tokens) != 4:
        raise exceptions.InvalidInputError(
            "Invalid constraint name '{}': Name must be in the form [projects|folders|organizations]/{{resource_id}}/constraints/{{constraint_name}}."
            .format(constraint_name))
    return constraint_name_tokens
コード例 #5
0
  def Run(self, args):
    """Extends the superclass method to do validation and disable creation of a new policy if --remove is specified.

    Args:
      args: argparse.Namespace, An object that contains the values for the
        arguments specified in the Args method.
    """
    if not args.value and args.remove:
      raise exceptions.InvalidInputError(
          'One or more values need to be specified if --remove is specified.')

    if args.remove:
      self.disable_create = True

    return super(Deny, self).Run(args)
コード例 #6
0
ファイル: allow.py プロジェクト: Guliux10/bchacks_deepbreath
    def Run(self, args):
        """Extends the superclass method to do validation and disable creation of a new policy if --remove is specified.

    Args:
      args: argparse.Namespace, An object that contains the values for the
        arguments specified in the Args method.
    """
        if not args.value and args.remove:
            raise exceptions.InvalidInputError(
                'One or more values need to be specified if --remove is specified.'
            )

        if args.remove:
            self.disable_create = True

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

        return super(Allow, self).Run(args)
コード例 #7
0
ファイル: utils.py プロジェクト: linsole/CS61A
def GetMessageFromFile(filepath, message):
  """Returns a message populated from the JSON or YAML file on the specified filepath.

  Args:
    filepath: str, A local path to an object specification in JSON or YAML
      format.
    message: messages.Message, The message class to populate from the file.
  """
  file_contents = files.ReadFileContents(filepath)

  try:
    yaml_obj = yaml.load(file_contents)
    json_str = json.dumps(yaml_obj)
  except yaml.YAMLParseError:
    json_str = file_contents

  try:
    return encoding.JsonToMessage(message, json_str)
  except Exception as e:
    raise exceptions.InvalidInputError('Unable to parse file [{}]: {}.'.format(
        filepath, e))
コード例 #8
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.
    """
        org_policy_api = org_policy_service.OrgPolicyApi(self.ReleaseTrack())
        input_policy = utils.GetMessageFromFile(args.policy_file,
                                                self.ReleaseTrack())
        if not input_policy.name:
            raise exceptions.InvalidInputError(
                'Name field not present in the organization policy.')

        try:
            policy = org_policy_api.GetPolicy(input_policy.name)
        except api_exceptions.HttpNotFoundError:
            create_response = org_policy_api.CreatePolicy(input_policy)
            log.CreatedResource(input_policy.name, 'policy')
            return create_response

        if policy == input_policy:
            return policy

        update_response = org_policy_api.UpdatePolicy(input_policy)
        log.UpdatedResource(input_policy.name, 'policy')
        return update_response
コード例 #9
0
def GetCustomConstraintMessageFromFile(filepath, release_track):
    """Returns a message populated from the JSON or YAML file on the specified filepath.

  Args:
    filepath: str, A local path to an object specification in JSON or YAML
      format.
    release_track: calliope.base.ReleaseTrack, Release track of the command.
  """
    file_contents = files.ReadFileContents(filepath)

    try:
        yaml_obj = yaml.load(file_contents)
        json_str = json.dumps(yaml_obj)
    except yaml.YAMLParseError:
        json_str = file_contents

    org_policy_messages = org_policy_service.OrgPolicyMessages(release_track)
    message = getattr(org_policy_messages,
                      'GoogleCloudOrgpolicyV2CustomConstraint')
    try:
        return encoding.JsonToMessage(message, json_str)
    except Exception as e:
        raise exceptions.InvalidInputError(
            'Unable to parse file [{}]: {}.'.format(filepath, e))