コード例 #1
0
ファイル: utils.py プロジェクト: linsole/CS61A
def _DeleteRulesWithEmptyValues(policy, args):
  """Delete any rule containing the specified condition with empty lists of allowed values and denied values and no other field set.

  Args:
    policy: messages.GoogleCloudOrgpolicyV2alpha1Policy, The policy to be
      updated.
    args: argparse.Namespace, An object that contains the values for the
      arguments specified in the Args method.

  Returns:
    The updated policy.
  """
  new_policy = copy.deepcopy(policy)

  org_policy_messages = org_policy_service.OrgPolicyMessages()

  condition = None
  if args.condition is not None:
    condition = org_policy_messages.GoogleTypeExpr(expression=args.condition)
  empty_values = org_policy_messages.GoogleCloudOrgpolicyV2alpha1PolicyPolicyRuleStringValues(
  )
  matching_empty_rule = org_policy_messages.GoogleCloudOrgpolicyV2alpha1PolicyPolicyRule(
      condition=condition, values=empty_values)
  new_policy.rules = [
      rule for rule in new_policy.rules if rule != matching_empty_rule
  ]

  return new_policy
コード例 #2
0
ファイル: describe.py プロジェクト: linsole/CS61A
  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)
コード例 #3
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
コード例 #4
0
def CreateRuleOnPolicy(policy, condition_expression=None):
  """Creates a rule on the policy that contains the specified condition expression.

  In the case that condition_expression is None, a rule without a condition is
  created.

  Args:
    policy: messages.GoogleCloudOrgpolicyV2alpha1Policy, The policy object to be
      updated.
    condition_expression: str, The condition expression to create a new rule
      with.

  Returns:
    The rule that was created as well as the new policy that includes this
    rule.
  """
  messages = service.OrgPolicyMessages()

  new_policy = copy.deepcopy(policy)

  condition = None
  if condition_expression is not None:
    condition = messages.GoogleTypeExpr(expression=condition_expression)

  new_rule = messages.GoogleCloudOrgpolicyV2alpha1PolicyPolicyRule(
      condition=condition)
  new_policy.rules.append(new_rule)

  return new_rule, new_policy
コード例 #5
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
コード例 #6
0
ファイル: delete.py プロジェクト: Guliux10/bchacks_deepbreath
    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 Run(self, args):
        org_policy_client = org_policy_service.OrgPolicyClient(
            self.ReleaseTrack())
        messages = org_policy_service.OrgPolicyMessages(self.ReleaseTrack())
        parent = utils.GetResourceFromArgs(args)
        request = messages.OrgpolicyOrganizationsCustomConstraintsListRequest(
            parent=parent)

        return list_pager.YieldFromList(
            org_policy_client.organizations_customConstraints,
            request,
            field='customConstraints',
            limit=args.limit,
            batch_size_attribute='pageSize',
            batch_size=args.page_size)
コード例 #8
0
    def SetUp(self):
        org_policy_client_class = apis.GetClientClass(
            org_policy_service.ORG_POLICY_API_NAME,
            org_policy_service.ORG_POLICY_API_VERSION)
        org_policy_real_client = apis.GetClientInstance(
            org_policy_service.ORG_POLICY_API_NAME,
            org_policy_service.ORG_POLICY_API_VERSION,
            no_http=True)
        mock_org_policy_client = mock.Client(org_policy_client_class,
                                             org_policy_real_client)
        mock_org_policy_client.Mock()
        self.addCleanup(mock_org_policy_client.Unmock)

        self.mock_policy_service = mock_org_policy_client.policies
        self.mock_constraint_service = mock_org_policy_client.constraints
        self.org_policy_messages = org_policy_service.OrgPolicyMessages()
コード例 #9
0
    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
コード例 #10
0
    def UpdatePolicy(self, policy, args):
        """Disables enforcement by removing old rules and creating a new rule with enforce set to False.

    Args:
      policy: messages.GoogleCloudOrgpolicyV2alpha1Policy, The policy to be
        updated.
      args: argparse.Namespace, An object that contains the values for the
        arguments specified in the Args method.

    Returns:
      The updated policy.
    """
        messages = service.OrgPolicyMessages(self.ReleaseTrack())
        new_rule = messages.GoogleCloudOrgpolicyV2alpha1PolicySpecPolicyRule()
        new_rule.enforce = False

        new_policy = copy.deepcopy(policy)
        new_policy.spec.rules = [new_rule]

        return new_policy
コード例 #11
0
ファイル: utils.py プロジェクト: novousernx/google-cloud-sdk
def _DeleteRulesWithEmptyValues(policy):
  """Delete any rule with empty lists of allowed values and denied values and no other field set.

  Args:
    policy: messages.GoogleCloudOrgpolicyV2alpha1Policy, The policy to be
      updated.

  Returns:
    The updated policy.
  """
  new_policy = copy.deepcopy(policy)

  org_policy_messages = org_policy_service.OrgPolicyMessages()
  empty_values = org_policy_messages.GoogleCloudOrgpolicyV2alpha1PolicySpecPolicyRuleStringValues(
  )
  matching_empty_rule = org_policy_messages.GoogleCloudOrgpolicyV2alpha1PolicySpecPolicyRule(
      values=empty_values)

  new_policy.spec.rules = [
      rule for rule in new_policy.spec.rules if rule != matching_empty_rule
  ]

  return new_policy
コード例 #12
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
コード例 #13
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))