Google Cloud IoT Core 将于 2023 年 8 月 16 日停用。如需了解详情,请与您的 Google Cloud 客户支持团队联系。

获取设备注册表的 IAM 政策

检索设备注册表的 IAM 政策。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Go

如需了解详情,请参阅 Cloud IoT Core Go API 参考文档

如需向 Cloud IoT Core 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


// getRegistryIAM gets the IAM policy for a device registry.
func getRegistryIAM(w io.Writer, projectID string, region string, registryID string) (*cloudiot.Policy, error) {
	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope)
	if err != nil {
		return nil, err
	}
	client, err := cloudiot.New(httpClient)
	if err != nil {
		return nil, err
	}

	var req cloudiot.GetIamPolicyRequest

	path := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
	response, err := client.Projects.Locations.Registries.GetIamPolicy(path, &req).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintln(w, "Policy:")
	for _, binding := range response.Bindings {
		fmt.Fprintf(w, "Role: %s\n", binding.Role)
		for _, member := range binding.Members {
			fmt.Fprintf(w, "\tMember: %s\n", member)
		}
	}

	return response, nil
}

Java

如需了解详情,请参阅 Cloud IoT Core Java API 参考文档

如需向 Cloud IoT Core 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

/** Retrieves IAM permissions for the given registry. */
protected static void getIamPermissions(String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  com.google.api.services.cloudiot.v1.model.Policy policy =
      service
          .projects()
          .locations()
          .registries()
          .getIamPolicy(registryPath, new GetIamPolicyRequest())
          .execute();

  System.out.println("Policy ETAG: " + policy.getEtag());

  if (policy.getBindings() != null) {
    for (com.google.api.services.cloudiot.v1.model.Binding binding : policy.getBindings()) {
      System.out.println(String.format("Role: %s", binding.getRole()));
      System.out.println("Binding members: ");
      for (String member : binding.getMembers()) {
        System.out.println(String.format("\t%s", member));
      }
    }
  } else {
    System.out.println(String.format("No policy bindings for %s", registryName));
  }
}

Node.js

如需了解详情,请参阅 Cloud IoT Core Node.js API 参考文档

如需向 Cloud IoT Core 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const iot = require('@google-cloud/iot');

const iotClient = new iot.v1.DeviceManagerClient({
  // optional auth parameters.
});

async function getIamPolicy() {
  // Construct request
  const formattedResource = iotClient.registryPath(
    projectId,
    cloudRegion,
    registryId
  );

  let bindings;
  const [response] = await iotClient.getIamPolicy({
    resource: formattedResource,
  });

  bindings = response.bindings;
  const etag = response.etag;

  console.log('ETAG:', etag);
  bindings = bindings || [];

  bindings.forEach(_binding => {
    console.log(`Role: ${_binding.role}`);
    _binding.members || (_binding.members = []);
    _binding.members.forEach(_member => {
      console.log(`\t${_member}`);
    });
  });
}

getIamPolicy();

PHP

如需了解详情,请参阅 Cloud IoT Core PHP API 参考文档

如需向 Cloud IoT Core 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Iot\V1\DeviceManagerClient;

/**
 * Retrieves IAM permissions for the given registry.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function get_iam_policy(
    $registryId,
    $projectId,
    $location = 'us-central1'
) {
    print('Getting IAM Policy' . PHP_EOL);

    // Instantiate a client.
    $deviceManager = new DeviceManagerClient();

    // Format the full registry path
    $registryName = $deviceManager->registryName($projectId, $location, $registryId);

    $policy = $deviceManager->getIamPolicy($registryName);

    print($policy->serializeToJsonString() . PHP_EOL);
}

Python

如需了解详情,请参阅 Cloud IoT Core Python API 参考文档

如需向 Cloud IoT Core 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
client = iot_v1.DeviceManagerClient()

registry_path = client.registry_path(project_id, cloud_region, registry_id)

policy = client.get_iam_policy(request={"resource": registry_path})

return policy

Ruby

如需了解详情,请参阅 Cloud IoT Core Ruby API 参考文档

如需向 Cloud IoT Core 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region the registry is located in"
# registry_id = "The registry to get an IAM policy for"

require "google/apis/cloudiot_v1"

# Initialize the client and authenticate with the specified scope
Cloudiot   = Google::Apis::CloudiotV1
iot_client = Cloudiot::CloudIotService.new
iot_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the location associated with the project
parent   = "projects/#{project_id}/locations/#{location_id}"
resource = "#{parent}/registries/#{registry_id}"

# List the devices in the provided region
policy = iot_client.get_registry_iam_policy(
  resource
)

if policy.bindings
  policy.bindings.each do |binding|
    puts "Role: #{binding.role} Member: #{binding.members[0]}"
  end
else
  puts "No bindings"
end

后续步骤

如需搜索并过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器