| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2018, Ryan Conway (@rylon) |
| 4 |
# Copyright (c) 2018, Scott Buchanan <[email protected]> (onepassword.py used as starting point) |
| 5 |
# Copyright (c) 2018, Ansible Project |
| 6 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 8 |
|
| 9 |
|
| 10 |
from __future__ import annotations |
| 11 |
|
| 12 |
DOCUMENTATION = r""" |
| 13 |
module: onepassword_info |
| 14 |
author: |
| 15 |
- Ryan Conway (@Rylon) |
| 16 |
requirements: |
| 17 |
- C(op) 1Password command line utility. See U(https://support.1password.com/command-line/) |
| 18 |
notes: |
| 19 |
- Tested with C(op) version 0.5.5. |
| 20 |
- Based on the P(community.general.onepassword#lookup) lookup plugin by Scott Buchanan <[email protected]>. |
| 21 |
short_description: Gather items from 1Password |
| 22 |
description: |
| 23 |
- M(community.general.onepassword_info) wraps the C(op) command line utility to fetch data about one or more 1Password items. |
| 24 |
- A fatal error occurs if any of the items being searched for can not be found. |
| 25 |
- Recommend using with the C(no_log) option to avoid logging the values of the secrets being retrieved. |
| 26 |
extends_documentation_fragment: |
| 27 |
- community.general._attributes |
| 28 |
- community.general._attributes.info_module |
| 29 |
options: |
| 30 |
search_terms: |
| 31 |
type: list |
| 32 |
elements: dict |
| 33 |
description: |
| 34 |
- A list of one or more search terms. |
| 35 |
- Each search term can either be a simple string or it can be a dictionary for more control. |
| 36 |
- When passing a simple string, O(search_terms[].field) is assumed to be V(password). |
| 37 |
- When passing a dictionary, the following fields are available. |
| 38 |
suboptions: |
| 39 |
name: |
| 40 |
type: str |
| 41 |
description: |
| 42 |
- The name of the 1Password item to search for (required). |
| 43 |
field: |
| 44 |
type: str |
| 45 |
description: |
| 46 |
- The name of the field to search for within this item (optional, defaults to V(password), or V(document) if the |
| 47 |
item has an attachment). |
| 48 |
section: |
| 49 |
type: str |
| 50 |
description: |
| 51 |
- The name of a section within this item containing the specified field (optional, it searches all sections if not |
| 52 |
specified). |
| 53 |
vault: |
| 54 |
type: str |
| 55 |
description: |
| 56 |
- The name of the particular 1Password vault to search, useful if your 1Password user has access to multiple vaults |
| 57 |
(optional). |
| 58 |
required: true |
| 59 |
auto_login: |
| 60 |
type: dict |
| 61 |
description: |
| 62 |
- A dictionary containing authentication details. If this is set, the module attempts to sign in to 1Password automatically. |
| 63 |
- Without this option, you must have already logged in using the 1Password CLI before running Ansible. |
| 64 |
- It is B(highly) recommended to store 1Password credentials in an Ansible Vault. Ensure that the key used to encrypt |
| 65 |
the Ansible Vault is equal to or greater in strength than the 1Password master password. |
| 66 |
suboptions: |
| 67 |
subdomain: |
| 68 |
type: str |
| 69 |
description: |
| 70 |
- 1Password subdomain name (V(subdomain).1password.com). |
| 71 |
- If this is not specified, the most recent subdomain is used. |
| 72 |
username: |
| 73 |
type: str |
| 74 |
description: |
| 75 |
- 1Password username. |
| 76 |
- Only required for initial sign in. |
| 77 |
master_password: |
| 78 |
type: str |
| 79 |
description: |
| 80 |
- The master password for your subdomain. |
| 81 |
- This is always required when specifying O(auto_login). |
| 82 |
required: true |
| 83 |
secret_key: |
| 84 |
type: str |
| 85 |
description: |
| 86 |
- The secret key for your subdomain. |
| 87 |
- Only required for initial sign in. |
| 88 |
cli_path: |
| 89 |
type: path |
| 90 |
description: Used to specify the exact path to the C(op) command line interface. |
| 91 |
default: 'op' |
| 92 |
""" |
| 93 |
|
| 94 |
EXAMPLES = r""" |
| 95 |
# Gather secrets from 1Password, assuming there is a 'password' field: |
| 96 |
- name: Get a password |
| 97 |
community.general.onepassword_info: |
| 98 |
search_terms: My 1Password item |
| 99 |
delegate_to: localhost |
| 100 |
register: my_1password_item |
| 101 |
no_log: true # Don't want to log the secrets to the console! |
| 102 |
|
| 103 |
# Gather secrets from 1Password, with more advanced search terms: |
| 104 |
- name: Get a password |
| 105 |
community.general.onepassword_info: |
| 106 |
search_terms: |
| 107 |
- name: My 1Password item |
| 108 |
field: Custom field name # optional, defaults to 'password' |
| 109 |
section: Custom section name # optional, defaults to 'None' |
| 110 |
vault: Name of the vault # optional, only necessary if there is more than 1 Vault available |
| 111 |
delegate_to: localhost |
| 112 |
register: my_1password_item |
| 113 |
no_log: true # Don't want to log the secrets to the console! |
| 114 |
|
| 115 |
# Gather secrets combining simple and advanced search terms to retrieve two items, one of which we fetch two |
| 116 |
# fields. In the first 'password' is fetched, as a field name is not specified (default behaviour) and in the |
| 117 |
# second, 'Custom field name' is fetched, as that is specified explicitly. |
| 118 |
- name: Get a password |
| 119 |
community.general.onepassword_info: |
| 120 |
search_terms: |
| 121 |
- My 1Password item # 'name' is optional when passing a simple string... |
| 122 |
- name: My Other 1Password item # ...but it can also be set for consistency |
| 123 |
- name: My 1Password item |
| 124 |
field: Custom field name # optional, defaults to 'password' |
| 125 |
section: Custom section name # optional, defaults to 'None' |
| 126 |
vault: Name of the vault # optional, only necessary if there is more than 1 Vault available |
| 127 |
- name: A 1Password item with document attachment |
| 128 |
delegate_to: localhost |
| 129 |
register: my_1password_item |
| 130 |
no_log: true # Don't want to log the secrets to the console! |
| 131 |
|
| 132 |
- name: Debug a password (for example) |
| 133 |
ansible.builtin.debug: |
| 134 |
msg: "{{ my_1password_item['onepassword']['My 1Password item'] }}" |
| 135 |
""" |
| 136 |
|
| 137 |
RETURN = r""" |
| 138 |
# One or more dictionaries for each matching item from 1Password, along with the appropriate fields. |
| 139 |
# This shows the response you would expect to receive from the third example documented above. |
| 140 |
onepassword: |
| 141 |
description: Dictionary of each 1password item matching the given search terms, shows what would be returned from the third |
| 142 |
example above. |
| 143 |
returned: success |
| 144 |
type: dict |
| 145 |
sample: |
| 146 |
"My 1Password item": |
| 147 |
password: the value of this field |
| 148 |
Custom field name: the value of this field |
| 149 |
"My Other 1Password item": |
| 150 |
password: the value of this field |
| 151 |
"A 1Password item with document attachment": |
| 152 |
document: the contents of the document attached to this item |
| 153 |
""" |
| 154 |
|
| 155 |
|
| 156 |
import errno |
| 157 |
import json |
| 158 |
import os |
| 159 |
import re |
| 160 |
|
| 161 |
from ansible.module_utils.basic import AnsibleModule |
| 162 |
from ansible.module_utils.common.text.converters import to_bytes, to_native |
| 163 |
|
| 164 |
from ansible_collections.community.general.plugins.module_utils._onepassword import OnePasswordConfig |
| 165 |
|
| 166 |
|
| 167 |
class AnsibleModuleError(Exception): |
| 168 |
def __init__(self, results): |
| 169 |
self.results = results |
| 170 |
|
| 171 |
def __repr__(self): |
| 172 |
return self.results |
| 173 |
|
| 174 |
|
| 175 |
class OnePasswordInfo: |
| 176 |
def __init__(self): |
| 177 |
self.cli_path = module.params.get("cli_path") |
| 178 |
self.auto_login = module.params.get("auto_login") |
| 179 |
self.logged_in = False |
| 180 |
self.token = None |
| 181 |
|
| 182 |
terms = module.params.get("search_terms") |
| 183 |
self.terms = self.parse_search_terms(terms) |
| 184 |
|
| 185 |
self._config = OnePasswordConfig() |
| 186 |
|
| 187 |
def _run(self, args, expected_rc=0, command_input=None, ignore_errors=False): |
| 188 |
if self.token: |
| 189 |
# Adds the session token to all commands if we're logged in. |
| 190 |
args += [to_bytes("--session=") + self.token] |
| 191 |
|
| 192 |
command = [self.cli_path] + args |
| 193 |
rc, out, err = module.run_command(command, data=command_input, check_rc=False, binary_data=True, encoding=None) |
| 194 |
if not ignore_errors and rc != expected_rc: |
| 195 |
raise AnsibleModuleError(to_native(err)) |
| 196 |
return rc, out, err |
| 197 |
|
| 198 |
def _parse_field(self, data_json, item_id, field_name, section_title=None): |
| 199 |
data = json.loads(data_json) |
| 200 |
|
| 201 |
if "documentAttributes" in data["details"]: |
| 202 |
# This is actually a document, let's fetch the document data instead! |
| 203 |
document = self._run(["get", "document", data["overview"]["title"]]) |
| 204 |
return {"document": document[1].strip()} |
| 205 |
|
| 206 |
else: |
| 207 |
# This is not a document, let's try to find the requested field |
| 208 |
|
| 209 |
# Some types of 1Password items have a 'password' field directly alongside the 'fields' attribute, |
| 210 |
# not inside it, so we need to check there first. |
| 211 |
if field_name in data["details"]: |
| 212 |
return {field_name: data["details"][field_name]} |
| 213 |
|
| 214 |
# Otherwise we continue looking inside the 'fields' attribute for the specified field. |
| 215 |
else: |
| 216 |
if section_title is None: |
| 217 |
for field_data in data["details"].get("fields", []): |
| 218 |
if field_data.get("name", "").lower() == field_name.lower(): |
| 219 |
return {field_name: field_data.get("value", "")} |
| 220 |
|
| 221 |
# Not found it yet, so now lets see if there are any sections defined |
| 222 |
# and search through those for the field. If a section was given, we skip |
| 223 |
# any non-matching sections, otherwise we search them all until we find the field. |
| 224 |
for section_data in data["details"].get("sections", []): |
| 225 |
if section_title is not None and section_title.lower() != section_data["title"].lower(): |
| 226 |
continue |
| 227 |
for field_data in section_data.get("fields", []): |
| 228 |
if field_data.get("t", "").lower() == field_name.lower(): |
| 229 |
return {field_name: field_data.get("v", "")} |
| 230 |
|
| 231 |
# We will get here if the field could not be found in any section and the item wasn't a document to be downloaded. |
| 232 |
optional_section_title = "" if section_title is None else f" in the section '{section_title}'" |
| 233 |
module.fail_json( |
| 234 |
msg=f"Unable to find an item in 1Password named '{item_id}' with the field '{field_name}'{optional_section_title}." |
| 235 |
) |
| 236 |
|
| 237 |
def parse_search_terms(self, terms): |
| 238 |
processed_terms = [] |
| 239 |
|
| 240 |
for term in terms: |
| 241 |
if not isinstance(term, dict): |
| 242 |
term = {"name": term} |
| 243 |
|
| 244 |
if "name" not in term: |
| 245 |
module.fail_json(msg=f"Missing required 'name' field from search term, got: '{term}'") |
| 246 |
|
| 247 |
term["field"] = term.get("field", "password") |
| 248 |
term["section"] = term.get("section") |
| 249 |
term["vault"] = term.get("vault") |
| 250 |
|
| 251 |
processed_terms.append(term) |
| 252 |
|
| 253 |
return processed_terms |
| 254 |
|
| 255 |
def get_raw(self, item_id, vault=None): |
| 256 |
try: |
| 257 |
args = ["get", "item", item_id] |
| 258 |
if vault is not None: |
| 259 |
args += [f"--vault={vault}"] |
| 260 |
rc, output, dummy = self._run(args) |
| 261 |
return output |
| 262 |
|
| 263 |
except Exception as e: |
| 264 |
if re.search(".*not found.*", f"{e}"): |
| 265 |
module.fail_json(msg=f"Unable to find an item in 1Password named '{item_id}'.") |
| 266 |
else: |
| 267 |
module.fail_json(msg=f"Unexpected error attempting to find an item in 1Password named '{item_id}': {e}") |
| 268 |
|
| 269 |
def get_field(self, item_id, field, section=None, vault=None): |
| 270 |
output = self.get_raw(item_id, vault) |
| 271 |
return self._parse_field(output, item_id, field, section) if output != "" else "" |
| 272 |
|
| 273 |
def full_login(self): |
| 274 |
if self.auto_login is not None: |
| 275 |
if None in [ |
| 276 |
self.auto_login.get("subdomain"), |
| 277 |
self.auto_login.get("username"), |
| 278 |
self.auto_login.get("secret_key"), |
| 279 |
self.auto_login.get("master_password"), |
| 280 |
]: |
| 281 |
module.fail_json( |
| 282 |
msg="Unable to perform initial sign in to 1Password. " |
| 283 |
"subdomain, username, secret_key, and master_password are required to perform initial sign in." |
| 284 |
) |
| 285 |
|
| 286 |
args = [ |
| 287 |
"signin", |
| 288 |
f"{self.auto_login['subdomain']}.1password.com", |
| 289 |
to_bytes(self.auto_login["username"]), |
| 290 |
to_bytes(self.auto_login["secret_key"]), |
| 291 |
"--output=raw", |
| 292 |
] |
| 293 |
|
| 294 |
try: |
| 295 |
rc, out, err = self._run(args, command_input=to_bytes(self.auto_login["master_password"])) |
| 296 |
self.token = out.strip() |
| 297 |
except AnsibleModuleError as e: |
| 298 |
module.fail_json(msg=f"Failed to perform initial sign in to 1Password: {e}") |
| 299 |
else: |
| 300 |
module.fail_json( |
| 301 |
msg=f"Unable to perform an initial sign in to 1Password. Please run '{self.cli_path} signin' " |
| 302 |
"or define credentials in 'auto_login'. See the module documentation for details." |
| 303 |
) |
| 304 |
|
| 305 |
def get_token(self): |
| 306 |
# If the config file exists, assume an initial signin has taken place and try basic sign in |
| 307 |
if os.path.isfile(self._config.config_file_path): |
| 308 |
if self.auto_login is not None: |
| 309 |
# Since we are not currently signed in, master_password is required at a minimum |
| 310 |
if not self.auto_login.get("master_password"): |
| 311 |
module.fail_json(msg="Unable to sign in to 1Password. 'auto_login.master_password' is required.") |
| 312 |
|
| 313 |
# Try signing in using the master_password and a subdomain if one is provided |
| 314 |
try: |
| 315 |
args = ["signin", "--output=raw"] |
| 316 |
|
| 317 |
if self.auto_login.get("subdomain"): |
| 318 |
args = ["signin", self.auto_login["subdomain"], "--output=raw"] |
| 319 |
|
| 320 |
rc, out, err = self._run(args, command_input=to_bytes(self.auto_login["master_password"])) |
| 321 |
self.token = out.strip() |
| 322 |
|
| 323 |
except AnsibleModuleError: |
| 324 |
self.full_login() |
| 325 |
|
| 326 |
else: |
| 327 |
self.full_login() |
| 328 |
|
| 329 |
else: |
| 330 |
# Attempt a full sign in since there appears to be no existing sign in |
| 331 |
self.full_login() |
| 332 |
|
| 333 |
def assert_logged_in(self): |
| 334 |
try: |
| 335 |
rc, out, err = self._run(["get", "account"], ignore_errors=True) |
| 336 |
if rc == 0: |
| 337 |
self.logged_in = True |
| 338 |
if not self.logged_in: |
| 339 |
self.get_token() |
| 340 |
except OSError as e: |
| 341 |
if e.errno == errno.ENOENT: |
| 342 |
module.fail_json(msg=f"1Password CLI tool '{self.cli_path}' not installed in path on control machine") |
| 343 |
raise e |
| 344 |
|
| 345 |
def run(self): |
| 346 |
result = {} |
| 347 |
|
| 348 |
self.assert_logged_in() |
| 349 |
|
| 350 |
for term in self.terms: |
| 351 |
value = self.get_field(term["name"], term["field"], term["section"], term["vault"]) |
| 352 |
|
| 353 |
if term["name"] in result: |
| 354 |
# If we already have a result for this key, we have to append this result dictionary |
| 355 |
# to the existing one. This is only applicable when there is a single item |
| 356 |
# in 1Password which has two different fields, and we want to retrieve both of them. |
| 357 |
result[term["name"]].update(value) |
| 358 |
else: |
| 359 |
# If this is the first result for this key, simply set it. |
| 360 |
result[term["name"]] = value |
| 361 |
|
| 362 |
return result |
| 363 |
|
| 364 |
|
| 365 |
def main(): |
| 366 |
global module |
| 367 |
module = AnsibleModule( |
| 368 |
argument_spec=dict( |
| 369 |
cli_path=dict(type="path", default="op"), |
| 370 |
auto_login=dict( |
| 371 |
type="dict", |
| 372 |
options=dict( |
| 373 |
subdomain=dict(type="str"), |
| 374 |
username=dict(type="str"), |
| 375 |
master_password=dict(required=True, type="str", no_log=True), |
| 376 |
secret_key=dict(type="str", no_log=True), |
| 377 |
), |
| 378 |
), |
| 379 |
search_terms=dict(required=True, type="list", elements="dict"), |
| 380 |
), |
| 381 |
supports_check_mode=True, |
| 382 |
) |
| 383 |
module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"} |
| 384 |
|
| 385 |
results = {"onepassword": OnePasswordInfo().run()} |
| 386 |
|
| 387 |
module.exit_json(changed=False, **results) |
| 388 |
|
| 389 |
|
| 390 |
if __name__ == "__main__": |
| 391 |
main() |