Aggiorna il criterio IAM di un registro dispositivi.
Per saperne di più
Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:
Esempio di codice
C#
public static object SetIamPolicy(string projectId, string cloudRegion, string registryId,
string role, string member)
{
var cloudIot = CreateAuthorizedClient();
// The resource name of the location associated with the key rings.
var parent = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}";
try
{
var req = new SetIamPolicyRequest();
Policy pol = new Policy();
pol.Bindings = new List<Binding>();
Binding bind = new Binding()
{
Role = role,
Members = new List<string>()
};
bind.Members.Add(member);
pol.Bindings.Add(bind);
req.Policy = pol;
var result = cloudIot.Projects.Locations.Registries.SetIamPolicy(req, parent).Execute();
}
catch (Google.GoogleApiException e)
{
Console.WriteLine(e.Message);
return e.Error.Code;
}
return 0;
}
Go
// setRegistryIAM sets the IAM policy for a device registry
func setRegistryIAM(w io.Writer, projectID string, region string, registryID string, member string, role 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
}
req := cloudiot.SetIamPolicyRequest{
Policy: &cloudiot.Policy{
Bindings: []*cloudiot.Binding{
{
Members: []string{member},
Role: role,
},
},
},
}
path := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
response, err := client.Projects.Locations.Registries.SetIamPolicy(path, &req).Do()
if err != nil {
return nil, err
}
fmt.Fprintf(w, "Successfully set IAM policy for registry: %s\n", registryID)
return response, nil
}
Java
/** Sets IAM permissions for the given registry. */
protected static void setIamPermissions(
String projectId, String cloudRegion, String registryName, String member, String role)
throws GeneralSecurityException, IOException {
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
JsonFactory jsonFactory = JacksonFactory.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();
List<com.google.api.services.cloudiot.v1.model.Binding> bindings = policy.getBindings();
boolean addNewRole = true;
if (bindings != null) {
for (com.google.api.services.cloudiot.v1.model.Binding binding : bindings) {
if (binding.getRole().equals(role)) {
List<String> members = binding.getMembers();
members.add(member);
binding.setMembers(members);
addNewRole = false;
}
}
} else {
bindings = new ArrayList<>();
}
if (addNewRole) {
com.google.api.services.cloudiot.v1.model.Binding bind =
new com.google.api.services.cloudiot.v1.model.Binding();
bind.setRole(role);
List<String> members = new ArrayList<>();
members.add(member);
bind.setMembers(members);
bindings.add(bind);
}
policy.setBindings(bindings);
SetIamPolicyRequest req = new SetIamPolicyRequest().setPolicy(policy);
policy = service.projects().locations().registries().setIamPolicy(registryPath, req).execute();
System.out.println("Policy ETAG: " + policy.getEtag());
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 mem : binding.getMembers()) {
System.out.println(String.format("\t%s", mem));
}
}
}
Node.js
// 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 setIamPolicy() {
// Construct request
const resource = iotClient.registryPath(projectId, cloudRegion, registryId);
const policy = {
bindings: [
{
members: [member],
role: role,
},
],
};
const request = {
resource: resource,
policy: policy,
};
let bindings;
const [response] = await iotClient.setIamPolicy(request);
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}`);
});
});
}
setIamPolicy();
PHP
use Google\Cloud\Iot\V1\DeviceManagerClient;
use Google\Cloud\Iam\V1\Policy;
use Google\Cloud\Iam\V1\Binding;
/**
* Sets IAM permissions for the given registry to a single role/member.
*
* @param string $registryId IOT Device Registry ID
* @param string $role Role used for IAM commands
* @param string $member Member used for IAM commands
* @param string $projectId Google Cloud project ID
* @param string $location (Optional) Google Cloud region
*/
function set_iam_policy(
$registryId,
$role,
$member,
$projectId,
$location = 'us-central1'
) {
print('Setting IAM policy' . PHP_EOL);
// Instantiate a client.
$deviceManager = new DeviceManagerClient();
$registryName = $deviceManager->registryName($projectId, $location, $registryId);
$binding = (new Binding())
->setMembers([$member])
->setRole($role);
$policy = (new Policy())
->setBindings([$binding]);
$policy = $deviceManager->setIamPolicy($registryName, $policy);
print($policy->serializeToJsonString() . PHP_EOL);
}
Python
# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# role = 'viewer'
# member = 'group:dpebot@google.com'
client = iot_v1.DeviceManagerClient()
registry_path = client.registry_path(project_id, cloud_region, registry_id)
body = {"bindings": [{"members": [member], "role": role}]}
return client.set_iam_policy(request={"resource": registry_path, "policy": body})
Ruby
# project_id = "Your Google Cloud project ID"
# location_id = "The Cloud region the registry is located in"
# registry_id = "The registry to set an IAM policy for"
# member = "The member to add to the policy bindings"
# role = "The role for the binding the policy is set to"
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}"
request = Google::Apis::CloudiotV1::SetIamPolicyRequest.new
policy = Google::Apis::CloudiotV1::Policy.new
binding = Google::Apis::CloudiotV1::Binding.new
binding.members = [member]
binding.role = role
policy.bindings = [binding]
request.policy = policy
# List the devices in the provided region
result = iot_client.set_registry_iam_policy(
resource, request
)
if result.bindings
puts "Binding set:"
result.bindings.each do |binding|
puts "\tRole: #{binding.role} Member: #{binding.members[0]}"
end
else
puts "No bindings"
end
Passaggi successivi
Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.