1#!/usr/bin/python 2# -*- coding: utf-8 -*- 3# 4# Copyright (C) 2017 Google 5# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) 6# ---------------------------------------------------------------------------- 7# 8# *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** 9# 10# ---------------------------------------------------------------------------- 11# 12# This file is automatically generated by Magic Modules and manual 13# changes will be clobbered when the file is regenerated. 14# 15# Please read more about how to change this file at 16# https://www.github.com/GoogleCloudPlatform/magic-modules 17# 18# ---------------------------------------------------------------------------- 19 20from __future__ import absolute_import, division, print_function 21 22__metaclass__ = type 23 24################################################################################ 25# Documentation 26################################################################################ 27 28ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} 29 30DOCUMENTATION = ''' 31--- 32module: gcp_compute_instance_info 33description: 34- Gather info for GCP Instance 35- This module was called C(gcp_compute_instance_facts) before Ansible 2.9. The usage 36 has not changed. 37short_description: Gather info for GCP Instance 38version_added: 2.7 39author: Google Inc. (@googlecloudplatform) 40requirements: 41- python >= 2.6 42- requests >= 2.18.4 43- google-auth >= 1.3.0 44options: 45 filters: 46 description: 47 - A list of filter value pairs. Available filters are listed here U(https://cloud.google.com/sdk/gcloud/reference/topic/filters). 48 - Each additional filter in the list will act be added as an AND condition (filter1 49 and filter2) . 50 type: list 51 zone: 52 description: 53 - A reference to the zone where the machine resides. 54 required: true 55 type: str 56extends_documentation_fragment: gcp 57''' 58 59EXAMPLES = ''' 60- name: get info on an instance 61 gcp_compute_instance_info: 62 zone: us-central1-a 63 filters: 64 - name = test_object 65 project: test_project 66 auth_kind: serviceaccount 67 service_account_file: "/tmp/auth.pem" 68''' 69 70RETURN = ''' 71resources: 72 description: List of resources 73 returned: always 74 type: complex 75 contains: 76 canIpForward: 77 description: 78 - Allows this instance to send and receive packets with non-matching destination 79 or source IPs. This is required if you plan to use this instance to forward 80 routes. 81 returned: success 82 type: bool 83 cpuPlatform: 84 description: 85 - The CPU platform used by this instance. 86 returned: success 87 type: str 88 creationTimestamp: 89 description: 90 - Creation timestamp in RFC3339 text format. 91 returned: success 92 type: str 93 deletionProtection: 94 description: 95 - Whether the resource should be protected against deletion. 96 returned: success 97 type: bool 98 disks: 99 description: 100 - An array of disks that are associated with the instances that are created 101 from this template. 102 returned: success 103 type: complex 104 contains: 105 autoDelete: 106 description: 107 - Specifies whether the disk will be auto-deleted when the instance is deleted 108 (but not when the disk is detached from the instance). 109 - 'Tip: Disks should be set to autoDelete=true so that leftover disks are 110 not left behind on machine deletion.' 111 returned: success 112 type: bool 113 boot: 114 description: 115 - Indicates that this is a boot disk. The virtual machine will use the first 116 partition of the disk for its root filesystem. 117 returned: success 118 type: bool 119 deviceName: 120 description: 121 - Specifies a unique device name of your choice that is reflected into the 122 /dev/disk/by-id/google-* tree of a Linux operating system running within 123 the instance. This name can be used to reference the device for mounting, 124 resizing, and so on, from within the instance. 125 returned: success 126 type: str 127 diskEncryptionKey: 128 description: 129 - Encrypts or decrypts a disk using a customer-supplied encryption key. 130 returned: success 131 type: complex 132 contains: 133 rawKey: 134 description: 135 - Specifies a 256-bit customer-supplied encryption key, encoded in RFC 136 4648 base64 to either encrypt or decrypt this resource. 137 returned: success 138 type: str 139 rsaEncryptedKey: 140 description: 141 - Specifies an RFC 4648 base64 encoded, RSA-wrapped 2048-bit customer-supplied 142 encryption key to either encrypt or decrypt this resource. 143 returned: success 144 type: str 145 sha256: 146 description: 147 - The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied 148 encryption key that protects this resource. 149 returned: success 150 type: str 151 index: 152 description: 153 - Assigns a zero-based index to this disk, where 0 is reserved for the boot 154 disk. For example, if you have many disks attached to an instance, each 155 disk would have a unique index number. If not specified, the server will 156 choose an appropriate value. 157 returned: success 158 type: int 159 initializeParams: 160 description: 161 - Specifies the parameters for a new disk that will be created alongside 162 the new instance. Use initialization parameters to create boot disks or 163 local SSDs attached to the new instance. 164 returned: success 165 type: complex 166 contains: 167 diskName: 168 description: 169 - Specifies the disk name. If not specified, the default is to use the 170 name of the instance. 171 returned: success 172 type: str 173 diskSizeGb: 174 description: 175 - Specifies the size of the disk in base-2 GB. 176 returned: success 177 type: int 178 diskType: 179 description: 180 - Reference to a disk type. 181 - Specifies the disk type to use to create the instance. 182 - If not specified, the default is pd-standard. 183 returned: success 184 type: str 185 sourceImage: 186 description: 187 - The source image to create this disk. When creating a new instance, 188 one of initializeParams.sourceImage or disks.source is required. To 189 create a disk with one of the public operating system images, specify 190 the image by its family name. 191 returned: success 192 type: str 193 sourceImageEncryptionKey: 194 description: 195 - The customer-supplied encryption key of the source image. Required 196 if the source image is protected by a customer-supplied encryption 197 key. 198 - Instance templates do not store customer-supplied encryption keys, 199 so you cannot create disks for instances in a managed instance group 200 if the source images are encrypted with your own keys. 201 returned: success 202 type: complex 203 contains: 204 rawKey: 205 description: 206 - Specifies a 256-bit customer-supplied encryption key, encoded 207 in RFC 4648 base64 to either encrypt or decrypt this resource. 208 returned: success 209 type: str 210 sha256: 211 description: 212 - The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied 213 encryption key that protects this resource. 214 returned: success 215 type: str 216 interface: 217 description: 218 - Specifies the disk interface to use for attaching this disk, which is 219 either SCSI or NVME. The default is SCSI. 220 - Persistent disks must always use SCSI and the request will fail if you 221 attempt to attach a persistent disk in any other format than SCSI. 222 returned: success 223 type: str 224 mode: 225 description: 226 - The mode in which to attach this disk, either READ_WRITE or READ_ONLY. 227 If not specified, the default is to attach the disk in READ_WRITE mode. 228 returned: success 229 type: str 230 source: 231 description: 232 - Reference to a disk. When creating a new instance, one of initializeParams.sourceImage 233 or disks.source is required. 234 - If desired, you can also attach existing non-root persistent disks using 235 this property. This field is only applicable for persistent disks. 236 returned: success 237 type: dict 238 type: 239 description: 240 - Specifies the type of the disk, either SCRATCH or PERSISTENT. If not specified, 241 the default is PERSISTENT. 242 returned: success 243 type: str 244 guestAccelerators: 245 description: 246 - List of the type and count of accelerator cards attached to the instance . 247 returned: success 248 type: complex 249 contains: 250 acceleratorCount: 251 description: 252 - The number of the guest accelerator cards exposed to this instance. 253 returned: success 254 type: int 255 acceleratorType: 256 description: 257 - Full or partial URL of the accelerator type resource to expose to this 258 instance. 259 returned: success 260 type: str 261 hostname: 262 description: 263 - The hostname of the instance to be created. The specified hostname must be 264 RFC1035 compliant. If hostname is not specified, the default hostname is [INSTANCE_NAME].c.[PROJECT_ID].internal 265 when using the global DNS, and [INSTANCE_NAME].[ZONE].c.[PROJECT_ID].internal 266 when using zonal DNS. 267 returned: success 268 type: str 269 id: 270 description: 271 - The unique identifier for the resource. This identifier is defined by the 272 server. 273 returned: success 274 type: int 275 labelFingerprint: 276 description: 277 - The fingerprint used for optimistic locking of this resource. Used internally 278 during updates. 279 returned: success 280 type: str 281 labels: 282 description: 283 - Labels to apply to this instance. A list of key->value pairs. 284 returned: success 285 type: dict 286 metadata: 287 description: 288 - The metadata key/value pairs to assign to instances that are created from 289 this template. These pairs can consist of custom metadata or predefined keys. 290 returned: success 291 type: dict 292 machineType: 293 description: 294 - A reference to a machine type which defines VM kind. 295 returned: success 296 type: str 297 minCpuPlatform: 298 description: 299 - Specifies a minimum CPU platform for the VM instance. Applicable values are 300 the friendly names of CPU platforms . 301 returned: success 302 type: str 303 name: 304 description: 305 - The name of the resource, provided by the client when initially creating the 306 resource. The resource name must be 1-63 characters long, and comply with 307 RFC1035. Specifically, the name must be 1-63 characters long and match the 308 regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character 309 must be a lowercase letter, and all following characters must be a dash, lowercase 310 letter, or digit, except the last character, which cannot be a dash. 311 returned: success 312 type: str 313 networkInterfaces: 314 description: 315 - An array of configurations for this interface. This specifies how this interface 316 is configured to interact with other network services, such as connecting 317 to the internet. Only one network interface is supported per instance. 318 returned: success 319 type: complex 320 contains: 321 accessConfigs: 322 description: 323 - An array of configurations for this interface. Currently, only one access 324 config, ONE_TO_ONE_NAT, is supported. If there are no accessConfigs specified, 325 then this instance will have no external internet access. 326 returned: success 327 type: complex 328 contains: 329 name: 330 description: 331 - The name of this access configuration. The default and recommended 332 name is External NAT but you can use any arbitrary string you would 333 like. For example, My external IP or Network Access. 334 returned: success 335 type: str 336 natIP: 337 description: 338 - Reference to an address. 339 - An external IP address associated with this instance. 340 - Specify an unused static external IP address available to the project 341 or leave this field undefined to use an IP from a shared ephemeral 342 IP address pool. If you specify a static external IP address, it must 343 live in the same region as the zone of the instance. 344 returned: success 345 type: dict 346 type: 347 description: 348 - The type of configuration. The default and only option is ONE_TO_ONE_NAT. 349 returned: success 350 type: str 351 aliasIpRanges: 352 description: 353 - An array of alias IP ranges for this network interface. Can only be specified 354 for network interfaces on subnet-mode networks. 355 returned: success 356 type: complex 357 contains: 358 ipCidrRange: 359 description: 360 - The IP CIDR range represented by this alias IP range. 361 - This IP CIDR range must belong to the specified subnetwork and cannot 362 contain IP addresses reserved by system or used by other network interfaces. 363 This range may be a single IP address (e.g. 10.2.3.4), a netmask (e.g. 364 /24) or a CIDR format string (e.g. 10.1.2.0/24). 365 returned: success 366 type: str 367 subnetworkRangeName: 368 description: 369 - Optional subnetwork secondary range name specifying the secondary 370 range from which to allocate the IP CIDR range for this alias IP range. 371 If left unspecified, the primary range of the subnetwork will be used. 372 returned: success 373 type: str 374 name: 375 description: 376 - The name of the network interface, generated by the server. For network 377 devices, these are eth0, eth1, etc . 378 returned: success 379 type: str 380 network: 381 description: 382 - Specifies the title of an existing network. Not setting the network title 383 will select the default network interface, which could have SSH already 384 configured . 385 returned: success 386 type: dict 387 networkIP: 388 description: 389 - An IPv4 internal network address to assign to the instance for this network 390 interface. If not specified by the user, an unused internal IP is assigned 391 by the system. 392 returned: success 393 type: str 394 subnetwork: 395 description: 396 - Reference to a VPC network. 397 - If the network resource is in legacy mode, do not provide this property. 398 If the network is in auto subnet mode, providing the subnetwork is optional. 399 If the network is in custom subnet mode, then this field should be specified. 400 returned: success 401 type: dict 402 scheduling: 403 description: 404 - Sets the scheduling options for this instance. 405 returned: success 406 type: complex 407 contains: 408 automaticRestart: 409 description: 410 - Specifies whether the instance should be automatically restarted if it 411 is terminated by Compute Engine (not terminated by a user). 412 - You can only set the automatic restart option for standard instances. 413 Preemptible instances cannot be automatically restarted. 414 returned: success 415 type: bool 416 onHostMaintenance: 417 description: 418 - Defines the maintenance behavior for this instance. For standard instances, 419 the default behavior is MIGRATE. For preemptible instances, the default 420 and only possible behavior is TERMINATE. 421 - For more information, see Setting Instance Scheduling Options. 422 returned: success 423 type: str 424 preemptible: 425 description: 426 - Defines whether the instance is preemptible. This can only be set during 427 instance creation, it cannot be set or changed after the instance has 428 been created. 429 returned: success 430 type: bool 431 serviceAccounts: 432 description: 433 - A list of service accounts, with their specified scopes, authorized for this 434 instance. Only one service account per VM instance is supported. 435 returned: success 436 type: complex 437 contains: 438 email: 439 description: 440 - Email address of the service account. 441 returned: success 442 type: str 443 scopes: 444 description: 445 - The list of scopes to be made available for this service account. 446 returned: success 447 type: list 448 shieldedInstanceConfig: 449 description: 450 - Configuration for various parameters related to shielded instances. 451 returned: success 452 type: complex 453 contains: 454 enableSecureBoot: 455 description: 456 - Defines whether the instance has Secure Boot enabled. 457 returned: success 458 type: bool 459 enableVtpm: 460 description: 461 - Defines whether the instance has the vTPM enabled. 462 returned: success 463 type: bool 464 enableIntegrityMonitoring: 465 description: 466 - Defines whether the instance has integrity monitoring enabled. 467 returned: success 468 type: bool 469 status: 470 description: 471 - 'The status of the instance. One of the following values: PROVISIONING, STAGING, 472 RUNNING, STOPPING, SUSPENDING, SUSPENDED, and TERMINATED.' 473 - As a user, use RUNNING to keep a machine "on" and TERMINATED to turn a machine 474 off . 475 returned: success 476 type: str 477 statusMessage: 478 description: 479 - An optional, human-readable explanation of the status. 480 returned: success 481 type: str 482 tags: 483 description: 484 - A list of tags to apply to this instance. Tags are used to identify valid 485 sources or targets for network firewalls and are specified by the client during 486 instance creation. The tags can be later modified by the setTags method. Each 487 tag within the list must comply with RFC1035. 488 returned: success 489 type: complex 490 contains: 491 fingerprint: 492 description: 493 - Specifies a fingerprint for this request, which is essentially a hash 494 of the metadata's contents and used for optimistic locking. 495 - The fingerprint is initially generated by Compute Engine and changes after 496 every request to modify or update metadata. You must always provide an 497 up-to-date fingerprint hash in order to update or change metadata. 498 returned: success 499 type: str 500 items: 501 description: 502 - An array of tags. Each tag must be 1-63 characters long, and comply with 503 RFC1035. 504 returned: success 505 type: list 506 zone: 507 description: 508 - A reference to the zone where the machine resides. 509 returned: success 510 type: str 511''' 512 513################################################################################ 514# Imports 515################################################################################ 516from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest 517import json 518 519################################################################################ 520# Main 521################################################################################ 522 523 524def main(): 525 module = GcpModule(argument_spec=dict(filters=dict(type='list', elements='str'), zone=dict(required=True, type='str'))) 526 527 if module._name == 'gcp_compute_instance_facts': 528 module.deprecate("The 'gcp_compute_instance_facts' module has been renamed to 'gcp_compute_instance_info'", version='2.13') 529 530 if not module.params['scopes']: 531 module.params['scopes'] = ['https://www.googleapis.com/auth/compute'] 532 533 return_value = {'resources': fetch_list(module, collection(module), query_options(module.params['filters']))} 534 module.exit_json(**return_value) 535 536 537def collection(module): 538 return "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances".format(**module.params) 539 540 541def fetch_list(module, link, query): 542 auth = GcpSession(module, 'compute') 543 return auth.list(link, return_if_object, array_name='items', params={'filter': query}) 544 545 546def query_options(filters): 547 if not filters: 548 return '' 549 550 if len(filters) == 1: 551 return filters[0] 552 else: 553 queries = [] 554 for f in filters: 555 # For multiple queries, all queries should have () 556 if f[0] != '(' and f[-1] != ')': 557 queries.append("(%s)" % ''.join(f)) 558 else: 559 queries.append(f) 560 561 return ' '.join(queries) 562 563 564def return_if_object(module, response): 565 # If not found, return nothing. 566 if response.status_code == 404: 567 return None 568 569 # If no content, return nothing. 570 if response.status_code == 204: 571 return None 572 573 try: 574 module.raise_for_status(response) 575 result = response.json() 576 except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: 577 module.fail_json(msg="Invalid JSON response with error: %s" % inst) 578 579 if navigate_hash(result, ['error', 'errors']): 580 module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) 581 582 return result 583 584 585if __name__ == "__main__": 586 main() 587