summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/cloud/google/gce_snapshot.py
blob: 2de14023ca108f17db359e24d18b5dae3c8695b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

ANSIBLE_METADATA = {'metadata_version': '1.0',
                    'status': ['preview'],
                    'supported_by': 'community'}


DOCUMENTATION = '''
---
module: gce_snapshot
version_added: "2.3"
short_description: Create or destroy snapshots for GCE storage volumes
description:
  - Manages snapshots for GCE instances. This module manages snapshots for
    the storage volumes of a GCE compute instance. If there are multiple
    volumes, each snapshot will be prepended with the disk name
options:
  instance_name:
    description:
      - The GCE instance to snapshot
    required: True
  snapshot_name:
    description:
      - The name of the snapshot to manage
  disks:
    description:
      - A list of disks to create snapshots for. If none is provided,
        all of the volumes will be snapshotted
    default: all
    required: False
  state:
    description:
      - Whether a snapshot should be C(present) or C(absent)
    required: false
    default: present
    choices: [present, absent]
  service_account_email:
    description:
      - GCP service account email for the project where the instance resides
    required: true
  credentials_file:
    description:
      - The path to the credentials file associated with the service account
    required: true
  project_id:
    description:
      - The GCP project ID to use
    required: true
requirements:
    - "python >= 2.6"
    - "apache-libcloud >= 0.19.0"
author: Rob Wagner (@robwagner33)
'''

EXAMPLES = '''
- name: Create gce snapshot
  gce_snapshot:
    instance_name: example-instance
    snapshot_name: example-snapshot
    state: present
    service_account_email: project_name@appspot.gserviceaccount.com
    credentials_file: /path/to/credentials
    project_id: project_name
  delegate_to: localhost

- name: Delete gce snapshot
  gce_snapshot:
    instance_name: example-instance
    snapshot_name: example-snapshot
    state: absent
    service_account_email: project_name@appspot.gserviceaccount.com
    credentials_file: /path/to/credentials
    project_id: project_name
  delegate_to: localhost

# This example creates snapshots for only two of the available disks as
# disk0-example-snapshot and disk1-example-snapshot
- name: Create snapshots of specific disks
  gce_snapshot:
    instance_name: example-instance
    snapshot_name: example-snapshot
    state: present
    disks:
      - disk0
      - disk1
    service_account_email: project_name@appspot.gserviceaccount.com
    credentials_file: /path/to/credentials
    project_id: project_name
  delegate_to: localhost
'''

RETURN = '''
snapshots_created:
    description: List of newly created snapshots
    returned: When snapshots are created
    type: list
    sample: "[disk0-example-snapshot, disk1-example-snapshot]"

snapshots_deleted:
    description: List of destroyed snapshots
    returned: When snapshots are deleted
    type: list
    sample: "[disk0-example-snapshot, disk1-example-snapshot]"

snapshots_existing:
    description: List of snapshots that already existed (no-op)
    returned: When snapshots were already present
    type: list
    sample: "[disk0-example-snapshot, disk1-example-snapshot]"

snapshots_absent:
    description: List of snapshots that were already absent (no-op)
    returned: When snapshots were already absent
    type: list
    sample: "[disk0-example-snapshot, disk1-example-snapshot]"
'''

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.gce import gce_connect

try:
    from libcloud.compute.types import Provider
    _ = Provider.GCE
    HAS_LIBCLOUD = True
except ImportError:
    HAS_LIBCLOUD = False


def find_snapshot(volume, name):
    '''
    Check if there is a snapshot already created with the given name for
    the passed in volume.

    Args:
        volume: A gce StorageVolume object to manage
        name: The name of the snapshot to look for

    Returns:
        The VolumeSnapshot object if one is found
    '''
    found_snapshot = None
    snapshots = volume.list_snapshots()
    for snapshot in snapshots:
        if name == snapshot.name:
            found_snapshot = snapshot
    return found_snapshot


def main():
    module = AnsibleModule(
        argument_spec=dict(
            instance_name=dict(required=True),
            snapshot_name=dict(required=True),
            state=dict(choices=['present', 'absent'], default='present'),
            disks=dict(default=None, type='list'),
            service_account_email=dict(type='str'),
            credentials_file=dict(type='path'),
            project_id=dict(type='str')
        )
    )

    if not HAS_LIBCLOUD:
        module.fail_json(msg='libcloud with GCE support (0.19.0+) is required for this module')

    gce = gce_connect(module)

    instance_name = module.params.get('instance_name')
    snapshot_name = module.params.get('snapshot_name')
    disks = module.params.get('disks')
    state = module.params.get('state')

    json_output = dict(
        changed=False,
        snapshots_created=[],
        snapshots_deleted=[],
        snapshots_existing=[],
        snapshots_absent=[]
    )

    snapshot = None

    instance = gce.ex_get_node(instance_name, 'all')
    instance_disks = instance.extra['disks']

    for instance_disk in instance_disks:
        disk_snapshot_name = snapshot_name
        device_name = instance_disk['deviceName']
        if disks is None or device_name in disks:
            volume_obj = gce.ex_get_volume(device_name)

            # If we have more than one disk to snapshot, prepend the disk name
            if len(instance_disks) > 1:
                disk_snapshot_name = device_name + "-" + disk_snapshot_name

            snapshot = find_snapshot(volume_obj, disk_snapshot_name)

            if snapshot and state == 'present':
                json_output['snapshots_existing'].append(disk_snapshot_name)

            elif snapshot and state == 'absent':
                snapshot.destroy()
                json_output['changed'] = True
                json_output['snapshots_deleted'].append(disk_snapshot_name)

            elif not snapshot and state == 'present':
                volume_obj.snapshot(disk_snapshot_name)
                json_output['changed'] = True
                json_output['snapshots_created'].append(disk_snapshot_name)

            elif not snapshot and state == 'absent':
                json_output['snapshots_absent'].append(disk_snapshot_name)

    module.exit_json(**json_output)


if __name__ == '__main__':
    main()