Debian Codegraph @

ansible_collections/containers/podman/plugins/modules/podman_login.py

raw
1 #!/usr/bin/python
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import absolute_import, division, print_function
5
6 __metaclass__ = type
7
8 DOCUMENTATION = r"""
9 module: podman_login
10 author:
11 - "Jason Hiatt (@jthiatt)"
12 - "Clemens Lange (@clelange)"
13 - "Michael Fox (@spmfox)"
14 short_description: Login to a container registry using podman
15 notes: []
16 description:
17 - Login to a container registry server using the podman login command
18 If the registry is not specified, the first registry under
19 `[registries.search]` from `registries.conf `will be used. The path of
20 the authentication file can be overridden by the user by setting the
21 `authfile` flag. The default path used is
22 `${XDG_RUNTIME_DIR}/containers/auth.json`.
23 requirements:
24 - "Podman installed on host"
25 options:
26 authfile:
27 description:
28 - Path of the authentication file. Default is
29 ``${XDG_RUNTIME_DIR}/containers/auth.json``
30 You can also override the default path of the authentication
31 file by setting the ``REGISTRY_AUTH_FILE`` environment
32 variable. ``export REGISTRY_AUTH_FILE=path``
33 type: path
34 certdir:
35 description:
36 - Use certificates at path (*.crt, *.cert, *.key) to connect
37 to the registry. Default certificates directory
38 is /etc/containers/certs.d.
39 type: path
40 password:
41 description:
42 - Password for the registry server.
43 type: str
44 registry:
45 description:
46 - Registry server. If the registry is not specified,
47 the first registry under `[registries.search]` from
48 `registries.conf` will be used.
49 type: str
50 tlsverify:
51 description:
52 - Require HTTPS and verify certificates when
53 contacting registries. If explicitly set to true,
54 then TLS verification will be used. If set to false,
55 then TLS verification will not be used. If not specified,
56 TLS verification will be used unless the target registry
57 is listed as an insecure registry in registries.conf.
58 type: bool
59 username:
60 description:
61 - Username for the registry server.
62 type: str
63 executable:
64 description:
65 - Path to C(podman) executable if it is not in the C($PATH) on the
66 machine running C(podman)
67 default: 'podman'
68 type: str
69 secret:
70 description:
71 - Name of an existing C(podman) secret to use for authentication
72 to target registry
73 type: str
74 """
75
76 EXAMPLES = r"""
77 - name: Login to default registry and create ${XDG_RUNTIME_DIR}/containers/auth.json
78 containers.podman.podman_login:
79 username: user
80 password: 'p4ssw0rd'
81
82 - name: Login to quay.io and create ${XDG_RUNTIME_DIR}/containers/auth.json
83 containers.podman.podman_login:
84 username: user
85 password: 'p4ssw0rd'
86 registry: quay.io
87
88 - name: Login to quay.io using existing secret called password
89 containers.podman.podman_login:
90 username: user
91 secret: password
92 registry: quay.io
93
94 """
95 # noqa: F402
96
97 import hashlib
98 import os
99 from ansible.module_utils.basic import AnsibleModule
100 from ansible_collections.containers.podman.plugins.module_utils.podman.common import (
101 LooseVersion,
102 )
103 from ansible_collections.containers.podman.plugins.module_utils.podman.common import (
104 get_podman_version,
105 )
106
107
108 def login(
109 module,
110 executable,
111 registry,
112 authfile,
113 certdir,
114 tlsverify,
115 username,
116 password,
117 secret,
118 ):
119
120 command = [executable, "login"]
121 changed = False
122
123 if username:
124 command.extend(["--username", username])
125 if password:
126 command.extend(["--password", password])
127 if secret:
128 command.extend(["--secret", secret])
129 if authfile:
130 command.extend(["--authfile", authfile])
131 authfile = os.path.expandvars(authfile)
132 else:
133 authfile = os.getenv("XDG_RUNTIME_DIR", "") + "/containers/auth.json"
134 if registry:
135 command.append(registry)
136 if certdir:
137 command.extend(["--cert-dir", certdir])
138 if tlsverify is not None:
139 if tlsverify:
140 command.append("--tls-verify")
141 else:
142 command.append("--tls-verify=False")
143 # Use a checksum to check if the auth JSON has changed
144 checksum = None
145 docker_authfile = os.path.expandvars("$HOME/.docker/config.json")
146 # podman falls back to ~/.docker/config.json if the default authfile doesn't exist
147 check_file = authfile if os.path.exists(authfile) else docker_authfile
148 if os.path.exists(check_file):
149 content = open(check_file, "rb").read()
150 checksum = hashlib.sha256(content).hexdigest()
151 rc, out, err = module.run_command(command)
152 if rc != 0:
153 if "Error: Not logged into" not in err:
154 module.fail_json(msg="Unable to gather info for %s: %s" % (registry, err))
155 else:
156 # If the command is successful, we managed to login
157 changed = True
158 if "Existing credentials are valid" in out:
159 changed = False
160 # If we have managed to calculate a checksum before, check if it has changed
161 # due to the login
162 if checksum:
163 content = open(check_file, "rb").read()
164 new_checksum = hashlib.sha256(content).hexdigest()
165 if new_checksum == checksum:
166 changed = False
167 return changed, out, err
168
169
170 def main():
171 module = AnsibleModule(
172 argument_spec=dict(
173 executable=dict(type="str", default="podman"),
174 registry=dict(type="str"),
175 authfile=dict(type="path"),
176 username=dict(type="str"),
177 password=dict(type="str", no_log=True),
178 certdir=dict(type="path"),
179 tlsverify=dict(type="bool"),
180 secret=dict(type="str", no_log=False),
181 ),
182 supports_check_mode=False,
183 required_by={
184 "password": "username",
185 },
186 mutually_exclusive=[
187 ["password", "secret"],
188 ],
189 )
190
191 registry = module.params["registry"]
192 authfile = module.params["authfile"]
193 username = module.params["username"]
194 password = module.params["password"]
195 certdir = module.params["certdir"]
196 tlsverify = module.params["tlsverify"]
197 secret = module.params["secret"]
198 executable = module.get_bin_path(module.params["executable"], required=True)
199
200 podman_version = get_podman_version(module, fail=False)
201
202 if (podman_version is not None) and (LooseVersion(podman_version) < LooseVersion("4.7.0")) and secret:
203 module.fail_json(msg="secret option may not be used with podman < 4.7.0")
204
205 if username and ((not password) and (not secret)):
206 module.fail_json(msg="Must pass either password or secret with username")
207
208 changed, out, err = login(
209 module,
210 executable,
211 registry,
212 authfile,
213 certdir,
214 tlsverify,
215 username,
216 password,
217 secret,
218 )
219
220 results = {
221 "changed": changed,
222 "stdout": out,
223 "stderr": err,
224 }
225
226 module.exit_json(**results)
227
228
229 if __name__ == "__main__":
230 main()