summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/cloud/atomic/atomic_image.py
blob: 5199927da73ae2181b718341326223752fd77206 (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
#!/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: atomic_image
short_description: Manage the container images on the atomic host platform
description:
    - Manage the container images on the atomic host platform
    - Allows to execute the commands specified by the RUN label in the container image when present
version_added: "2.2"
author: "Saravanan KR @krsacme"
notes:
    - Host should support C(atomic) command
requirements:
  - atomic
  - "python >= 2.6"
options:
    backend:
        description:
          - Define the backend where the image is pulled.
        required: False
        choices: ["docker", "ostree"]
        default: None
        version_added: "2.4"
    name:
        description:
          - Name of the container image
        required: True
        default: null
    state:
        description:
          - The state of the container image.
          - The state C(latest) will ensure container image is upgraded to the latest version and forcefully restart container, if running.
        required: False
        choices: ["present", "absent", "latest"]
        default: latest
    started:
        description:
          - Start or Stop the container
        required: False
        choices: ["yes", "no"]
        default: yes
'''

EXAMPLES = '''

# Execute the run command on rsyslog container image (atomic run rhel7/rsyslog)
- atomic_image:
    name: rhel7/rsyslog
    state: latest

# Pull busybox to the OSTree backend
- atomic_image:
    name: busybox
    state: latest
    backend: ostree
'''

RETURN = '''
msg:
    description: The command standard output
    returned: always
    type: string
    sample: [u'Using default tag: latest ...']
'''


# import module snippets
from ansible.module_utils.basic import AnsibleModule


def do_upgrade(module, image):
    args = ['atomic', 'update', '--force', image]
    rc, out, err = module.run_command(args, check_rc=False)
    if rc != 0: # something went wrong emit the msg
        module.fail_json(rc=rc, msg=err)
    elif 'Image is up to date' in out:
        return False

    return True


def core(module):
    image = module.params['name']
    state = module.params['state']
    started = module.params['started']
    backend = module.params['backend']
    is_upgraded = False

    module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C')
    out = {}
    err = {}
    rc = 0

    if backend:
        if state == 'present' or state == 'latest':
            args = ['atomic', 'pull', "--storage=%s" % backend, image]
            rc, out, err = module.run_command(args, check_rc=False)
            if rc < 0:
                module.fail_json(rc=rc, msg=err)
            else:
                out_run = ""
                if started:
                    args = ['atomic', 'run', "--storage=%s" % backend, image]
                    rc, out_run, err = module.run_command(args, check_rc=False)
                    if rc < 0:
                        module.fail_json(rc=rc, msg=err)

                changed = "Extracting" in out or "Copying blob" in out
                module.exit_json(msg=(out + out_run), changed=changed)
        elif state == 'absent':
            args = ['atomic', 'images', 'delete',  "--storage=%s" % backend, image]
            if rc < 0:
                module.fail_json(rc=rc, msg=err)
            else:
                changed = "Unable to find" not in out
                module.exit_json(msg=out, changed=changed)
        return

    if state == 'present' or state == 'latest':
        if state == 'latest':
            is_upgraded = do_upgrade(module, image)

        if started:
            args = ['atomic', 'run', image]
        else:
            args = ['atomic', 'install', image]
    elif state == 'absent':
        args = ['atomic', 'uninstall', image]

    rc, out, err = module.run_command(args, check_rc=False)

    if rc < 0:
        module.fail_json(rc=rc, msg=err)
    elif rc == 1 and 'already present' in err:
        module.exit_json(restult=err, changed=is_upgraded)
    elif started and 'Container is running' in out:
        module.exit_json(result=out, changed=is_upgraded)
    else:
        module.exit_json(msg=out, changed=True)


def main():
    module = AnsibleModule(
        argument_spec=dict(
            backend=dict(default=None, choices=['docker', 'ostree']),
            name=dict(default=None, required=True),
            state=dict(default='latest', choices=['present', 'absent', 'latest']),
            started=dict(default='yes', type='bool'),
            ),
        )

    # Verify that the platform supports atomic command
    rc, out, err = module.run_command('atomic -v', check_rc=False)
    if rc != 0:
        module.fail_json(msg="Error in running atomic command", err=err)

    try:
        core(module)
    except Exception as e:
        module.fail_json(msg=str(e))


if __name__ == '__main__':
    main()