|
42 | 42 | from googleapiclient.errors import HttpError |
43 | 43 |
|
44 | 44 |
|
45 | | -def create_iot_topic(topic_name): |
| 45 | +def create_iot_topic(project, topic_name): |
46 | 46 | """Creates a PubSub Topic and grants access to Cloud IoT Core.""" |
47 | | - pubsub_client = pubsub.Client() |
48 | | - topic = pubsub_client.topic(topic_name) |
49 | | - topic.create() |
50 | | - |
51 | | - topic = pubsub_client.topic(topic_name) |
52 | | - policy = topic.get_iam_policy() |
53 | | - publishers = policy.get('roles/pubsub.publisher', []) |
54 | | - if hasattr(publishers, "append"): |
55 | | - publishers.append(policy.service_account( |
56 | | - 'cloud-iot@system.gserviceaccount.com')) |
57 | | - else: |
58 | | - publishers.add(policy.service_account( |
59 | | - 'cloud-iot@system.gserviceaccount.com')) |
60 | | - policy['roles/pubsub.publisher'] = publishers |
61 | | - topic.set_iam_policy(policy) |
| 47 | + pubsub_client = pubsub.PublisherClient() |
| 48 | + topic_path = pubsub_client.topic_path(project, topic_name) |
| 49 | + |
| 50 | + topic = pubsub_client.create_topic(topic_path) |
| 51 | + policy = pubsub_client.get_iam_policy(topic_path) |
| 52 | + |
| 53 | + policy.bindings.add( |
| 54 | + role='roles/pubsub.publisher', |
| 55 | + members=['serviceAccount:cloud-iot@system.gserviceaccount.com']) |
| 56 | + |
| 57 | + pubsub_client.set_iam_policy(topic_path, policy) |
62 | 58 |
|
63 | 59 | return topic |
64 | 60 |
|
@@ -476,7 +472,7 @@ def run_command(args): |
476 | 472 | args.cloud_region, args.pubsub_topic, args.registry_id) |
477 | 473 |
|
478 | 474 | elif args.command == 'create-topic': |
479 | | - create_iot_topic(args.pubsub_topic) |
| 475 | + create_iot_topic(args.project_id, args.pubsub_topic) |
480 | 476 |
|
481 | 477 | elif args.command == 'delete-device': |
482 | 478 | delete_device( |
|
0 commit comments