1# -*- coding: utf-8 -*- #
2# Copyright 2015 Google LLC. All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#    http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""Command for setting IAM policies for registries."""
17
18from __future__ import absolute_import
19from __future__ import division
20from __future__ import unicode_literals
21
22from googlecloudsdk.api_lib.cloudiot import registries
23from googlecloudsdk.calliope import base
24from googlecloudsdk.command_lib.iam import iam_util
25from googlecloudsdk.command_lib.iot import flags
26from googlecloudsdk.command_lib.iot import resource_args
27
28
29@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA)
30class SetIamPolicy(base.Command):
31  """Set the IAM policy for a device registry.
32
33  This command replaces the existing IAM policy for a device registry, given
34  a REGISTRY and a file encoded in JSON or YAML that contains the IAM
35  policy. If the given policy file specifies an "etag" value, then the
36  replacement will succeed only if the policy already in place matches that
37  etag. (An etag obtained via $ gcloud iot registries get-iam-policy will
38  prevent the replacement if the policy for the device registry has been
39  subsequently updated.) A policy file that does not contain an etag value will
40  replace any existing policy for the device registry.
41  """
42
43  detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
44      'device registry', 'my-registry', additional_flags='--region=us-central1')
45
46  @staticmethod
47  def Args(parser):
48    resource_args.AddRegistryResourceArg(parser, 'for which to set IAM policy')
49    flags.GetIamPolicyFileFlag().AddToParser(parser)
50
51  def Run(self, args):
52    client = registries.RegistriesClient()
53    messages = client.messages
54
55    policy = iam_util.ParsePolicyFile(args.policy_file, messages.Policy)
56    registry_ref = args.CONCEPTS.registry.Parse()
57
58    response = client.SetIamPolicy(
59        registry_ref,
60        set_iam_policy_request=messages.SetIamPolicyRequest(policy=policy))
61    iam_util.LogSetIamPolicy(registry_ref.Name(), 'registry')
62    return response
63