cli.create.credentials package

Module contents

Compatibility wrapper.

This package was migrated from a flat module (credentials.py) to a package layout:

credentials/__main__.py contains the original implementation.

We re-export the public API so existing imports keep working.

class cli.create.credentials.Any(*args, **kwargs)

Bases: object

Special type indicating an unconstrained type.

  • Any is compatible with every type.

  • Any assumed to have all methods.

  • All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.

class cli.create.credentials.CommentedMap(*args: Any, **kw: Any)

Bases: ordereddict, CommentedBase

add_referent(cm: Any) None
add_yaml_merge(value: Any) None
copy() a shallow copy of od
get(key: Any, default: Any = None) Any

Return the value for key if key is in the dictionary, else default.

insert(pos: Any, key: Any, value: Any, comment: Any | None = None) None

insert key value into given position, as defined by source YAML attach comment if provided

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
property merge: Any
mlget(key: Any, default: Any = None, list_ok: Any = False) Any

multi-level get that expects dicts within dicts

non_merged_items() Any
pop(key[, default]) v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

update([E, ]**F) None.  Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

update_key_value(key: Any) None
values() an object providing a view on D's values
class cli.create.credentials.InventoryManager(role_path: Path, inventory_path: Path, vault_pw: str, overrides: Dict[str, str], allow_empty_plain: bool = False)

Bases: object

apply_schema() Dict

Apply the schema and return the updated inventory.

generate_secure_alphanumeric(length: int) str

Generate a cryptographically secure random alphanumeric string of the given length.

generate_value(algorithm: str) str

Generate a random secret value according to the specified algorithm.

Supported algorithms: • “random_hex”

– Returns a 64-byte (512-bit) secure random string, encoded as 128 hexadecimal characters. – Use when you need maximum entropy in a hex-only format.

  • “sha256”

    – Generates 32 random bytes, hashes them with SHA-256, and returns a 64-character hex digest. – Good for when you want a fixed-length (256-bit) hash output.

  • “sha1”

    – Generates 20 random bytes, hashes them with SHA-1, and returns a 40-character hex digest. – Only use in legacy contexts; SHA-1 is considered weaker than SHA-256.

  • “bcrypt”

    – Creates a random 16-byte URL-safe password, then applies a bcrypt hash. – Suitable for storing user-style passwords where bcrypt verification is needed.

  • “alphanumeric”

    – Produces a 64-character string drawn from [A–Z, a–z, 0–9]. – Offers ≈380 bits of entropy; human-friendly charset.

  • “base64_prefixed_32”

    – Generates 32 random bytes, encodes them in Base64, and prefixes the result with “base64:”. – Useful when downstream systems expect a Base64 format.

  • “random_hex_16”

    – Returns 16 random bytes (128 bits) encoded as 32 hexadecimal characters. – Handy for shorter tokens or salts.

Returns:

A securely generated string according to the chosen algorithm.

load_application_id(role_path: Path) str

Load the application ID from the role’s vars/main.yml file.

recurse_credentials(branch: dict, dest: dict, prefix: str = '')

Recursively process only the ‘credentials’ section and generate values.

class cli.create.credentials.Path(*args, **kwargs)

Bases: PurePath

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

absolute()

Return an absolute version of this path by prepending the current working directory. No normalization or symlink resolution is performed.

Use resolve() to get the canonical path to a file.

chmod(mode, *, follow_symlinks=True)

Change the permissions of the path, like os.chmod().

classmethod cwd()

Return a new path pointing to the current working directory (as returned by os.getcwd()).

exists()

Whether this path exists.

expanduser()

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

glob(pattern)

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

group()

Return the group name of the file gid.

Make this path a hard link pointing to the same file as target.

Note the order of arguments (self, target) is the reverse of os.link’s.

classmethod home()

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

is_block_device()

Whether this path is a block device.

is_char_device()

Whether this path is a character device.

is_dir()

Whether this path is a directory.

is_fifo()

Whether this path is a FIFO.

is_file()

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()

Check if this path is a POSIX mount point

is_socket()

Whether this path is a socket.

Whether this path is a symbolic link.

iterdir()

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

lchmod(mode)

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

Make the target path a hard link pointing to this path.

Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.

Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.

lstat()

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

mkdir(mode=511, parents=False, exist_ok=False)

Create a new directory at this given path.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)

Open the file pointed by this path and return a file object, as the built-in open() function does.

owner()

Return the login name of the file owner.

read_bytes()

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)

Open the file in text mode, read it, and close the file.

Return the path to which the symbolic link points.

rename(target)

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

replace(target)

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

resolve(strict=False)

Make the path absolute, resolving all symlinks on the way and also normalizing it.

rglob(pattern)

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

rmdir()

Remove this directory. The directory must be empty.

samefile(other_path)

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

stat(*, follow_symlinks=True)

Return the result of the stat() system call on this path, like os.stat() does.

Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

touch(mode=438, exist_ok=True)

Create this file with the given access mode, if it doesn’t exist.

Remove this file or link. If the path is a directory, use rmdir() instead.

write_bytes(data)

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None, newline=None)

Open the file in text mode, write to it, and close the file.

class cli.create.credentials.VaultHandler(vault_password_file: str)

Bases: object

encrypt_leaves(branch: Dict[str, Any], vault_pw: str)

Recursively encrypt all leaves (plain text values) under the credentials section.

encrypt_string(value: str, name: str) str

Encrypt a string using ansible-vault.

class cli.create.credentials.YAML(*, typ: List[str] | str | None = None, pure: Any = False, output: Any = None, plug_ins: Any = None)

Bases: object

Xdump_all(documents: Any, stream: Any, *, transform: Any = None) Any

Serialize a sequence of Python objects into a YAML stream.

property block_seq_indent: Any
compact(seq_seq: Any = None, seq_map: Any = None) None
compose(stream: Path | StreamTextType) Any

Parse the first YAML document in a stream and produce the corresponding representation tree.

compose_all(stream: Path | StreamTextType) Any

Parse all YAML documents in a stream and produce corresponding representation trees.

property composer: Any
property constructor: Any
dump(data: Path | StreamType, stream: Any = None, *, transform: Any = None) Any
dump_all(documents: Any, stream: Path | StreamType, *, transform: Any = None) Any
emit(events: Any, stream: Any) None

Emit YAML parsing events into a stream. If stream is None, return the produced string instead.

property emitter: Any
get_constructor_parser(stream: StreamTextType) Any

the old cyaml needs special setup, and therefore the stream

get_serializer_representer_emitter(stream: StreamType, tlca: Any) Any
property indent: Any
load(stream: Path | StreamTextType) Any

at this point you either have the non-pure Parser (which has its own reader and scanner) or you have the pure Parser. If the pure Parser is set, then set the Reader and Scanner, if not already set. If either the Scanner or Reader are set, you cannot use the non-pure Parser,

so reset it to the pure parser and set the Reader resp. Scanner if necessary

load_all(stream: Path | StreamTextType) Any
map(**kw: Any) Any
official_plug_ins() Any

search for list of subdirs that are plug-ins, if __file__ is not available, e.g. single file installers that are not properly emulating a file-system (issue 324) no plug-ins will be found. If any are packaged, you know which file that are and you can explicitly provide it during instantiation:

yaml = ruamel.yaml.YAML(plug_ins=[‘ruamel/yaml/jinja2/__plug_in__’])

parse(stream: StreamTextType) Any

Parse a YAML stream and produce parsing events.

property parser: Any
property reader: Any
register_class(cls: Any) Any

register a class for dumping/loading - if it has attribute yaml_tag use that to register, else use class name - if it has methods to_yaml/from_yaml use those to dump/load else dump attributes

as mapping

property representer: Any
property resolver: Any
scan(stream: StreamTextType) Any

Scan a YAML stream and produce scanning tokens.

property scanner: Any
seq(*args: Any) Any
serialize(node: Any, stream: StreamType | None) Any

Serialize a representation tree into a YAML stream. If stream is None, return the produced string instead.

serialize_all(nodes: Any, stream: StreamType | None) Any

Serialize a sequence of representation trees into a YAML stream. If stream is None, return the produced string instead.

property serializer: Any
property tags: Any
property version: Tuple[int, int] | None
cli.create.credentials.ask_for_confirmation(key: str) bool

Prompt the user for confirmation to overwrite an existing value.

cli.create.credentials.ensure_map(node: CommentedMap, key: str) CommentedMap

Ensure node[key] exists and is a mapping (CommentedMap) for round-trip safety.

cli.create.credentials.main() int
cli.create.credentials.parse_overrides(pairs: list[str]) Dict[str, str]

Parse –set key=value pairs into a dict. Supports both ‘credentials.key=val’ and ‘key=val’ (short) forms.

cli.create.credentials.to_vault_block(vault_handler: VaultHandler, value: str | Any, label: str) Any

Return a ruamel scalar tagged as !vault. If the input value is already vault-encrypted (string contains $ANSIBLE_VAULT or is a !vault scalar), reuse/wrap. Otherwise, encrypt plaintext via ansible-vault.

Special rule: - Empty strings (“”) are NOT encrypted and are returned as plain “”.