decided to start over

This commit is contained in:
2026-05-23 07:07:26 -04:00
parent ffcf6b2596
commit 71f57d3122
62 changed files with 0 additions and 5058 deletions

View File

@@ -1,5 +0,0 @@
---
profile: moderate
parseable: yes
skip_list:
- fqcn-builtins

View File

View File

@@ -1,6 +0,0 @@
#!/bin/bash
set -euo pipefail
alias ansible-galaxy="/usr/bin/ansible-galaxy"
alias ansible-vault="/usr/bin/ansible-vault"
alias ansible-playbook="/usr/bin/ansible-playbook"

View File

@@ -1,187 +0,0 @@
#!/bin/bash
set -euo pipefail
SKATO_ANSIBLE_ROOT=$(dirname "$0")
SKATO_ANSIBLE_ROOT=$(dirname "$SKATO_ANSIBLE_ROOT")
export SKATO_ANSIBLE_ROOT
printf "root=%s\n" "$SKATO_ANSIBLE_ROOT" > "./config" # INI format
export SKATO_BOOTSTRAP_ROLE="${SKATO_ANSIBLE_ROOT}/roles/bootstrap"
export SKANSIBLE_SECRETS="${SKATO_ANSIBLE_ROOT}/.secrets"
if [[ -f "./ansible_aliases" ]]; then
source ./ansible_aliases
fi
# Relative directory paths for role templates/files
export SKANSIBLE_ARIA="aria2"
export SKANSIBLE_PROFTPD="proftpd"
export SKANSIBLE_PROFTPD_CONFS="${SKANSIBLE_PROFTPD}/conf.d"
# @NOTE below 4 filepaths have filenames that must correspond to
# the filenames in role ProFTPd templates'/files' Display settings
export SKANSIBLE_PROFTPD_CONFS_WELCOME="${SKANSIBLE_PROFTPD}/conf.d/WELCOME.txt"
export SKANSIBLE_PROFTPD_CONFS_BANNER="${SKANSIBLE_PROFTPD}/conf.d/BANNER.txt"
export SKANSIBLE_PROFTPD_CONFS_SUCCESS="${SKANSIBLE_PROFTPD}/conf.d/SUCCESS.txt"
export SKANSIBLE_PROFTPD_CONFS_EXIT="${SKANSIBLE_PROFTPD}/conf.d/BYE.txt"
export SKANSIBLE_SSHD_CONFS="sshd_config.d"
export SKANSIBLE_SYSTEMD="systemd"
export SKANSIBLE_SYSTEMD_USER_UNITS="${SKANSIBLE_SYSTEMD}/user"
export SKANSIBLE_FAIL2BAN="fail2ban"
export SKANSIBLE_FAIL2BAN_JAILS="${SKANSIBLE_FAIL2BAN}/jail.d"
export SKANSIBLE_FAIL2BAN_FILTERS="${SKANSIBLE_FAIL2BAN}/filter.d"
export SKANSIBLE_GITCONFIG_CONFS="gitconfig.d"
# @NOTE files in here must have extension "key" with IDs in
# "gpg_keys" inventory variable list as basenames.
export SKANSIBLE_GPG="gnupg"
# @NOTE files in path below must have extensions "key" (private),
# "crt" (signed), or "pem" (public) with inventory host FQDN as basename
export SKANSIBLE_SSL="ca-certificates"
set-root () {
if [[ $# -eq 0 ]]; then
SKATO_ANSIBLE_ROOT=$(awk -F "=" '/root/ {print $2}' "./config")
export SKATO_ANSIBLE_ROOT
elif [[ -z "$1" ]]; then
SKATO_ANSIBLE_ROOT="$1"
export SKATO_ANSIBLE_ROOT
sed -i 's|^(root=).*||g' "./config"
sed -i "1 i\root=${SKATO_ANSIBLE_ROOT}" "./config"
fi
}
gxy () {
ansible-galaxy "$@"
}
vult () {
ansible-vault "$@"
}
play () {
ansible-playbook "$@"
}
import-gpg () {
for id in "$@";
do
gpg --export-secret-keys "$id" > "${SKATO_BOOTSTRAP_ROLE}/files/${SKANSIBLE_GPG}/${id}.key"
printf "Please manually add GPG key with 'id' of '%s' in 'users.\$username.gpg_keys' list of inventory file." "$id"
done
printf "Please manually change ID attribute of GPG keys in 'users.\$username.gpg_keys' list of inventory file."
}
import-ssl () {
for domain in "$@";
do
cp "/usr/local/share/ca-certificates/${domain}.key" "${SKATO_BOOTSTRAP_ROLE}/files/${SKANSIBLE_SSL}/${domain}.key"
cp "/usr/local/share/ca-certificates/${domain}.pem" "${SKATO_BOOTSTRAP_ROLE}/files/${SKANSIBLE_SSL}/${domain}.pem"
cp "/usr/local/share/ca-certificates/${domain}.crt" "${SKATO_BOOTSTRAP_ROLE}/files/${SKANSIBLE_SSL}/${domain}.crt"
printf "Please manually change 'fqdn' attribute in inventory group or host variable file to '%s'." "$domain"
done
}
import () {
case "$1" in
ssl) shift; import-ssl "$@";;
gpg) shift; import-gpg "$@";;
*) exit 1;;
esac
}
decrypt () {
while getopts "mv:i:d:" flag; do
case "$flag" in
m) METHOD=$OPTARG;;
v) VAULT_ID=$OPTARG;;
i) INPUT_FILE=$OPTARG;;
d) OUTPUT_PATH=$OPTARG;;
*) exit 1;;
esac
done
if ! [[ "$VAULT_ID" == *"@"* ]]; then
ID_TAG="$VAULT_ID"
if [[ "$METHOD" == "prompt" ]]; then
VAULT_ID="${VAULT_ID}@prompt"
elif [[ "$METHOD" == "file" ]]; then
if [[ -z "$INPUT_FILE" ]]; then
exit 1
else
VAULT_ID="${VAULT_ID}@${INPUT_FILE}"
fi
else
exit 1
fi
fi
if [[ -z "$OUTPUT_PATH" ]]; then
OUTPUT_FILE="${SKANSIBLE_SECRETS}/${ID_TAG}.txt"
else
mkdir -p "${SKANSIBLE_SECRETS}/${OUTPUT_PATH}"
OUTPUT_FILE="${SKANSIBLE_SECRETS}/${OUTPUT_PATH}/${ID_TAG}.txt"
fi
ansible-vault decrypt --vault-id "$VAULT_ID" --output "$OUTPUT_FILE" "$INPUT_FILE"
}
encrypt () {
while getopts "mv:d:pn:" flag; do
case "$flag" in
m) METHOD="$OPTARG";;
v) VAULT_ID="$OPTARG";;
d) PASS_PATH="$OPTARG";;
p) read -rp "Provide intended password: " PASSWORD;;
n) VAR_NAME="$OPTARG";;
*) exit 1;;
esac
done
while [[ -z "$PASSWORD" ]]; do
printf "Password missing. \nPlease specify a password. \n"
read -rp "Provide intended password: " PASSWORD
done
if ! [[ "$VAULT_ID" == *"@"* ]]; then
ID_TAG="${VAULT_ID}"
if [[ "$METHOD" == "prompt" ]]; then
VAULT_ID="${VAULT_ID}@prompt"
elif [[ "$METHOD" == "file" ]]; then
if [[ -z "$PASS_PATH" ]]; then
PASS_FILE="${SKANSIBLE_SECRETS}/${VAULT_ID}.txt"
else
mkdir -p "${SKANSIBLE_SECRETS}/${PASS_PATH}"
PASS_FILE="${SKANSIBLE_SECRETS}/${PASS_PATH}/${VAULT_ID}.txt"
fi
printf "%s\n" "$PASSWORD" > "$PASS_FILE"
VAULT_ID="${VAULT_ID}@${PASS_FILE}"
fi
fi
printf "Make sure to copy following to appropriate location in appropriate YAML file under %s: \n" "$SKATO_ANSIBLE_ROOT"
if [[ -z "$VAR_NAME" ]]; then
ansible-vault encrypt_string --name "$VAR_NAME" --stdin-name "$VAR_NAME" --vault-id "$VAULT_ID" --output - "$PASSWORD"
else
ansible-vault encrypt_string --stdin-name "$ID_TAG" --vault-id "$VAULT_ID" --output - "$PASSWORD"
fi
YAMLS_WITH_PASSWORDS=("${SKATO_BOOTSTRAP_ROLE}/vars/main/software.yml" "${SKATO_BOOTSTRAP_ROLE}/defaults/main/software.yml")
printf "Examples of common YAML files passwords may be in: \n"
printf " 1. any YAML file in %s \n" "${SKATO_ANSIBLE_ROOT}/hostvars"
printf " 2. any YAML file in %s \n" "${SKATO_ANSIBLE_ROOT}/groupvars"
for i in "${!YAMLS_WITH_PASSWORDS[@]}"; do
printf " %u. %s \n" "$(( i + 3 ))" "${YAMLS_WITH_PASSWORDS[$i]}"
done
}
# source ./extensions.d/edit.sh
case "$1" in
set-root) shift; set-root "$1";;
gxy) shift; gxy "$@";;
vult) shift; vult "$@";;
play) shift; play "$@";;
import) shift; import "$@";;
decrypt) shift; decrypt "$@";;
encrypt) shift; encrypt "$@";;
*) exit 1;;
esac

28
.env
View File

@@ -1,28 +0,0 @@
SKATO_ANSIBLE_ROOT=$(dirname "$0")
SKATO_ANSIBLE_ROOT=$(dirname "$SKATO_ANSIBLE_ROOT")
SKATO_BOOTSTRAP_ROLE="${SKATO_ANSIBLE_ROOT}/roles/bootstrap"
SKANSIBLE_SECRETS="${SKATO_ANSIBLE_ROOT}/.secrets"
# Relative directory paths for role templates/files
SKANSIBLE_ARIA="aria2"
SKANSIBLE_PROFTPD="proftpd"
SKANSIBLE_PROFTPD_CONFS="${SKANSIBLE_PROFTPD}/conf.d"
# @NOTE below 4 filepaths have filenames that must correspond to
# the filenames in role ProFTPd templates'/files' Display settings
SKANSIBLE_PROFTPD_CONFS_WELCOME="${SKANSIBLE_PROFTPD}/conf.d/WELCOME.txt"
SKANSIBLE_PROFTPD_CONFS_BANNER="${SKANSIBLE_PROFTPD}/conf.d/BANNER.txt"
SKANSIBLE_PROFTPD_CONFS_SUCCESS="${SKANSIBLE_PROFTPD}/conf.d/SUCCESS.txt"
SKANSIBLE_PROFTPD_CONFS_EXIT="${SKANSIBLE_PROFTPD}/conf.d/BYE.txt"
SKANSIBLE_SSHD_CONFS="sshd_config.d"
SKANSIBLE_SYSTEMD="systemd"
SKANSIBLE_SYSTEMD_USER_UNITS="${SKANSIBLE_SYSTEMD}/user"
SKANSIBLE_FAIL2BAN="fail2ban"
SKANSIBLE_FAIL2BAN_JAILS="${SKANSIBLE_FAIL2BAN}/jail.d"
SKANSIBLE_FAIL2BAN_FILTERS="${SKANSIBLE_FAIL2BAN}/filter.d"
SKANSIBLE_GITCONFIG_CONFS="gitconfig.d"
# @NOTE files in here must have extension "key" with IDs in
# "gpg_keys" inventory variable list as basenames.
SKANSIBLE_GPG="gnupg"
# @NOTE files in path below must have extensions "key" (private),
# "crt" (signed), or "pem" (public) with inventory host FQDN as basename
SKANSIBLE_SSL="ca-certificates"

21
.gitignore vendored
View File

@@ -1,21 +0,0 @@
.venv/
*.bak
hosts.yml
.secrets/*
**/*.key
**/*.gpg
**/*.asc
**/*.pem
**/*.ppk
**/*.crt
**/*.cert
log.txt
**/update-motd.d/*.sh
**/vhost@vps1-sukaato.moe.conf.j2
collections/
motd
banner
.galaxy_cache/
galaxy_token
uv.lock
__pycache__/

View File

@@ -1 +0,0 @@
3.13

232
LICENSE
View File

@@ -1,232 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
checkers
Copyright (C) 2024 xenobyte
This program 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.
This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
checkers Copyright (C) 2024 xenobyte
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@@ -1,39 +0,0 @@
# SUKAATO Ansible
This repository is for automating the management of the configuration of, and the provisioning of software for, my virtual private servers using [Ansible](https://www.redhat.com/en/ansible-collaborative?intcmp=7015Y000003t7aWQAQ). It's main purpose is to spin up the VPSs, create initial users and groups, import SSH or GPG keys, lock down SSH access or harden SSH, and then install and configure packages available to the given package manager of the operating system. The `bootstrap` role in here serves to abstract some of these tasks for our main playbook files.
## Variable Names and Their Scopes
To be able to make use of the Ansible playbooks, it is necessary to specify some variables in or at relevant scopes, though some may have some defaults. The relevant scopes variables are defined in, for our purposes, are:
- Ansible **inventory scope**: corresponds to variables inside per-hostname files in `group_vars` or `host_vars` directories, or the inventory file itself, i.e. `hosts.ini` or `hosts.yml`. The inventory file has some enforced naming conventions to be covered later or elsewhere.
- Ansible **role scope**: corresponds to variables found in files inside the `defaults` / `vars` directory in a role directory, or variables found in files inside subdirectory `main` in either `defaults` or `vars` directory of that role directory. There are favored conventional directory structures within which these variables are specified in the aforementioned directories, to be covered later or elsewhere.
Other variables that tend to have default definitions as is but that may be of interest are those found in Jinja templates of roles, in this case of the role `bootstrap`. Look through the `bootstrap` role's `templates` directory and you will discover them--most of them defined in role tasks or handlers that make reference to them. However, more information may be found elsewhere.
### Inventory Scope
Herein are listed the relevant variables at or in the *inventory* scope. These must be specified for a specific inventory host or group, typically in their corresponding files under `group_vars` or `host_vars`. Some variables must take in a dictionary type to be valid. To save space, there will be more detail on what keys are required or optional for such dictionaries [elsewhere](https://git.sukaato.moe/admin/skato-ansible/wiki/Inventory-Scope) and not here.
name | type | value validity rule
---|---|---
`fqdn` | `<str>` | fully qualified domain name
`vps_service` | `<dict{<str>:<str\|bool\|list>}>` | valid fields providing data for spinning up new VPS
`groups` | `<dict{$group_name:<dict>}>` | fields/keys that are group names with data configuring that group
`users` | `<dict{$user_name:<dict>}>` | fields/keys that are user names with data configuring that user
`keywords` | `<list[<str>]>` | strings that describe the VPS, useful for applying tags if allowed by API
`custom_vars` | `<dict{<str>:<any>}>` | your own custom variables, though there are some reserved variable names for this namespace
### Role Scope
Herein are listed the relevant variables at or in the *role* scope. These must be specified for a set of role tasks expected to run in a playbook for the host specified for its play. Some variables must take in a dictionary type to be valid. To save space, there will be more detail on what keys are required or optional for such dictionaries [elsewhere](https://git.sukaato.moe/admin/skato-ansible/wiki/Role-Scope) and not here.
name | type | value validity rule
---|---|---
`software` | `<dict{<str>:<dict>}>` | valid fields providing data for software installations
`config` | `<dict{$software_name:<dict>}>` | software name fields providing data for configuring that software
## Installation
> **TBC**
> This README is yet unfinished and unverified. Check back later.

View File

@@ -1,75 +0,0 @@
from custtypes import AnsibleRoles, AnsibleScopes, ExecutedPath
from whereami import USER_PATH, ANSIBLE_CONFIG, ANSIBLE_ROOTS
from configparser import ConfigParser as cfg
from typing import Sequence
from re import Pattern as RegEx
from pathlib import PurePath
from parse import Parser
# @TODO below class should mostly work as a context manager
class ControlNode:
__parser = Parser()
def __init__(self):
self.__user_path = USER_PATH()
self.__config = cfg()
if ANSIBLE_CONFIG.exists():
self.__config.read(str(ANSIBLE_CONFIG))
else:
raise Exception
self.__data = None
self.__filepath: ExecutedPath | None = None
self.__file = None
def __enter__(self):
self.__file = open(str(self.__filepath), "r+")
self.__data = self.__parser.load(self.__filepath)
return self.__data
def __exit__(self, exc_type, exc_value, exc_traceback):
result = self.__parser.dump(self.__data)
if isinstance(result, str):
self.__file.write(result)
else:
result.write(self.__file)
self.__file.close()
def __call__(self, scope: AnsibleScopes = AnsibleScopes.INVENTORY, pick: int | str | RegEx | AnsibleRoles = 0, filepath: ExecutedPath | str | None = None):
if scope is None:
raise NotImplementedError
else:
paths = ANSIBLE_ROOTS[scope.name.lower()]
if isinstance(paths, Sequence):
path = None
if isinstance(pick, int):
path = paths[pick]
elif isinstance(pick, str):
path = tuple(filter(lambda p: str(p) == pick or pick in str(p), paths))
if len(path) > 0:
path = path[0]
elif isinstance(pick, RegEx):
path = tuple(filter(lambda p: pick.search(str(p)), paths))
if len(path) > 0:
path = path[0]
else:
path = tuple(filter(lambda p: str(p) == pick.name.lower() or pick.name.lower() in str(p), paths))
if len(path) > 0:
path = path[0]
if path is None:
raise KeyError
if isinstance(filepath, ExecutedPath):
filepath = str(filepath)
if path.is_dir():
self.__filepath = path / filepath
elif path.is_file():
self.__filepath = path
return __enter__

View File

@@ -1,696 +0,0 @@
[defaults]
# (boolean) By default Ansible will issue a warning when received from a task action (module or action plugin)
# These warnings can be silenced by adjusting this setting to False.
;action_warnings=True
# (list) Accept list of cowsay templates that are 'safe' to use, set to empty list if you want to enable all installed templates.
;cowsay_enabled_stencils=bud-frogs, bunny, cheese, daemon, default, dragon, elephant-in-snake, elephant, eyes, hellokitty, kitty, luke-koala, meow, milk, moofasa, moose, ren, sheep, small, stegosaurus, stimpy, supermilker, three-eyes, turkey, turtle, tux, udder, vader-koala, vader, www
# (string) Specify a custom cowsay path or swap in your cowsay implementation of choice
;cowpath=
# (string) This allows you to chose a specific cowsay stencil for the banners or use 'random' to cycle through them.
;cow_selection=default
# (boolean) This option forces color mode even when running without a TTY or the "nocolor" setting is True.
;force_color=False
# (path) The default root path for Ansible config files on the controller.
home=.
# (boolean) This setting allows suppressing colorizing output, which is used to give a better indication of failure and status information.
;nocolor=False
# (boolean) If you have cowsay installed but want to avoid the 'cows' (why????), use this.
;nocows=False
# (boolean) Sets the default value for the any_errors_fatal keyword, if True, Task failures will be considered fatal errors.
;any_errors_fatal=False
# (path) The password file to use for the become plugin. --become-password-file.
# If executable, it will be run and the resulting stdout will be used as the password.
;become_password_file=
# (pathspec) Colon separated paths in which Ansible will search for Become Plugins.
become_plugins=plugins/become:.ansible/plugins/become:/usr/share/ansible/plugins/become
# (string) Chooses which cache plugin to use, the default 'memory' is ephemeral.
fact_caching=jsonfile
# (string) Defines connection or path information for the cache plugin
fact_caching_connection=.facts
# (string) Prefix to use for cache plugin files/tables
;fact_caching_prefix=ansible_facts
# (integer) Expiration timeout for the cache plugin data
;fact_caching_timeout=86400
# (list) List of enabled callbacks, not all callbacks need enabling, but many of those shipped with Ansible do as we don't want them activated by default.
;callbacks_enabled=
# (string) When a collection is loaded that does not support the running Ansible version (with the collection metadata key `requires_ansible`).
;collections_on_ansible_version_mismatch=warning
# (pathspec) Colon separated paths in which Ansible will search for collections content. Collections must be in nested *subdirectories*, not directly in these directories. For example, if ``COLLECTIONS_PATHS`` includes ``'{{ ANSIBLE_HOME ~ "/collections" }}'``, and you want to add ``my.collection`` to that directory, it must be saved as ``'{{ ANSIBLE_HOME} ~ "/collections/ansible_collections/my/collection" }}'``.
collections_path=collections:.ansible/collections:/usr/share/collections:/etc/ansible/collections
# (boolean) A boolean to enable or disable scanning the sys.path for installed collections
;collections_scan_sys_path=True
# (path) The password file to use for the connection plugin. --connection-password-file.
;connection_password_file=
# (pathspec) Colon separated paths in which Ansible will search for Action Plugins.
action_plugins=plugins/action:.ansible/plugins/action:/usr/share/ansible/plugins/action
# (boolean) When enabled, this option allows lookup plugins (whether used in variables as ``{{lookup('foo')}}`` or as a loop as with_foo) to return data that is not marked 'unsafe'.
# By default, such data is marked as unsafe to prevent the templating engine from evaluating any jinja2 templating language, as this could represent a security risk. This option is provided to allow for backward compatibility, however users should first consider adding allow_unsafe=True to any lookups which may be expected to contain data which may be run through the templating engine late
;allow_unsafe_lookups=False
# (boolean) This controls whether an Ansible playbook should prompt for a login password. If using SSH keys for authentication, you probably do not need to change this setting.
;ask_pass=False
# (boolean) This controls whether an Ansible playbook should prompt for a vault password.
;ask_vault_pass=False
# (pathspec) Colon separated paths in which Ansible will search for Cache Plugins.
cache_plugins=plugins/cache:.ansible/plugins/cache:/usr/share/ansible/plugins/cache
# (pathspec) Colon separated paths in which Ansible will search for Callback Plugins.
callback_plugins=plugins/callback:.ansible/plugins/callback:/usr/share/ansible/plugins/callback
# (pathspec) Colon separated paths in which Ansible will search for Cliconf Plugins.
cliconf_plugins=plugins/cliconf:.ansible/plugins/cliconf:/usr/share/ansible/plugins/cliconf
# (pathspec) Colon separated paths in which Ansible will search for Connection Plugins.
connection_plugins=plugins/connection:.ansible/plugins/connection:/usr/share/ansible/plugins/connection
# (boolean) Toggles debug output in Ansible. This is *very* verbose and can hinder multiprocessing. Debug output can also include secret information despite no_log settings being enabled, which means debug mode should not be used in production.
# @TODO turn the below off in prod
debug=True
# (string) This indicates the command to use to spawn a shell under for Ansible's execution needs on a target. Users may need to change this in rare instances when shell usage is constrained, but in most cases it may be left as is.
;executable=/bin/sh
# (string) This option allows you to globally configure a custom path for 'local_facts' for the implied :ref:`ansible_collections.ansible.builtin.setup_module` task when using fact gathering.
# If not set, it will fallback to the default from the ``ansible.builtin.setup`` module: ``/etc/ansible/facts.d``.
# This does **not** affect user defined tasks that use the ``ansible.builtin.setup`` module.
# The real action being created by the implicit task is currently ``ansible.legacy.gather_facts`` module, which then calls the configured fact modules, by default this will be ``ansible.builtin.setup`` for POSIX systems but other platforms might have different defaults.
fact_path=facts.d
# (pathspec) Colon separated paths in which Ansible will search for Jinja2 Filter Plugins.
filter_plugins=plugins/filter:.ansible/plugins/filter:/usr/share/ansible/plugins/filter
# (boolean) This option controls if notified handlers run on a host even if a failure occurs on that host.
# When false, the handlers will not run if a failure has occurred on a host.
# This can also be set per play or on the command line. See Handlers and Failure for more details.
force_handlers=False
# (integer) Maximum number of forks Ansible will use to execute tasks on target hosts.
forks=5
# (string) This setting controls the default policy of fact gathering (facts discovered about remote systems).
# This option can be useful for those wishing to save fact gathering time. Both 'smart' and 'explicit' will use the cache plugin.
gathering=smart
# (list) Set the `gather_subset` option for the :ref:`ansible_collections.ansible.builtin.setup_module` task in the implicit fact gathering. See the module documentation for specifics.
# It does **not** apply to user defined ``ansible.builtin.setup`` tasks.
;gather_subset=
# (integer) Set the timeout in seconds for the implicit fact gathering, see the module documentation for specifics.
# It does **not** apply to user defined :ref:`ansible_collections.ansible.builtin.setup_module` tasks.
;gather_timeout=
# (string) This setting controls how duplicate definitions of dictionary variables (aka hash, map, associative array) are handled in Ansible.
# This does not affect variables whose values are scalars (integers, strings) or arrays.
# **WARNING**, changing this setting is not recommended as this is fragile and makes your content (plays, roles, collections) non portable, leading to continual confusion and misuse. Don't change this setting unless you think you have an absolute need for it.
# We recommend avoiding reusing variable names and relying on the ``combine`` filter and ``vars`` and ``varnames`` lookups to create merged versions of the individual variables. In our experience this is rarely really needed and a sign that too much complexity has been introduced into the data structures and plays.
# For some uses you can also look into custom vars_plugins to merge on input, even substituting the default ``host_group_vars`` that is in charge of parsing the ``host_vars/`` and ``group_vars/`` directories. Most users of this setting are only interested in inventory scope, but the setting itself affects all sources and makes debugging even harder.
# All playbooks and roles in the official examples repos assume the default for this setting.
# Changing the setting to ``merge`` applies across variable sources, but many sources will internally still overwrite the variables. For example ``include_vars`` will dedupe variables internally before updating Ansible, with 'last defined' overwriting previous definitions in same file.
# The Ansible project recommends you **avoid ``merge`` for new projects.**
# It is the intention of the Ansible developers to eventually deprecate and remove this setting, but it is being kept as some users do heavily rely on it. New projects should **avoid 'merge'**.
;hash_behaviour=replace
# (pathlist) Comma separated list of Ansible inventory sources
inventory=hosts.ini,hosts4.ini,hosts6.ini,hosts.yml,hosts4.yml,hosts6.yml,hosts.yaml,hosts4.yaml,hosts6.yaml
# (pathspec) Colon separated paths in which Ansible will search for HttpApi Plugins.
httpapi_plugins=plugins/httpapi:.ansible/httpapi:/usr/share/ansible/plugins/httpapi
# (float) This sets the interval (in seconds) of Ansible internal processes polling each other. Lower values improve performance with large playbooks at the expense of extra CPU load. Higher values are more suitable for Ansible usage in automation scenarios, when UI responsiveness is not required but CPU usage might be a concern.
# The default corresponds to the value hardcoded in Ansible <= 2.1
;internal_poll_interval=0.001
# (pathspec) Colon separated paths in which Ansible will search for Inventory Plugins.
inventory_plugins=plugins/inventory:.ansible/inventory:/usr/share/ansible/plugins/inventory
# (string) This is a developer-specific feature that allows enabling additional Jinja2 extensions.
# See the Jinja2 documentation for details. If you do not know what these do, you probably don't need to change this setting :)
;jinja2_extensions=[]
# (boolean) This option preserves variable types during template operations.
;jinja2_native=False
# (boolean) Enables/disables the cleaning up of the temporary files Ansible used to execute the tasks on the remote.
# If this option is enabled it will disable ``ANSIBLE_PIPELINING``.
;keep_remote_files=False
# (boolean) Controls whether callback plugins are loaded when running /usr/bin/ansible. This may be used to log activity from the command line, send notifications, and so on. Callback plugins are always loaded for ``ansible-playbook``.
;bin_ansible_callbacks=False
# (tmppath) Temporary directory for Ansible to use on the controller.
;local_tmp={{ ANSIBLE_HOME ~ "/.tmp" }}
local_tmp=.tmp
# (list) List of logger names to filter out of the log file
;log_filter=
# (path) File to which Ansible will log on the controller. When empty logging is disabled.
log_path=log.txt
# (pathspec) Colon separated paths in which Ansible will search for Lookup Plugins.
lookup_plugins=plugins/lookup:.ansible/lookup:/usr/share/ansible/plugins/lookup
# (string) Sets the macro for the 'ansible_managed' variable available for :ref:`ansible_collections.ansible.builtin.template_module` and :ref:`ansible_collections.ansible.windows.win_template_module`. This is only relevant for those two modules.
;ansible_managed=Ansible managed
# (string) This sets the default arguments to pass to the ``ansible`` adhoc binary if no ``-a`` is specified.
;module_args=
# (string) Compression scheme to use when transferring Python modules to the target.
;module_compression=ZIP_DEFLATED
# (string) Module to use with the ``ansible`` AdHoc command, if none is specified via ``-m``.
;module_name=command
# (pathspec) Colon separated paths in which Ansible will search for Modules.
library=plugins/modules:.ansible/modules:/usr/share/ansible/plugins/modules
# (pathspec) Colon separated paths in which Ansible will search for Module utils files, which are shared by modules.
module_utils=plugins/module_utils:.ansible/module_utils:/usr/share/ansible/plugins/module_utils
# (pathspec) Colon separated paths in which Ansible will search for Netconf Plugins.
netconf_plugins=plugins/netconf:.ansible/netconf:/usr/share/ansible/plugins/netconf
# (boolean) Toggle Ansible's display and logging of task details, mainly used to avoid security disclosures.
;no_log=False
# (boolean) Toggle Ansible logging to syslog on the target when it executes tasks. On Windows hosts this will disable a newer style PowerShell modules from writing to the event log.
;no_target_syslog=False
# (raw) What templating should return as a 'null' value. When not set it will let Jinja2 decide.
;null_representation=
# (integer) For asynchronous tasks in Ansible (covered in Asynchronous Actions and Polling), this is how often to check back on the status of those tasks when an explicit poll interval is not supplied. The default is a reasonably moderate 15 seconds which is a tradeoff between checking in frequently and providing a quick turnaround when something may have completed.
;poll_interval=15
# (path) Option for connections using a certificate or key file to authenticate, rather than an agent or passwords, you can set the default value here to avoid re-specifying --private-key with every invocation.
;private_key_file=
# (boolean) By default, imported roles publish their variables to the play and other roles, this setting can avoid that.
# This was introduced as a way to reset role variables to default values if a role is used more than once in a playbook.
# Included roles only make their variables public at execution, unlike imported roles which happen at playbook compile time.
;private_role_vars=False
# (integer) Port to use in remote connections, when blank it will use the connection plugin default.
;remote_port=
# (string) Sets the login user for the target machines
# When blank it uses the connection plugin's default, normally the user currently executing Ansible.
;remote_user=
# (pathspec) Colon separated paths in which Ansible will search for Roles.
roles_path=roles:.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles
# (string) Set the main callback used to display Ansible output. You can only have one at a time.
# You can have many other callbacks, but just one can be in charge of stdout.
# See :ref:`callback_plugins` for a list of available options.
;stdout_callback=default
# (string) Set the default strategy used for plays.
;strategy=linear
# (pathspec) Colon separated paths in which Ansible will search for Strategy Plugins.
strategy_plugins=plugins/strategy:.ansible/plugins/strategy:/usr/share/ansible/plugins/strategy
# (boolean) Toggle the use of "su" for tasks.
;su=False
# (string) Syslog facility to use when Ansible logs to the remote target
;syslog_facility=LOG_USER
# (pathspec) Colon separated paths in which Ansible will search for Terminal Plugins.
terminal_plugins=plugins/terminal:.ansible/plugins/terminal:/usr/share/ansible/plugins/terminal
# (pathspec) Colon separated paths in which Ansible will search for Jinja2 Test Plugins.
test_plugins=plugins/test:.ansible/plugins/test:/usr/share/ansible/plugins/test
# (integer) This is the default timeout for connection plugins to use.
;timeout=10
# (string) Can be any connection plugin available to your ansible installation.
# There is also a (DEPRECATED) special 'smart' option, that will toggle between 'ssh' and 'paramiko' depending on controller OS and ssh versions.
;transport=ssh
# (boolean) When True, this causes ansible templating to fail steps that reference variable names that are likely typoed.
# Otherwise, any '{{ template_expression }}' that contains undefined variables will be rendered in a template or ansible action line exactly as written.
;error_on_undefined_vars=True
# (pathspec) Colon separated paths in which Ansible will search for Vars Plugins.
vars_plugins=plugins/vars:.ansible/plugins/vars:/usr/share/ansible/plugins/vars
# (string) The vault_id to use for encrypting by default. If multiple vault_ids are provided, this specifies which to use for encryption. The --encrypt-vault-id cli option overrides the configured value.
;vault_encrypt_identity=
# (string) The label to use for the default vault id label in cases where a vault id label is not provided
;vault_identity=default
# (list) A list of vault-ids to use by default. Equivalent to multiple --vault-id args. Vault-ids are tried in order.
;vault_identity_list=
# (string) If true, decrypting vaults with a vault id will only try the password from the matching vault-id
;vault_id_match=False
# (path) The vault password file to use. Equivalent to --vault-password-file or --vault-id
# If executable, it will be run and the resulting stdout will be used as the password.
;vault_password_file=
# (integer) Sets the default verbosity, equivalent to the number of ``-v`` passed in the command line.
;verbosity=0
# (boolean) Toggle to control the showing of deprecation warnings
;deprecation_warnings=True
# (boolean) Toggle to control showing warnings related to running devel
;devel_warning=True
# (boolean) Normally ``ansible-playbook`` will print a header for each task that is run. These headers will contain the name: field from the task if you specified one. If you didn't then ``ansible-playbook`` uses the task's action to help you tell which task is presently running. Sometimes you run many of the same action and so you want more information about the task to differentiate it from others of the same action. If you set this variable to True in the config then ``ansible-playbook`` will also include the task's arguments in the header.
# This setting defaults to False because there is a chance that you have sensitive values in your parameters and you do not want those to be printed.
# If you set this to True you should be sure that you have secured your environment's stdout (no one can shoulder surf your screen and you aren't saving stdout to an insecure file) or made sure that all of your playbooks explicitly added the ``no_log: True`` parameter to tasks which have sensitive values See How do I keep secret data in my playbook? for more information.
;display_args_to_stdout=False
# (boolean) Toggle to control displaying skipped task/host entries in a task in the default callback
;display_skipped_hosts=True
# (string) Root docsite URL used to generate docs URLs in warning/error text; must be an absolute URL with valid scheme and trailing slash.
;docsite_root_url=https://docs.ansible.com/ansible-core/
# (pathspec) Colon separated paths in which Ansible will search for Documentation Fragments Plugins.
;doc_fragment_plugins={{ ANSIBLE_HOME ~ "/plugins/doc_fragments:/usr/share/ansible/plugins/doc_fragments" }}
# (string) By default Ansible will issue a warning when a duplicate dict key is encountered in YAML.
# These warnings can be silenced by adjusting this setting to False.
;duplicate_dict_key=warn
# (boolean) Whether or not to enable the task debugger, this previously was done as a strategy plugin.
# Now all strategy plugins can inherit this behavior. The debugger defaults to activating when
# a task is failed on unreachable. Use the debugger keyword for more flexibility.
;enable_task_debugger=False
# (boolean) Toggle to allow missing handlers to become a warning instead of an error when notifying.
;error_on_missing_handler=True
# (list) Which modules to run during a play's fact gathering stage, using the default of 'smart' will try to figure it out based on connection type.
# If adding your own modules but you still want to use the default Ansible facts, you will want to include 'setup' or corresponding network module to the list (if you add 'smart', Ansible will also figure it out).
# This does not affect explicit calls to the 'setup' module, but does always affect the 'gather_facts' action (implicit or explicit).
;facts_modules=smart
# (boolean) Set this to "False" if you want to avoid host key checking by the underlying tools Ansible uses to connect to the host
host_key_checking=False
# (boolean) Facts are available inside the `ansible_facts` variable, this setting also pushes them as their own vars in the main namespace.
# Unlike inside the `ansible_facts` dictionary, these will have an `ansible_` prefix.
;inject_facts_as_vars=True
# (string) Path to the Python interpreter to be used for module execution on remote targets, or an automatic discovery mode. Supported discovery modes are ``auto`` (the default), ``auto_silent``, ``auto_legacy``, and ``auto_legacy_silent``. All discovery modes employ a lookup table to use the included system Python (on distributions known to include one), falling back to a fixed ordered list of well-known Python interpreter locations if a platform-specific default is not available. The fallback behavior will issue a warning that the interpreter should be set explicitly (since interpreters installed later may change which one is used). This warning behavior can be disabled by setting ``auto_silent`` or ``auto_legacy_silent``. The value of ``auto_legacy`` provides all the same behavior, but for backwards-compatibility with older Ansible releases that always defaulted to ``/usr/bin/python``, will use that interpreter if present.
;interpreter_python=auto
# (boolean) If 'false', invalid attributes for a task will result in warnings instead of errors
;invalid_task_attribute_failed=True
# (boolean) Toggle to control showing warnings related to running a Jinja version older than required for jinja2_native
;jinja2_native_warning=True
# (boolean) By default Ansible will issue a warning when there are no hosts in the inventory.
# These warnings can be silenced by adjusting this setting to False.
;localhost_warning=True
# (int) Maximum size of files to be considered for diff display
;max_diff_size=104448
# (list) List of extensions to ignore when looking for modules to load
# This is for rejecting script and binary module fallback extensions
;module_ignore_exts={{(REJECT_EXTS + ('.yaml', '.yml', '.ini'))}}
# (bool) Enables whether module responses are evaluated for containing non UTF-8 data
# Disabling this may result in unexpected behavior
# Only ansible-core should evaluate this configuration
;module_strict_utf8_response=True
# (list) TODO: write it
;network_group_modules=eos, nxos, ios, iosxr, junos, enos, ce, vyos, sros, dellos9, dellos10, dellos6, asa, aruba, aireos, bigip, ironware, onyx, netconf, exos, voss, slxos
# (boolean) Previously Ansible would only clear some of the plugin loading caches when loading new roles, this led to some behaviours in which a plugin loaded in previous plays would be unexpectedly 'sticky'. This setting allows to return to that behaviour.
;old_plugin_cache_clear=False
# (path) A number of non-playbook CLIs have a ``--playbook-dir`` argument; this sets the default value for it.
playbook_dir=playbooks:/etc/ansible/playbooks
# (string) This sets which playbook dirs will be used as a root to process vars plugins, which includes finding host_vars/group_vars
;playbook_vars_root=top
# (path) A path to configuration for filtering which plugins installed on the system are allowed to be used.
# See :ref:`plugin_filtering_config` for details of the filter file's format.
# The default is /etc/ansible/plugin_filters.yml
;plugin_filters_cfg=
# (string) Attempts to set RLIMIT_NOFILE soft limit to the specified value when executing Python modules (can speed up subprocess usage on Python 2.x. See https://bugs.python.org/issue11284). The value will be limited by the existing hard limit. Default value of 0 does not attempt to adjust existing system-defined limits.
;python_module_rlimit_nofile=0
# (bool) This controls whether a failed Ansible playbook should create a .retry file.
;retry_files_enabled=False
# (path) This sets the path in which Ansible will save .retry files when a playbook fails and retry files are enabled.
# This file will be overwritten after each run with the list of failed hosts from all plays.
;retry_files_save_path=
# (str) This setting can be used to optimize vars_plugin usage depending on user's inventory size and play selection.
;run_vars_plugins=demand
# (bool) This adds the custom stats set via the set_stats plugin to the default output
;show_custom_stats=False
# (string) Action to take when a module parameter value is converted to a string (this does not affect variables). For string parameters, values such as '1.00', "['a', 'b',]", and 'yes', 'y', etc. will be converted by the YAML parser unless fully quoted.
# Valid options are 'error', 'warn', and 'ignore'.
# Since 2.8, this option defaults to 'warn' but will change to 'error' in 2.12.
;string_conversion_action=warn
# (boolean) Allows disabling of warnings related to potential issues on the system running ansible itself (not on the managed hosts)
# These may include warnings about 3rd party packages or other conditions that should be resolved if possible.
;system_warnings=True
# (boolean) This option defines whether the task debugger will be invoked on a failed task when ignore_errors=True is specified.
# True specifies that the debugger will honor ignore_errors, False will not honor ignore_errors.
;task_debugger_ignore_errors=True
# (integer) Set the maximum time (in seconds) that a task can run for.
# If set to 0 (the default) there is no timeout.
;task_timeout=0
# (string) Make ansible transform invalid characters in group names supplied by inventory sources.
;force_valid_group_names=never
# (boolean) Toggles the use of persistence for connections.
;use_persistent_connections=False
# (bool) A toggle to disable validating a collection's 'metadata' entry for a module_defaults action group. Metadata containing unexpected fields or value types will produce a warning when this is True.
;validate_action_group_metadata=True
# (list) Accept list for variable plugins that require it.
vars_plugins_enabled=host_group_vars
# (list) Allows to change the group variable precedence merge order.
;precedence=all_inventory, groups_inventory, all_plugins_inventory, all_plugins_play, groups_plugins_inventory, groups_plugins_play
# (string) The salt to use for the vault encryption. If it is not provided, a random salt will be used.
;vault_encrypt_salt=
# (bool) Force 'verbose' option to use stderr instead of stdout
;verbose_to_stderr=False
# (integer) For asynchronous tasks in Ansible (covered in Asynchronous Actions and Polling), this is how long, in seconds, to wait for the task spawned by Ansible to connect back to the named pipe used on Windows systems. The default is 5 seconds. This can be too low on slower systems, or systems under heavy load.
# This is not the total time an async command can run for, but is a separate timeout to wait for an async command to start. The task will only start to be timed against its async_timeout once it has connected to the pipe, so the overall maximum duration the task can take will be extended by the amount specified here.
;win_async_startup_timeout=5
# (list) Check all of these extensions when looking for 'variable' files which should be YAML or JSON or vaulted versions of these.
# This affects vars_files, include_vars, inventory and vars plugins among others.
yaml_valid_extensions=.yml,.yaml
[privilege_escalation]
# (boolean) Display an agnostic become prompt instead of displaying a prompt containing the command line supplied become method
;agnostic_become_prompt=True
# (boolean) This setting controls if become is skipped when remote user and become user are the same. I.E root sudo to root.
# If executable, it will be run and the resulting stdout will be used as the password.
;become_allow_same_user=False
# (boolean) Toggles the use of privilege escalation, allowing you to 'become' another user after login.
;become=False
# (boolean) Toggle to prompt for privilege escalation password.
;become_ask_pass=False
# (string) executable to use for privilege escalation, otherwise Ansible will depend on PATH
;become_exe=
# (string) Flags to pass to the privilege escalation executable.
;become_flags=
# (string) Privilege escalation method to use when `become` is enabled.
;become_method=sudo
# (string) The user your login/remote user 'becomes' when using privilege escalation, most systems will use 'root' when no user is specified.
;become_user=root
[persistent_connection]
# (path) Specify where to look for the ansible-connection script. This location will be checked before searching $PATH.
# If null, ansible will start with the same directory as the ansible script.
;ansible_connection_path=
# (int) This controls the amount of time to wait for response from remote device before timing out persistent connection.
;command_timeout=30
# (integer) This controls the retry timeout for persistent connection to connect to the local domain socket.
;connect_retry_timeout=15
# (integer) This controls how long the persistent connection will remain idle before it is destroyed.
;connect_timeout=30
# (path) Path to socket to be used by the connection persistence system.
;control_path_dir={{ ANSIBLE_HOME ~ "/pc" }}
[connection]
# (boolean) This is a global option, each connection plugin can override either by having more specific options or not supporting pipelining at all.
# Pipelining, if supported by the connection plugin, reduces the number of network operations required to execute a module on the remote server, by executing many Ansible modules without actual file transfer.
# It can result in a very significant performance improvement when enabled.
# However this conflicts with privilege escalation (become). For example, when using 'sudo:' operations you must first disable 'requiretty' in /etc/sudoers on all managed hosts, which is why it is disabled by default.
# This setting will be disabled if ``ANSIBLE_KEEP_REMOTE_FILES`` is enabled.
pipelining=False
[colors]
# (string) Defines the color to use on 'Changed' task status
;changed=yellow
# (string) Defines the default color to use for ansible-console
;console_prompt=white
# (string) Defines the color to use when emitting debug messages
;debug=dark gray
# (string) Defines the color to use when emitting deprecation messages
;deprecate=purple
# (string) Defines the color to use when showing added lines in diffs
;diff_add=green
# (string) Defines the color to use when showing diffs
;diff_lines=cyan
# (string) Defines the color to use when showing removed lines in diffs
;diff_remove=red
# (string) Defines the color to use when emitting error messages
;error=red
# (string) Defines the color to use for highlighting
;highlight=white
# (string) Defines the color to use when showing 'OK' task status
;ok=green
# (string) Defines the color to use when showing 'Skipped' task status
;skip=cyan
# (string) Defines the color to use on 'Unreachable' status
;unreachable=bright red
# (string) Defines the color to use when emitting verbose messages. i.e those that show with '-v's.
;verbose=blue
# (string) Defines the color to use when emitting warning messages
;warn=bright purple
[selinux]
# (boolean) This setting causes libvirt to connect to lxc containers by passing --noseclabel to virsh. This is necessary when running on systems which do not have SELinux.
;libvirt_lxc_noseclabel=False
# (list) Some filesystems do not support safe operations and/or return inconsistent errors, this setting makes Ansible 'tolerate' those in the list w/o causing fatal errors.
# Data corruption may occur and writes are not always verified when a filesystem is in the list.
;special_context_filesystems=fuse, nfs, vboxsf, ramfs, 9p, vfat
[diff]
# (bool) Configuration toggle to tell modules to show differences when in 'changed' status, equivalent to ``--diff``.
;always=False
# (integer) How many lines of context to show when displaying the differences between files.
;context=3
[galaxy]
# (path) The directory that stores cached responses from a Galaxy server.
# This is only used by the ``ansible-galaxy collection install`` and ``download`` commands.
# Cache files inside this dir will be ignored if they are world writable.
;cache_dir={{ ANSIBLE_HOME ~ "/galaxy_cache" }}
cache_dir=.galaxy_cache
# (bool) whether ``ansible-galaxy collection install`` should warn about ``--collections-path`` missing from configured :ref:`collections_paths`
;collections_path_warning=True
# (path) Collection skeleton directory to use as a template for the ``init`` action in ``ansible-galaxy collection``, same as ``--collection-skeleton``.
;collection_skeleton=
# (list) patterns of files to ignore inside a Galaxy collection skeleton directory
;collection_skeleton_ignore=^.git$, ^.*/.git_keep$
# (bool) Disable GPG signature verification during collection installation.
;disable_gpg_verify=False
# (bool) Some steps in ``ansible-galaxy`` display a progress wheel which can cause issues on certain displays or when outputting the stdout to a file.
# This config option controls whether the display wheel is shown or not.
# The default is to show the display wheel if stdout has a tty.
;display_progress=
# (path) Configure the keyring used for GPG signature verification during collection installation and verification.
gpg_keyring=$HOME/.gnupg
# (boolean) If set to yes, ansible-galaxy will not validate TLS certificates. This can be useful for testing against a server with a self-signed certificate.
;ignore_certs=
# (list) A list of GPG status codes to ignore during GPG signature verification. See L(https://github.com/gpg/gnupg/blob/master/doc/DETAILS#general-status-codes) for status code descriptions.
# If fewer signatures successfully verify the collection than `GALAXY_REQUIRED_VALID_SIGNATURE_COUNT`, signature verification will fail even if all error codes are ignored.
;ignore_signature_status_codes=
# (str) The number of signatures that must be successful during GPG signature verification while installing or verifying collections.
# This should be a positive integer or all to indicate all signatures must successfully validate the collection.
# Prepend + to the value to fail if no valid signatures are found for the collection.
;required_valid_signature_count=1
# (path) Role skeleton directory to use as a template for the ``init`` action in ``ansible-galaxy``/``ansible-galaxy role``, same as ``--role-skeleton``.
;role_skeleton=
# (list) patterns of files to ignore inside a Galaxy role or collection skeleton directory
;role_skeleton_ignore=^.git$, ^.*/.git_keep$
# (string) URL to prepend when roles don't specify the full URI, assume they are referencing this server as the source.
;server=https://galaxy.ansible.com
# (list) A list of Galaxy servers to use when installing a collection.
# The value corresponds to the config ini header ``[galaxy_server.{{item}}]`` which defines the server details.
# See :ref:`galaxy_server_config` for more details on how to define a Galaxy server.
# The order of servers in this list is used to as the order in which a collection is resolved.
# Setting this config option will ignore the :ref:`galaxy_server` config option.
;server_list=
# (int) The default timeout for Galaxy API calls. Galaxy servers that don't configure a specific timeout will fall back to this value.
;server_timeout=60
# (path) Local path to galaxy access token file
;token_path={{ ANSIBLE_HOME ~ "/galaxy_token" }}
token_path=galaxy_token
[inventory]
# (string) This setting changes the behaviour of mismatched host patterns, it allows you to force a fatal error, a warning or just ignore it
;host_pattern_mismatch=warning
# (boolean) If 'true', it is a fatal error when any given inventory source cannot be successfully parsed by any available inventory plugin; otherwise, this situation only attracts a warning.
;any_unparsed_is_failed=False
# (bool) Toggle to turn on inventory caching.
# This setting has been moved to the individual inventory plugins as a plugin option :ref:`inventory_plugins`.
# The existing configuration settings are still accepted with the inventory plugin adding additional options from inventory configuration.
# This message will be removed in 2.16.
;cache=False
# (string) The plugin for caching inventory.
# This setting has been moved to the individual inventory plugins as a plugin option :ref:`inventory_plugins`.
# The existing configuration settings are still accepted with the inventory plugin adding additional options from inventory and fact cache configuration.
# This message will be removed in 2.16.
;cache_plugin=
# (string) The inventory cache connection.
# This setting has been moved to the individual inventory plugins as a plugin option :ref:`inventory_plugins`.
# The existing configuration settings are still accepted with the inventory plugin adding additional options from inventory and fact cache configuration.
# This message will be removed in 2.16.
;cache_connection=
# (string) The table prefix for the cache plugin.
# This setting has been moved to the individual inventory plugins as a plugin option :ref:`inventory_plugins`.
# The existing configuration settings are still accepted with the inventory plugin adding additional options from inventory and fact cache configuration.
# This message will be removed in 2.16.
;cache_prefix=ansible_inventory_
# (string) Expiration timeout for the inventory cache plugin data.
# This setting has been moved to the individual inventory plugins as a plugin option :ref:`inventory_plugins`.
# The existing configuration settings are still accepted with the inventory plugin adding additional options from inventory and fact cache configuration.
# This message will be removed in 2.16.
;cache_timeout=3600
# (list) List of enabled inventory plugins, it also determines the order in which they are used.
;enable_plugins=host_list, script, auto, yaml, ini, toml
enable_plugins=yaml,ini,host_list,script,auto
# (bool) Controls if ansible-inventory will accurately reflect Ansible's view into inventory or its optimized for exporting.
;export=False
# (list) List of extensions to ignore when using a directory as an inventory source
;ignore_extensions={{(REJECT_EXTS + ('.orig', '.ini', '.cfg', '.retry'))}}
# (list) List of patterns to ignore when using a directory as an inventory source
;ignore_patterns=
# (bool) If 'true' it is a fatal error if every single potential inventory source fails to parse, otherwise this situation will only attract a warning.
;unparsed_is_failed=False
# (boolean) By default Ansible will issue a warning when no inventory was loaded and notes that it will use an implicit localhost-only inventory.
# These warnings can be silenced by adjusting this setting to False.
;inventory_unparsed_warning=True
[netconf_connection]
# (string) This variable is used to enable bastion/jump host with netconf connection. If set to True the bastion/jump host ssh settings should be present in ~/.ssh/config file, alternatively it can be set to custom ssh configuration file path to read the bastion/jump host settings.
;ssh_config=
[paramiko_connection]
# (boolean) TODO: write it
;host_key_auto_add=False
# (boolean) TODO: write it
;look_for_keys=True
[jinja2]
# (list) This list of filters avoids 'type conversion' when templating variables
# Useful when you want to avoid conversion into lists or dictionaries for JSON strings, for example.
;dont_type_filters=string, to_json, to_nice_json, to_yaml, to_nice_yaml, ppretty, json
[tags]
# (list) default list of tags to run in your plays, Skip Tags has precedence.
;run=
# (list) default list of tags to skip in your plays, has precedence over Run Tags
;skip=

View File

@@ -1,82 +0,0 @@
"""
Library of custom type hints.
"""
from typing import TypeAlias as Neotype, TypedDict as Dict
from typing import Required
from collections.abc import Sequence
from pathlib import Path, PurePath, PurePosixPath, PureWindowsPath, PosixPath, WindowsPath
from enum import StrEnum, auto
from io import TextIOBase, BufferedIOBase, RawIOBase
ExecutedPath: Neotype = PosixPath | WindowsPath
IdlePath: Neotype = PurePosixPath | PureWindowsPath
File: Neotype = TextIOBase | BufferedIOBase | RawIOBase
class RootFate(StrEnum):
disposal = auto()
retention = auto()
class NodeType(StrEnum):
remote = auto()
control = auto()
class VPS(StrEnum):
Linode = auto()
class VPSRegion(StrEnum):
us_east = auto()
class AnsibleScopes(StrEnum):
INTERNAL = auto()
INVENTORY = auto()
GROUPVARS = auto()
HOSTVARS = auto()
ROLE = auto()
class AnsibleRoles(StrEnum):
bootstrap = auto()
class Scopes(StrEnum):
SYS = auto()
USER = auto()
LOCAL = auto()
PROJ = auto()
SHARED = auto()
class Roles(StrEnum):
CONF = auto()
DATA = auto()
MEM = auto()
EXE = auto()
class UserName(StrEnum):
root = auto()
class GroupName(StrEnum):
remote = auto()
sudo = auto()
class Software(StrEnum):
openssh_client = auto()
openssh_server = auto()
class SoftwareRoles(StrEnum):
client = auto()
server = auto()
class PacMans(StrEnum):
APT = auto()
class PathCollection(Dict, total=False):
sys: ExecutedPath | IdlePath | str | Sequence[ExecutedPath | IdlePath | str]
user: ExecutedPath | IdlePath | str | Sequence[ExecutedPath | IdlePath | str]
local: ExecutedPath | IdlePath | str | Sequence[ExecutedPath | IdlePath | str]
proj: ExecutedPath | IdlePath | str | Sequence[ExecutedPath | IdlePath | str]
shared: ExecutedPath | IdlePath | str | Sequence[ExecutedPath | IdlePath | str]
class PathRoles(Dict, total=False):
conf: PathCollection
data: PathCollection
mem: PathCollection
exe: PathCollection

View File

@@ -1,356 +0,0 @@
from typing import Self, Literal, Never, Callable, Sequence
from custtypes import Roles, Scopes, PathCollection, PathRoles
from custtypes import Software, SoftwareRoles, PacMans
from custtypes import ExecutedPath, IdlePath, File
from custtypes import UserName, GroupName, VPS, VPSRegion, RootFate
from pathlib import Path, PurePath
from sshkey import SSHKeyCollection, SSHKeyType, SSHKey
from random import choice as gamble
from re import Pattern as RegEx
from softman import sshd
from yaml import YAMLObject
from ansible_vault import Vault
class Group(YAMLObject):
yaml_tag = u"!Group"
# @TODO create Enum class child for category parameter type hinting in below method
def __init__(self, group_name: GroupName | str = GroupName.sudo, category: Literal["system", "regular"] = "system", gid: int | str | None = 27):
if isinstance(group_name, GroupName):
self.group_name = group_name.name.lower()
else:
self.group_name = group_name
self.id = str(gid)
self.type = category
def __repr__(self):
return "%s(group_name=%r,category=%r,gid=%r)" % (
self.__class__.__name__,
self.group_name,
self.category,
self.id
)
class User(YAMLObject):
yaml_tag = u"!User"
def __init__(self, username: UserName | str = UserName.root, password: str = "test", services: list[str | Software] = [Software.openssh_server], uid: int | str | None = 0):
self.exists = True
if isinstance(username, UserName):
self.username = username.name.lower()
else:
self.username = username
self.id = str(uid)
self.password = password
new_services = []
for s in services:
if isinstance(s, Software):
new_services.append(s.name.lower())
else:
new_services.append(s)
self.services: tuple = tuple(new_services)
self.shell = "/bin/bash"
self.home = "/"
self.category: Literal["system", "regular"] = "regular"
group = Group(username, self.id)
self.group = group
self.groups: list[str | GroupName] | None = None
if self.groups is None:
self.admin = True
elif isinstance(self.groups, Sequence) and GroupName.sudo in self.groups:
self.admin = True
else:
self.admin = False
ssh_keys = SSHKeyCollection()
ssh_keys.pull()
self.__ssh_keys = ssh_keys
# print("here")
self.__public_keys = self.__ssh_keys.publish(SSHKeyType.pubkey, datatype=list)
pubkeys = ssh_keys.publish(SSHKeyType.pubkey, datatype=list)
self.__auth_keys: SSHKeyCollection = SSHKeyCollection()
for p in pubkeys:
self.__auth_keys.append(p)
self.ssh_authorized_keys: list[str | None] = []
self.__private_keys = self.__ssh_keys.publish(SSHKeyType.privkey, datatype=list)[0]
privkeys = ssh_keys.publish(SSHKeyType.privkey, datatype=list)
self.__priv_keys: SSHKeyCollection = SSHKeyCollection()
for p in privkeys[0]:
self.__priv_keys.append(p)
self.ssh_private_key_paths: list[str | None] = []
self.__priv_key_pref: int = privkeys[1]
self.ssh_private_key_path_pref: int = privkeys[1]
self.__apps = (sshd,)
self.__ssh_keypairs: tuple[SSHKey | tuple[SSHKey]] | SSHKey = tuple()
self.__ssh_keypair_chosen = False
def get_app(self, name: Software) -> Never:
raise NotImplementedError
def update_app(self, name: Software, attr: str, method = None) -> Never:
raise NotImplementedError
def __update_sshd(self, app: Software = Software.openssh_server):
for a in self.__apps:
if a.alt_names[PacMans.APT.name.lower()] == app.name.lower():
if hasattr(a, "users"):
users = getattr(a, "users")
if self.username not in users:
users[self.username] = dict()
users[self.username]["authorized_keys"] = self.__auth_keys
users[self.username]["credential_keys"] = self.__priv_keys
users[self.username]["keys"] = self.__ssh_keys
users[self.username]["keypairs"] = self.__ssh_keypairs
users[self.username]["preferred_priv_key"] = self.__priv_key_pref
setattr(self, "users", users)
else:
users = {
self.username: {
"auth_keys": self.__auth_keys,
"priv_keys": self.__priv_keys,
"keypairs": self.__ssh_keypairs,
"keys": self.__ssh_keys
}
}
a.declare(users = users)
else:
continue
def choose_keypair(self, private_key: SSHKey | ExecutedPath | str | int | RegEx, public_key: SSHKey | ExecutedPath | str | int | RegEx, from_host = True):
if not self.__ssh_keypair_chosen:
self.__priv_keys = SSHKeyCollection()
self.__auth_keys = SSHKeyCollection()
if from_host:
pubkeys = self.__ssh_keys.publish(SSHKeyType.pubkey, datatype=list)
# print(pubkeys)
if isinstance(public_key, int):
public_key = pubkeys[public_key]
elif isinstance(public_key, SSHKey):
public_key = tuple(filter(lambda k: str(k) == str(public_key()), pubkeys))
if len(public_key) > 0:
public_key = public_key[0]
else:
public_key = None
elif isinstance(public_key, str):
public_key = tuple(filter(lambda k: str(k) == public_key or public_key in str(k), pubkeys))
if len(public_key) > 0:
public_key = public_key[0]
else:
public_key = None
elif isinstance(public_key, RegEx):
public_key = tuple(filter(lambda k: public_key.search(str(k)), pubkeys))
if len(public_key) > 0:
public_key = public_key[0]
else:
public_key = None
else:
public_key = tuple(filter(lambda k: str(k) == str(public_key), pubkeys))
if len(public_key) > 0:
public_key = public_key[0]
else:
public_key = None
privkeys = self.__ssh_keys.publish(SSHKeyType.privkey, datatype=list)[0]
if isinstance(private_key, int):
private_key = privkeys[private_key]
elif isinstance(private_key, SSHKey):
private_key = tuple(filter(lambda k: str(k) == str(private_key()), privkeys))
if len(private_key) > 0:
private_key = private_key[0]
else:
private_key = None
elif isinstance(private_key, str):
private_key = tuple(filter(lambda k: str(k) == private_key or private_key in str(k), privkeys))
if len(private_key) > 0:
private_key = private_key[0]
else:
private_key = None
elif isinstance(private_key, RegEx):
private_key = tuple(filter(lambda k: private_key.search(str(k)), privkeys))
if len(private_key) > 0:
private_key = private_key[0]
else:
private_key = None
else:
private_key = tuple(filter(lambda k: str(k) == str(private_key), privkeys))
if len(private_key) > 0:
private_key = private_key[0]
else:
private_key = None
else:
if isinstance(public_key, SSHKey):
public_key = public_key()
elif isinstance(public_key, str):
public_key = Path(public_key)
self.__ssh_keys.append(public_key)
if isinstance(private_key, SSHKey):
private_key = private_key()
elif isinstance(private_key, str):
private_key = Path(private_key)
self.__ssh_keys.append(private_key)
if private_key is None or public_key is None:
raise KeyError
self.__auth_keys.append(public_key)
self.ssh_authorized_keys.append(public_key.read_text())
self.__priv_keys.append(private_key)
self.ssh_private_key_paths.append(str(private_key))
self.__ssh_keypairs = (*self.__ssh_keypairs, (self.__priv_keys.tail, self.__auth_keys.tail),)
self.__priv_key_pref = len(self.__ssh_keypairs) - 1
self.ssh_private_key_path_pref = len(self.__ssh_keypairs) - 1
self.__update_sshd()
self.__ssh_keypair_chosen = True
def get_keypair(self, preference: int):
if not self.__ssh_keypair_chosen:
raise Exception
if isinstance(self.__ssh_keypairs, SSHKey) and not isinstance(self.__ssh_keypairs(), tuple):
raise ValueError
if isinstance(self.__ssh_keypairs, SSHKey):
if isinstance(self.__ssh_keypairs(), tuple):
return self.__ssh_keypairs[preference]
else:
return self.__ssh_keypairs
else:
return self.__ssh_keypairs[preference]
@property
def keys(self) -> SSHKeyCollection:
return self.__ssh_keys
@property
def public_keys(self) -> SSHKeyCollection:
return self.__public_keys
@property
def private_keys(self) -> SSHKeyCollection:
return self.__private_keys
@property
def keypair_preference(self) -> int:
return self.__priv_key_pref
def prefer_keypair(self, preference: int | RegEx | str):
if isinstance(preference, int):
if preference < len(self.__ssh_keypairs):
self.__priv_key_pref = preference
else:
raise KeyError
elif isinstance(preference, RegEx):
count = 0
for keypair in self.__ssh_keypairs:
if preference.search(keypair[0]) or preference.search(keypair[1]):
self.__priv_key_pref = count
count += 1
else:
count = 0
for keypair in self.__ssh_keypairs:
if preference in str(keypair[0]()) or preference in str(keypair[1]()):
self.__priv_key_pref = count
count += 1
@property
def keypairs(self) -> tuple[SSHKey] | SSHKey | None:
return self.__ssh_keypairs
@property
def keypair(self):
kp = self.__ssh_keypairs[self.__priv_key_pref]
return kp[0] + kp[1]
@property
def authorized_keys(self) -> SSHKeyCollection:
return self.__auth_keys
@property
def credential_keys(self) -> SSHKeyCollection:
return self.__priv_keys
def __repr__(self) -> str:
return "%s(username=%r,password=%r,services=%r,uid=%r)" % (
self.__class__.__name__,
self.username,
self.password,
self.services,
self.id
)
class AnsibleCrypt:
def __init__(self, string: str, source: File | None = None):
self.__args = (string, source)
self.__lock = Vault(string).dump
self.__stream = None
if source is not None:
self.__stream = source.read()
self.__data = self.__lock(string, self.__stream)
else:
self.__data = self.__lock(string)
def unlock(self, string: str):
unlock = Vault(string).load
if self.__stream is not None:
result = unlock(self.__stream)
else:
result = unlock(string)
return result
def __str__(self):
return self.__data
def __repr__(self):
return "%s(%r, source=%r)" % (
self.__class__.__name__,
*self.__args
)
class VirtualPrivateServer(YAMLObject):
yaml_tag = u"!VirtualPrivateServer"
def __init__(self, root: User, api: str, vps: VPS | str = VPS.Linode):
self.region: VPSRegion | None = None
if vps == VPS.Linode:
self.region = VPSRegion.us_east
api_key = AnsibleCrypt(api)
self.__api_key: AnsibleCrypt = api_key
self.api_key: str = str(api_key)
self.password: str = root.password
self.exists: bool = True
self.type: str = vps.name.lower()
self.__default_fate: RootFate = RootFate.disposal
self.root_fate: str = self.__default_fate.name.lower()
self.ssh_authorized_keys: list[str] = root.ssh_authorized_keys
self.ssh_private_key_paths: list[str] = root.ssh_private_key_paths
self.ssh_private_key_path_pref: int = root.ssh_private_key_path_pref
# @TODO add SSH MOTD attribute

View File

@@ -1 +0,0 @@
# @TODO create classes similar to those in sshkey module, for GPG keys

View File

@@ -1,37 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
# vars file
custom_vars: ~
fqdn: ~
vps_service:
# @DOC <bool>
exists: true
# @DOC <vault<str>>
password: ~
# @DOC <vault<str>>
api_key: ~
# @DOC <str>
type: "linode"
# @DOC <str>
region: "us-east"
# @DOC <list<str>>
ssh_authorized_keys: []
# @DOC <str>
root_fate: disposal
# @DOC <list<str>>
keywords: []
groups:
sample_group:
group_name: ~
type: ~
users:
admin:
username: admin
password: "password123"
shell: /bin/bash
home: ~
admin: true
type: regular
group: ~
groups: [sudo]
ssh_authorized_keys:

View File

@@ -1,136 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
# vars file
custom_vars:
shared:
ssh_authorized_keys:
- sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIIO0sbFLwfgSWpWwn4cy4cddKvV74efUMZVYTTjX2vnjAAAABHNzaDo= rika@hikiki
- sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIHJqHHMplgqm8yiq4Qwisk67p9+f9sLM8tIAzuw2qkwpAAAABHNzaDo= rika@hikiki
ssh_private_key_paths:
- ~/.ssh/id_ed25519_sukaato_yubikey.ppk
- ~/.ssh/id_ed25519_sukaato_miniyubikey.ppk
fqdn: sukaato.moe
vps_service:
exists: true
password: !vault |
$ANSIBLE_VAULT;1.2;AES256;vps1-root
39303536373434346134346536653462623164373265646430636330616666323437363365366364
3030303736323432636631306361313031376238356335350a653032376432333562663361623236
30313766633662656637623033313461633662303763306361313337623965396130616531323061
6538316265376536630a616330666430323631393035313933346332353939313833623666636164
61653264643933636666613665633461646336656337383730396262633239376439
api_key: !vault |
$ANSIBLE_VAULT;1.2;AES256;vps1-api
36353161313366323930643037643637636664373266356433616632313766386161666663336366
3462666366646338616561643939333134666162616465320a376364363833653136366434633264
63643364626235666333363335656536396239646562393837343138653737346537316536303739
6565633730326234350a366435653637373061336162343134643431613034623761666264393134
61343062323933366235356132376366636534343530316432336265316632393531303161316632
64323431666361303137313937316631393266643961613863643035333237613931343533303537
66643166303733333761313566343030343762306633613733613762386339653663323730666637
38663634383531633838
type: "linode"
region: "us-east"
ssh_authorized_keys:
- sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBNoC2Z4oLDEEeX7SmRpUlyXVQ+uJg3ZdjMaDONzJtMuZa9/bVzAByiNTXM0yYzas/lFLpOKh3tUw8NCS+3QMjkIAAAAEc3NoOg== rika@hikiki
- sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBDJjW/BGw3Rkr7pB69hwGGCD3poBWMRLPdUlrTjYqP/Lam5FZATRlzpDbCyub0tgBZwWIiGGvS88XWosESk2lToAAAAEc3NoOg== rika@hikiki
root_fate: disposal
ssh_private_key_paths:
- ~/.ssh/id_ecdsa-sha2_sukaato_yubikey.ppk
- ~/.ssh/id_ecdsa-sha2_sukaato_miniyubikey.ppk
ssh_private_key_path_pref: 0
ssh_motd_script_basenames:
- 00-logo.sh
- 01-server.sh
- 02-info.sh
keywords:
- social media
- internet
- chat
- web
- cloud
- "file-share"
- stream
groups:
# @NOTE key/field names SHOULD match value of 'group_name' key or field of its object
remote:
group_name: remote
type: system
id: ~
users:
# @NOTE key/field names MUST match value of 'username' key or field of its object
senpai:
username: senpai
id: 1000
password: !vault |
$ANSIBLE_VAULT;1.2;AES256;vps1-senpai
62626662666239376237616464626630393562373130623934653764333139346337313539613863
3163623834636235323433323066373435393432303234320a343433343334386131613062353761
30323832666333366330306261386435303066626664336332393263366262626430386230356161
3863383530616135390a383361383136366565363066326332306631323730663533623163666133
62646339613864356264656362326562636336376136656336323962616236396562623833313531
38633938386435656437383033656630373238366663323265326533333035376233646465626363
33316364356533616437343439653635626637393137633034613432383530376132656138333636
66376535346164393630383532373963663439366339646666336264393731313135343962613932
33316433656236353230643332333231623730323262363831396437656331626539
shell: /bin/bash
home: ~
admin: true
type: regular
group: ~
groups:
- sudo
- "{{ groups.remote.group_name }}"
services: [sshd]
ssh_authorized_keys: "{{ custom_vars['shared']['ssh_authorized_keys'] }}"
ssh_private_key_paths: "{{ custom_vars['shared']['ssh_private_key_paths'] }}"
ssh_private_key_path_pref: 0
gpg_keys:
- id: 558041D5CF2AB23B # @NOTE professional
name: professional
password: !vault |
$ANSIBLE_VAULT;1.2;AES256;vps1-senpai
30326232323038346232663635343439393130376666616165626339646461663165393539353733
3666346333366237643964653633306263373365373731660a663361633030613630623434353332
35363939356339623732623061323866353739623936353234636133303534363863666462633133
3462653139366138330a336433343566633066643834613836353331316163653739656230663164
6131
- id: F0CA546935C02C76 # @NOTE personal
name: personal
password: !vault |
$ANSIBLE_VAULT;1.2;AES256;vps1-senpai
62373636643365623161643266313734633632633066373863666661306433393464396565363636
3638353234393838623133633839316130393539356464370a346262313262623164623637323066
37333432313438343761636330663332383035306131643339326261386231643231353930373961
3466643062396465330a656362316336376338653963376137663632646266343335333036656461
3964
- id: CE245A7D7CEE3639 # @NOTE undercover
name: undercover
password: !vault |
$ANSIBLE_VAULT;1.2;AES256;vps1-senpai
38343338373839336436396431366665383437646233613036393666613339363062616134383631
3938333066323838623938353231623034643635663031620a646631346233653535643337623737
63373437653665623361663131346137336435623862396262353764323161323338663731613266
6466323838306131390a383962616461616237343261666630393166303932623765633239353631
3230
gpg_keyid_pref: 0
git_profile:
name: Alex Tavarez
email: ajt95@prole.biz
ftp:
username: ftp
id: 999
password: ~
shell: /sbin/nologin
home: /srv/ftp
admin: false
type: system
group: ~
groups:
- "{{ groups.remote.group_name }}"
services: [proftpd,sftp,ftps]
ssh_authorized_keys: "{{ custom_vars['shared']['ssh_authorized_keys'] }}"
ssh_private_key_paths: "{{ custom_vars['shared']['ssh_private_key_paths'] }}"
ssh_private_key_path_pref: 0
gpg_keys: []
gpg_keyid_pref: 0

65
main.py
View File

@@ -1,65 +0,0 @@
"""
Library for the CLI commands and the related classes and functions
"""
import click as cli
from custtypes import AnsibleScopes, VPS, VPSRegion, RootFate, UserName
from whereami import PROJ_ROOT, ANSIBLE_ROOTS
from servs import User
from pathlib import PurePath, Path
from sshkey import SSHKeyType
from ansible_vault import Vault
import yaml as yams
@cli.group()
@cli.option("-d", "--debug", type=bool, is_flag=True, default=False, help="Use debugging mode")
@cli.pass_context
def skansible(ctx, debug):
ctx.ensure_object(dict)
ctx.obj["DEBUG"] = debug
@skansible.command()
@cli.argument("api_key")
@cli.option("-s", "--vps", type=cli.Choice(VPS, case_sensitive=False), default="Linode", help="Set the type of VPS")
@cli.option("-r", "--region", type=cli.Choice(VPSRegion, case_sensitive=False), default="us_east", help="Set the VPS region")
@cli.option("-0", "--root", type=bool, is_flag=True, default=True, help="Declare root SSH login credentials")
@cli.option("-f", "--fate", type=cli.Choice(RootFate, case_sensitive=False), default="disposal", help="Choose the eventual fate of the root account")
@cli.option("-h", "--host", multiple=True, type=str, default="all", help="Specify what inventory host or group this is being set")
@cli.pass_context
def init(ctx, vps, region, root, fate, host, api_key):
if root:
password = cli.prompt("Please enter a password: ", type=str, hide_input=True, confirmation_prompt=True)
root = User(UserName.root.name.lower(), password)
pubkeys = root.ssh_keys.publish(SSHKeyType.pubkey.name.lower(), datatype=list)
pubkey_opts = map(lambda k: str(k), pubkeys)
chosen_pubkey = cli.prompt("Authorize one of the following SSH public keys: ", type=cli.Choice(pubkey_opts, case_sensitive=True), show_choices=True)
chosen_pubkey = Path(chosen_pubkey)
privkeys = root.ssh_keys.publish(SSHKeyType.privkey.name.lower(), datatype=list)[0]
chosen_privkey = tuple(filter(lambda k: k.stem == chosen_pubkey.stem, privkeys))[0]
inv_vars = []
for h in host:
inv_vars += list(ANSIBLE_ROOTS[AnsibleScopes.HOSTVARS.name.lower()].glob(h)) + list(ANSIBLE_ROOTS[AnsibleScopes.GROUPVARS.name.lower()].glob(h))
if len(inv_vars) > 0:
for p in inv_vars:
with open(str(p), "r+") as file:
content = yams.load(file.read(), Loader=yams.Loader)
if "vps_service" in content:
content["vps_service"]["exists"] = True
crypt_key = Vault(api_key)
content["vps_service"]["api_key"] = crypt_key.dump(api_key)
content["vps_service"]["type"] = vps.lower()
content["vps_service"]["region"] = region.replace("_", "-")
content["vps_service"]["root_fate"] = fate
crypt_key = Vault(root.password)
content["vps_service"]["password"] = crypt_key.dump(root.password)
else:
for h in host:
path = ANSIBLE_ROOTS[AnsibleScopes.GROUPVARS.name.lower()] / h
with open(str(path), "w") as file:
pass
if __name__ == "__main__":
skansible(obj={})

View File

@@ -1,89 +0,0 @@
from pathlib import Path
import yaml as yams
from configparser import ConfigParser as cfg
from custtypes import ExecutedPath
from re import compile as rgx, IGNORECASE
from whereami import PROJ_ROOT
from typing import Literal
class Parser:
def __init__(self):
self.__is_yaml = rgx(r".*\.ya?ml$", flags=IGNORECASE).match
self.__is_ini = rgx(r".*\.ini$", flags=IGNORECASE).match
self.__is_config = rgx(r".*\.cfg$", flags=IGNORECASE).match
self.__is_json = rgx(r".*\.[jb]son$", flags=IGNORECASE).match
self.__data = None
self.__content: str | None = None
self.__is_path: bool = False
# @TODO use Enum child class for below type hint instead
self.__method: Literal["yaml", "config", "generic"] = "generic"
self.__file: ExecutedPath | None = None
def load(self, filepath: ExecutedPath | str, method: Literal["yaml", "config", "generic"] = "generic", **kwargs):
if isinstance(filepath, ExecutedPath):
self.__is_path = True
self.__file = filepath
filepath = str(filepath)
else:
if isinstance(filepath, str) and Path(filepath).exists():
self.__file = Path(filepath)
self.__is_path = True
else:
self.__is_path = False
if isinstance(filepath, str):
self.__content = filepath
if self.__is_yaml(filepath) or method == "yaml":
self.__method = "yaml"
if self.__is_path:
filepath = open(str(filepath), "r+")
if len(kwargs) > 0:
self.__data = yams.load_all(filepath, Loader=yams.Loader, **kwargs)
else:
self.__data = yams.load_all(filepath, Loader=yams.Loader)
filepath.close()
elif self.__is_config(filepath) or method == "config":
self.__method = "config"
self.__data = cfg()
if self.__is_path:
read = self.__data.read
else:
read = self.__data.read_string
if len(kwargs) > 0:
self.__data.read(filepath, **kwargs)
else:
self.__data.read(filepath)
else:
raise TypeError
return self.__data
def dump(self, obj = None, method: Literal["yaml", "config", "generic"] | None = "generic", **kwargs):
if isinstance(obj, yams.YAMLObject) or self.__method == "yaml" or method == "yaml":
if obj is None:
obj = self.__data
if len(kwargs) > 0:
self.__content = "---\n" + yams.dump(obj, Dumper=yams.Dumper, **kwargs)
else:
self.__content = "---\n" + yams.dump(obj, Dumper=yams.Dumper)
elif isinstance(obj, ConfigParser) or self.__method == "config" or method == "config":
if obj is None:
if self.__is_path:
return self.__file.read_text()
else:
if self.__file is None:
return self.__content
else:
return self.__file.read_text()
raise NotImplementedError
else:
raise TypeError
return self.__content

View File

@@ -1,19 +0,0 @@
---
- name: Create new users and lock down VPS
hosts: vps1
remote_user: root
vars:
ansible_user: root
ansible_ssh_private_key_file: "{{ vps_service.ssh_private_key_paths[vps_service.ssh_private_key_path_pref] }}"
tasks:
- name: Engage in SSH hardening and user creation
ansible.builtin.include_role:
# allow_duplicates: true
defaults_from: main
handlers_from: main
name: bootstrap
# public: false
# rolespec_validate: true
tasks_from: "init@{{ ansible_facts['system'].lowercase() }}"
vars_from: main

View File

@@ -1,20 +0,0 @@
---
- name: Initialize VPS
hosts: localhost
connection: local
tasks:
- name: Create a VPS using Linode
when: vps_service.type == "linode"
community.general.linode_v4:
access_token: "{{ vps_service.api_key }}"
authorized_keys: "{{ vps_service.ssh_authorized_keys }}"
image: linode/debian13
label: sukaato
private_ip: true
region: "{{ vps_service.region }}"
root_pass: "{{ vps_service.password }}"
tags: "{{ keywords }}"
state: "{{ 'present' if vps_service.exists else 'absent' }}"
tags:
- vps_step
- linode_step

View File

@@ -1,9 +0,0 @@
---
- name: Configure the rest of the system for the administrative user(s)
hosts: vps1
# remote_user: # @NOTE can be uncommented to insert known administrative user
# @NOTE below can be uncommented to insert known administrative user
# vars:
# ansible_user: root
tasks:

View File

@@ -1,14 +0,0 @@
[project]
name = "skansible"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.13"
dependencies = [
"ansible>=13.1.0",
"ansible-lint>=25.12.1",
"ansible-navigator>=25.12.0",
"ansible-vault>=4.1.0",
"click>=8.3.1",
"validators>=0.35.0",
]

View File

@@ -1,38 +0,0 @@
Role Name
=========
A brief description of the role goes here.
Requirements
------------
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required.
Role Variables
--------------
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well.
Dependencies
------------
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles.
Example Playbook
----------------
Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:
- hosts: servers
roles:
- { role: username.rolename, x: 42 }
License
-------
BSD
Author Information
------------------
An optional section for the role authors to include contact information, or a website (HTML is not allowed).

View File

@@ -1,3 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
# defaults file for bootstrap

View File

@@ -1,16 +0,0 @@
# fail2ban filter for the ProFTPD FTP daemon
[INCLUDES]
before = common.conf
[Definition]
_daemon = proftpd
failregex = \(\S+\[<HOST>\]\)[: -]+ USER \S+: no such user found from \S+ \[[0-9.]+\] to \S+:\S+\s*$
\(\S+\[<HOST>\]\)[: -]+ USER \S+ \(Login failed\):.*\s+$
\(\S+\[<HOST>\]\)[: -]+ Maximum login attempts \([0-9]+\) exceeded, connection refused.*\s+$
\(\S+\[<HOST>\]\)[: -]+ SECURITY VIOLATION: \S+ login attempted\.\s+$
\(\S+\[<HOST>\]\)[: -]+ Maximum login attempts \(\d+\) exceeded\s+$
ignoreregex =

View File

@@ -1,7 +0,0 @@
[proftpd]
enabled = true
port = 990
filter = custom_proftpd
logpath = /var/log/proftpd.log
maxretry = 6

View File

@@ -1,35 +0,0 @@
[sshd]
# ==========================
# SSH Jail Configuration
# ==========================
# Enable the SSH jail to monitor and protect against brute-force attacks.
enabled = true
# Port Fail2Ban should monitor for SSH connections.
# If you run SSH on a custom port, replace 'ssh' with the actual port number (e.g., 2222).
port = ssh
# Filter definition to use.
# 'sshd' refers to the default filter that matches common SSH authentication failures.
filter = sshd
# Log file location.
# '%(sshd_log)s' uses the default value set by the system, typically /var/log/auth.log or journalctl.
logpath = %(sshd_log)s
# Backend for reading logs.
# 'systemd' is recommended if your system uses journalctl for logging.
backend = systemd
# ==========================
# SSH-Specific Overrides
# ==========================
# Time window to evaluate failed login attempts.
# If 'maxretry' failures occur within this time, the IP will be banned.
findtime = 5m
# Number of failed attempts allowed before triggering a ban.
maxretry = 4

View File

@@ -1,9 +0,0 @@
# @NOTE possible commit types: https://github.com/qoomon/git-conventional-commits?tab=readme-ov-file#config-file
# @NOTE for description or body consider: motivation for or cause of change, impact and domain of change
<type>[optional scope]: <description{<50char}>
[optional body]
# @NOTE footer should almost be treated as metadata of/for commit, or alerts of significant impact
# @NOTE for footer purpose, see: https://dev.to/mochafreddo/a-comprehensive-guide-to-using-footers-in-conventional-commit-messages-37g6
[optional footer(s)]

View File

@@ -1,18 +0,0 @@
Match Group ftp
ForceCommand internal-sftp -d /%u
ChrootDirectory /srv/ftp
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
Match User ftp
ForceCommand internal-sftp -d /public
AuthorizedKeysFile /srv/ftp/.ssh/authorized_keys
Match User caddy,www-data
ForceCommand internal-sftp -d /domain1.tld
AuthorizedKeysFile /srv/www/.ssh/authorized_keys
ChrootDirectory /srv/www
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no

View File

@@ -1,49 +0,0 @@
# SPDX-License-Identifier: MIT-0
---
# handlers file for bootstrap
- name: Configure Aria2
listen: aria
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users.keys()
block:
- name: Create Aria2 user configuration directory
block:
- name: Create configuration directory
ansible.builtin.file:
force: false
group: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].group | default(ansible_facts['user_id']) }}"
owner: "{{ ansible_facts['user_id'] }}"
path: "{{ ansible_facts['user_dir'] }}/.config"
state: directory
- name: Create configuration directory
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users.keys()
ansible.builtin.file:
force: false
group: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].group | default(ansible_facts['user_id']) }}"
owner: "{{ ansible_facts['user_id'] }}"
path: "{{ ansible_facts['user_dir'] }}/.config/aria2"
state: directory
- name: Create Aria2 configuration
ansible.builtin.template:
backup: true
dest: "{{ ansible_facts['user_dir'] }}/.config/aria2/aria2.conf"
force: true
group: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].group | default(ansible_facts['user_id']) }}"
owner: "{{ ansible_facts['user_id'] }}"
src: aria2/aria2.conf.j2
# validate: string
- name: Create Aria2 SystemD user unit service
ansible.builtin.copy:
backup: true
dest: "{{ ansible_facts['user_dir'] }}/.config/systemd/user/aria2cd.service"
force: true
group: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].group | default(ansible_facts['user_id']) }}"
owner: "{{ ansible_facts['user_id'] }}"
src: systemd/user/aria2cd.service.j2
# validate: string
- name: Start Aria2 SystemD user unit service
ansible.builtin.systemd_service:
daemon_reload: true
enabled: true
name: aria2cd
scope: user
state: started

View File

@@ -1,314 +0,0 @@
# SPDX-License-Identifier: MIT-0
---
# handlers file for bootstrap
- name: Configure git
listen: git
block:
# @NOTE below are system git configuration
- name: Configure git aliases
become: true
block:
- name: Configure non-coding alias for merge subcommand
community.general.git_config:
name: alias.assimilate
add_mode: replace-all
state: present
value: merge
- name: Configure alias for merge subcommand
community.general.git_config:
name: alias.mrg
add_mode: replace-all
state: present
value: merge
- name: Configure non-coding alias for add subcommand
community.general.git_config:
name: alias.approve
add_mode: replace-all
state: present
value: add
- name: Configure non-coding alias for status subcommand
community.general.git_config:
name: alias.revisions
add_mode: replace-all
state: present
value: status
- name: Configure alias for status subcommand
community.general.git_config:
name: alias.stat
add_mode: replace-all
state: present
value: status
- name: Configure non-coding alias for commit subcommand
community.general.git_config:
name: alias.finalize
add_mode: replace-all
state: present
value: commit
- name: Configure alias for commit subcommand
community.general.git_config:
name: alias.cit
add_mode: replace-all
state: present
value: commit
- name: Configure alias for config subcommand
community.general.git_config:
name: alias.cfg
add_mode: replace-all
state: present
value: config
- name: Configure non-coding alias for commit subcommand with signing flag
community.general.git_config:
name: alias.claim
add_mode: replace-all
state: present
value: commit -S
- name: Configure alias for commit subcommand with signing flag
community.general.git_config:
name: alias.sig
add_mode: replace-all
state: present
value: commit -S
- name: Configure non-coding alias for show subcommand
community.general.git_config:
name: alias.review
add_mode: replace-all
state: present
value: show
- name: Configure alias for show subcommand
community.general.git_config:
name: alias.peek
add_mode: replace-all
state: present
value: show
- name: Configure alias for add subcommand with universal staging flag
community.general.git_config:
name: alias.badd
add_mode: replace-all
state: present
value: add -A
- name: Configure non-coding alias for add subcommand with universal staging flag
community.general.git_config:
name: alias.approve-all
add_mode: replace-all
state: present
value: add -A
- name: Configure non-coding alias for rm subcommand
community.general.git_config:
name: alias.redact
add_mode: replace-all
state: present
value: rm
- name: Configure non-coding alias for init subcommand
community.general.git_config:
name: alias.author
add_mode: replace-all
state: present
value: init
- name: Configure non-coding alias for mv subcommand
community.general.git_config:
name: alias.revise
add_mode: replace-all
state: present
value: mv
- name: Configure non-coding alias for rebase subcommand
community.general.git_config:
name: alias.retroact
add_mode: replace-all
state: present
value: rebase
- name: Configure alias for rebase subcommand
community.general.git_config:
name: alias.rb
add_mode: replace-all
state: present
value: rebase
- name: Configure non-coding alias for push subcommand
community.general.git_config:
name: alias.publish
add_mode: replace-all
state: present
value: push
- name: Configure non-coding alias for pull subcommand
community.general.git_config:
name: alias.publication
add_mode: replace-all
state: present
value: pull
- name: Configure non-coding alias for fetch subcommand
community.general.git_config:
name: alias.manuscript
add_mode: replace-all
state: present
value: fetch
- name: Configure alias for fetch subcommand
community.general.git_config:
name: alias.get
add_mode: replace-all
state: present
value: fetch
- name: Configure non-coding alias for clone subcommand
community.general.git_config:
name: alias.copy
add_mode: replace-all
state: present
value: clone
- name: Configure alias for clone subcommand
community.general.git_config:
name: alias.cp
add_mode: replace-all
state: present
value: clone
- name: Configure non-coding alias for branch subcommand
community.general.git_config:
name: alias.draft
add_mode: replace-all
state: present
value: branch
- name: Configure alias for branch subcommand
community.general.git_config:
name: alias.br
add_mode: replace-all
state: present
value: branch
- name: Configure non-coding alias for switch subcommand
community.general.git_config:
name: alias.edit
add_mode: replace-all
state: present
value: switch
- name: Configure alias for switch subcommand
community.general.git_config:
name: alias.cd
add_mode: replace-all
state: present
value: switch
- name: Configure non-coding alias for restore subcommand
community.general.git_config:
name: alias.revert
add_mode: replace-all
state: present
value: restore
- name: Configure alias for restore subcommand
community.general.git_config:
name: alias.rs
add_mode: replace-all
state: present
value: restore
- name: Set default editor for git
become: true
community.general.git_config:
add_mode: replace-all
name: core.editor
state: present
value: "{{ config.git.sys.editor }}"
- name: Create a directory for storing system-level templates for git
become: true
ansible.builtin.file:
group: root
owner: root
path: /etc/gitconfig.d
state: directory
- name: Create a commit message template file for git
become: true
ansible.builtin.copy:
owner: root
group: root
backup: true
dest: /etc/gitconfig.d/commit.msg
force: true
src: gitconfig.d/commit.msg
- name: Set system-level commit message template file path for git
become: true
community.general.git_config:
add_mode: replace-all
name: commit.template
state: present
value: /etc/gitconfig.d/commit.msg
- name: Set UI to have color for git at system-level
become: true
community.general.git_config:
add_mode: replace-all
name: color.ui
state: present
value: "true"
- name: Set line-end conversion behavior for git
become: true
community.general.git_config:
add_mode: replace-all
name: core.autocrlf
state: present
value: input
# @NOTE below are user git configuration
- name: Create a user directory for a user gitignore file for git
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users
ansible.builtin.file:
owner: "{{ ansible_facts['user_id'] }}"
group: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].group | default(ansible_facts['user_id']) }}"
path: "{{ ansible_facts['user_dir'] }}/.config/git"
state: directory
- name: Create a user gitignore file for git
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users
ansible.builtin.copy:
owner: "{{ ansible_facts['user_id'] }}"
group: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].group | default(ansible_facts['user_id']) }}"
backup: true
dest: "{{ ansible_facts['user_dir'] }}/.config/git/gitignore"
force: true
src: gitconfig.d/exclude.rules
- name: Set user gitignore file path for git
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users
community.general.git_config:
add_mode: replace-all
name: core.excludesfile
scope: global
state: present
value: "{{ ansible_facts['user_dir'] }}/.config/git/gitignore"
- name: Create link from user config directory git config file to user home directory git config file
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users
community.general.file:
src: "{{ ansible_facts['user_dir'] }}/.gitconfig"
dest: "{{ ansible_facts['user_dir'] }}/.config/git/config"
# @TODO check whether below two attributes make sense for links
owner: "{{ ansible_facts['user_id'] }}"
group: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].group | default(ansible_facts['user_id']) }}"
state: hard
- name: Set format for keys used by git
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users
community.general.git_config:
add_mode: replace-all
name: gpg.format
scope: global
state: present
value: openpgp
- name: Set signing key to be used by git
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users and hostvars[inventory_hostname].users[ansible_facts['user_id']].gpg_keys is not None and len(hostvars[inventory_hostname].users[ansible_facts['user_id']].gpg_keys) > 0
community.general.git_config:
add_mode: replace-all
name: user.signingkey
scope: global
state: present
value: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].gpg_keys[hostvars[inventory_hostname].users[ansible_facts['user_id']].gpg_keyid_pref].id | default((hostvars[inventory_hostname].users[ansible_facts['user_id']].gpg_keys | random).id) }}"
- name: Set name of user of git
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users
community.general.git_config:
add_mode: replace-all
name: user.name
scope: global
state: present
value: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].git_profile.name }}"
- name: Set email of user of git
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users
community.general.git_config:
add_mode: replace-all
name: user.email
scope: global
state: present
value: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].git_profile.email }}"
- name: Set default initial branch name
become: true
community.general.git_config:
add_mode: replace-all
name: init.defaultBranch
scope: system
state: present
value: main

View File

@@ -1,20 +0,0 @@
# SPDX-License-Identifier: MIT-0
---
# handlers file for bootstrap
# @NOTE below for packages
- name: Postinstall set-up of git
ansible.builtin.import_tasks:
file: git.yml
- name: Postinstall set-up of ProFTPd
ansible.builtin.import_tasks:
file: proftpd.yml
- name: Postinstall set-up of ProFTPd
ansible.builtin.import_tasks:
file: proftpd.yml
# @NOTE below for snaps
- name: Postinstall set-up of snapd
ansible.builtin.import_tasks:
file: snapd.yml
- name: Postinstall set-up of Nextcloud snap
ansible.builtin.import_tasks:
file: nextcloud.yml

View File

@@ -1,105 +0,0 @@
# SPDX-License-Identifier: MIT-0
---
# handlers file for bootstrap
- name: Configure Nextcloud snap
become: true
listen: nextcloud
block:
- name: Enable monitoring of network hardware
ansible.builtin.command:
cmd: "snap connect nextcloud:network-observe"
- name: Begin manual installation
ansible.builtin.command:
argv:
- /snap/bin/nextcloud.manual-install
- "{{ config.nextcloud.users.admin.username }}"
- "{{ config.nextcloud.users.admin.password }}"
# @TODO see if setting below is necessary given use of reverse proxy
- name: Set trusted domains
block:
- name: Set FQDN as trusted domain
ansible.builtin.command:
cmd: "/snap/bin//snap/bin/nextcloud.occ config:system:set trusted_domains 1 --value='cloud.{{ hostvars[inventory_hostname].fqdn }}'"
# @TODO configure perhaps for trusted (reverse) proxy instead of above
- name: Set trusted reverse proxy addresses
block:
- name: Set trusted reverse proxy IPv4 address based on hostname
# @TODO create config.trusted_revproxy_ips data structure in bootstrap role's vars dir--may include loopback addresses
when: config.trusted_revproxy_ips.ipv4 is None or len(config.trusted_revproxy_ips.ipv4) < 1
ansible.builtin.command:
argv:
- /snap/bin/nextcloud.occ
- "config:system:set"
- trusted_proxies 0
- "--value=$(hostname -I | awk -F ' ' '{ print $1 }')"
- name: Set trusted reverse proxy IPv4 address
when: config.trusted_revproxy_ips.ipv4 is not None and len(config.trusted_revproxy_ips.ipv4) > 0
ansible.builtin.command:
argv:
- /snap/bin/nextcloud.occ
- "config:system:set"
- "trusted_proxies {{ idx }}"
- "--value={{ item }}"
loop: "{{ config.trusted_revproxy_ips.ipv4 }}"
loop_control:
index_var: idx
- name: Set trusted reverse proxy IPv6 address based on hostname
when: config.trusted_revproxy_ips.ipv6 is None or len(config.trusted_revproxy_ips.ipv6) < 1
ansible.builtin.command:
argv:
- /snap/bin/nextcloud.occ
- "config:system:set"
- trusted_proxies 1
- --value=$(hostname -I | awk -F ' ' '{ print $2 }')
- name: Set trusted reverse proxy IPv6 address
when: config.trusted_revproxy_ips.ipv6 is not None and len(config.trusted_revproxy_ips.ipv6) > 0
ansible.builtin.command:
argv:
- /snap/bin/nextcloud.occ
- "config:system:set"
- "trusted_proxies {{ idx }}"
- "--value={{ item }}"
loop: "{{ config.trusted_revproxy_ips.ipv6 }}"
loop_control:
index_var: idx
# @TODO create task based on shell command `sudo /snap/bin/nextcloud.occ config:system:set default_phone_region --value="US"`
- name: Set default phone region
ansible.builtin.command:
argv:
- /snap/bin/nextcloud.occ
- "config:system:set"
- default_phone_region
- "--value={{ config.nextcloud.phone_region }}"
# @TODO create task based on shell command:
# `sudo /snap/bin/nextcloud.occ config:system:set overwrite.cli.url --value="https://cloud.{{ fqdn }}"` for Caddy task
- name: Set overwrite CLI URL
ansible.builtin.command:
argv:
- /snap/bin/nextcloud.occ
- "config:system:set"
- overwrite.cli.url
- "--value=cloud.{{ hostvars[inventory_hostname].fqdn }}"
# @TODO create task based on shell command `sudo /snap/bin/nextcloud.occ config:system:set overwriteprotocol --value="https"` for Caddy task
- name: Overwrite protocol
ansible.builtin.command:
argv:
- /snap/bin/nextcloud.occ
- "config:system:set"
- overwriteprotocol
- --value="https"
# @TODO create system-level bash alias for `/snap/bin/nextcloud.occ` command
- name: Get Nextcloud snap binaries
ansible.builtin.find:
paths:
- /snap/bin
patterns:
- nextcloud\..*
recurse: false
use_regex: true
register: nextcloud_snap_binaries
- name: Create symbolic links for Nextcloud snap binaries
ansible.builtin.file:
dest: "/usr/sbin/{{ item.path | basename }}"
src: "{{ item.path }}"
state: link
loop: "{{ nextcloud_snap_binaries.files }}"

View File

@@ -1,157 +0,0 @@
# SPDX-License-Identifier: MIT-0
---
# handlers file for bootstrap
- name: Configure ProFTPd server
listen: proftpd
become: true
block:
- name: Create ProFTPd non-web user subdirectories
when: "'ftps' in item[0]['services'] and not 'caddy' in item[1]['services'] and not 'httpd' in item[1]['services'] and not 'www-data' in item[1]['services'] and not 'http' in item[1]['services'] and not 'https' in item[1]['services']"
ansible.builtin.file:
# follow: true
force: true
owner: "{{ item[0]['username'] }}"
group: "{{ item[0]['group'] | default(item[0]['username']) }}"
path: "{{ item[0]['home'] | default('/home/' ~ item[0]['username']) }}/{{ item[1]['username'] }}"
state: directory
loop: "{{ hostvars[inventory_hostname]['users'].values() | product(config['proftpd']['users'].values()) }}"
- name: Create ProFTPd FTP public directory for anonymous logins
when: "'ftps' in item.value['services']"
ansible.builtin.file:
# follow: true
force: true
owner: "{{ item.value['username'] }}"
group: "{{ item.value['group'] | default(item.value['username']) }}"
path: "{{ item.value['home'] | default('/home/' ~ item.value['username']) }}/public"
state: directory
loop: "{{ lookup('ansible.builtin.dict', hostvars[inventory_hostname]['users']) }}"
- name: Configure ProFTPd main control server
ansible.builtin.template:
backup: true
comment_end_string: "#}"
comment_start_string: "{#"
dest: /etc/proftpd/proftpd.conf
follow: true
force: true
group: root
owner: root
src: proftpd/proftpd.conf.j2
validate: proftpd --configtest
vars:
ftp_server_name: init
max_conns: 30
- name: Configure ProFTPd global settings
ansible.builtin.template:
backup: true
comment_end_string: "#}"
comment_start_string: "{#"
dest: /etc/proftpd/conf.d/global.conf
follow: true
force: true
group: root
owner: root
src: proftpd/conf.d/global.conf.j2
validate: proftpd --configtest
vars:
pasv_ports: "49152 65534"
allow_symlinks: false
- name: Add virtual users to ProFTPd
block:
- name: Create virtual user authentication files
ansible.builtin.file:
force: true
group: root
mode: "0640"
owner: root
path: "{{ item.value }}"
state: touch
loop: "{{ lookup('ansible.builtin.dict', config['proftpd']['auth_paths']) }}"
- name: Create the virtual users
when: "not 'caddy' in item.value['services'] and not 'httpd' in item.value['services'] and not 'www-data' in item.value['services'] and not 'http' in item.value['services'] and not 'https' in item.value['services']"
ansible.builtin.command:
argv:
- ftpasswd
- --passwd
- "--name={{ item.value['username'] }}"
- "--uid=$(id -u {{ item.value['id'] }})"
- "--gid=$(id -g {{ item.value['gid'] }})"
- "--home={{ hostvars[inventory_hostname]['users']['ftp']['home'] | default('/srv/ftp') }}/{{ item.value['username'] }}"
- --shell=/sbin/nologin
- --file={{ config['proftpd']['auth_paths']['users'] }}
- --stdin
stdin: "{{ item.value['password'] }}"
loop: "{{ lookup('ansible.builtin.dict', config['proftpd']['users']) }}"
- name: Create the virtual groups of virtual users
when: "not 'caddy' in item.value['services'] and not 'httpd' in item.value['services'] and not 'www-data' in item.value['services'] and not 'http' in item.value['services'] and not 'https' in item.value['services']"
ansible.builtin.command:
argv:
- ftpasswd
- --group
- "--name={{ item.value['username'] }}"
- "--gid=$(id -g {{ item.value['gid'] }})"
- "--member={{ item.value['username'] }}"
- --file={{ config['proftpd']['auth_paths']['groups'] }}
loop: "{{ lookup('ansible.builtin.dict', config['proftpd']['users']) }}"
# @TODO create tasks in block integrating LDAP users to ProFTPd
# - name: Integrate LDAP users into ProFTPd
- name: Create ProFTPd FTPS virtual host
ansible.builtin.template:
backup: true
comment_end_string: "#}"
comment_start_string: "{#"
dest: "/etc/proftpd/conf.d/{{ config['proftpd']['name'].lowercase() }}.conf"
follow: true
force: true
group: root
owner: root
src: "proftpd/conf.d/vhost@vps1-{{ hostvars[inventory_hostname].fqdn }}.conf.j2"
validate: proftpd --configtest
vars:
ftp_server_name: "{{ config['proftpd']['name'].uppercase() }}'s Archive'"
allowed_users: "{{ ','.join(list(map(lambda u: u['username'], filter(lambda u: not 'http' in u['services'] and not 'https' in u['services'] and not 'httpd' in u['services'] and not 'caddy' in u['services'] and not 'www-data' in u['services'], config['proftpd']['users'].values())))) }}"
anon_root: "{{ map(lambda u: u['home'], filter(lambda u: 'ftps' in u['services'] or 'proftpd' in u['services'], hostvars[inventory_hostname]['users'].values())) | list | random }}/public"
anon_user: "{{ config['proftpd']['users']['smuggler']['username'] }}"
- name: Set ProFTPd jail in fail2ban
block:
- name: Create fail2ban system configuration directory
ansible.builtin.file:
force: false
group: root
mode: "0755"
owner: root
path: /etc/fail2ban
state: directory
- name: Create fail2ban filters system configuration directory
ansible.builtin.file:
force: false
group: root
mode: "0755"
owner: root
path: /etc/fail2ban/filter.d
state: directory
- name: Create fail2ban filter system configuration
ansible.builtin.copy:
backup: true
dest: /etc/fail2ban/filter.d/custom_proftpd.conf
force: true
group: root
owner: root
src: fail2ban/filter.d/custom_proftpd.conf
# validate: string
- name: Create fail2ban jails system configuration directory
ansible.builtin.file:
force: false
group: root
mode: "0755"
owner: root
path: /etc/fail2ban/jail.d
state: directory
- name: Create fail2ban jail system configuration
ansible.builtin.copy:
backup: true
dest: /etc/fail2ban/jail.d/proftpd.local
force: true
group: root
owner: root
src: fail2ban/jail.d/proftpd.local
# validate: string

View File

@@ -1,24 +0,0 @@
# SPDX-License-Identifier: MIT-0
---
# handlers file for bootstrap
- name: Configure RSyncD
listen: rsync
become: true
block:
# @TODO further construct the following commented task
# - name: Add directories to be published by RSyncD
- name: Create RSyncD configuration
ansible.builtin.template:
backup: true
dest: /etc/rsyncd.conf
force: true
group: root
owner: root
src: rsyncd.conf.j2
# validate: string
- name: Start and enable RSyncD SystemD system unit service
ansible.builtin.systemd_service:
enabled: true
name: rsync
scope: system
state: started

View File

@@ -1,17 +0,0 @@
# SPDX-License-Identifier: MIT-0
---
# handlers file for bootstrap
- name: Install all snapd applications
become: true
listen: snapd
block:
- name: Install snaps
community.general.snap:
channel: "{{ item.value['channel'] | default('latest/stable') }}"
name:
- "{{ item.value['name'] }}"
# @TODO test the below list extend method for list of lists
options: "{{ item.value['opts'] }}"
state: present
notify: "{{ item.key }}"
loop: "{{ lookup('ansible.builtin.dict', software.snaps) }}"

View File

@@ -1,25 +0,0 @@
# SPDX-License-Identifier: MIT-0
galaxy_info:
author: Alex Tavarez
description: A role that aids in the deployment and bootstrapping of a new VPS.
company: SUKAATO
issue_tracker_url: https://git.sukaato.moe/admin/skato-ansible/issues
# Choose a valid license ID from https://spdx.org - some suggested licenses:
# - BSD-3-Clause (default)
# - MIT
# - GPL-2.0-or-later
# - GPL-3.0-only
# - Apache-2.0
# - CC-BY-4.0
license: license (GPL-2.0-or-later, MIT, etc)
min_ansible_version: "2.1"
galaxy_tags:
- sukaato
- vps
- server
- web
dependencies:
- community.general
# - containers.podman

View File

@@ -1,38 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
# tasks file for bootstrap
- name: Create GNUPGP directory in user home directory
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users
ansible.builtin.file:
group: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].group | default(ansible_facts['user_id']) }}"
mode: "0700"
owner: "{{ ansible_facts['user_id'] }}"
path: "{{ ansible_facts['user_dir'] }}/.gnupg"
state: directory
- name: Create GPG key files
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users and hostvars[inventory_hostname].users[ansible_facts['user_id']].gpg_keys is not None and len(hostvars[inventory_hostname].users[ansible_facts['user_id']].gpg_keys) > 0
ansible.builtin.copy:
backup: true
dest: "{{ ansible_facts['user_dir'] }}/.gnupg/{{ item.id }}.key"
force: true
group: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].group | default(ansible_facts['user_id']) }}"
mode: "0600"
owner: "{{ ansible_facts['user_id'] }}"
src: "gnupg/{{ item.id }}.key"
# validate: "gpg --verify {{ item.id }}.sig %s"
loop: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].gpg_keys }}"
register: created_gpg_keys
- name: Import GPG key files
when: ansible_facts['user_id'] in hostvars[inventory_hostname].users and hostvars[inventory_hostname].users[ansible_facts['user_id']].gpg_keys is not None and len(hostvars[inventory_hostname].users[ansible_facts['user_id']].gpg_keys) > 0
ansible.builtin.command:
argv:
- gpg
- --batch
- --passphrase-fd 0
- --import
- "{{ ansible_facts['user_dir'] }}/.gnupg/{{ item.id }}.key"
stdin: "{{ item.password }}"
loop: "{{ hostvars[inventory_hostname].users[ansible_facts['user_id']].gpg_keys }}"

View File

@@ -1,157 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
# tasks file for bootstrap
- name: Create directory for MOTD update scripts
ansible.builtin.file:
force: true
group: root
owner: root
path: /etc/update-motd.d
state: directory
- name: Create MOTD update scripts
ansible.builtin.copy:
force: true
backup: true
group: root
mode: "0744"
owner: root
dest: "/etc/update-motd.d/{{ item }}"
src: "update-motd.d/{{ item }}"
state: present
loop: "{{ hostvars[inventory_hostname].vps_service.ssh_motd_script_basenames }}"
- name: Create hidden SSH directories under users' home directories
when: hostvars[inventory_hostname].groups.remote.group_name in item.value.groups
ansible.builtin.file:
group: "{{ item.value.group | default(item.value.username) }}"
mode: "0700"
owner: "{{ item.value.username }}"
path: "{{ item.value.home | default('/home/' ~ item.value.username) }}/.ssh"
state: directory
loop: "{{ lookup('ansible.builtin.dict', hostvars[inventory_hostname].users) }}"
tags:
- ensure_paths
- ensure_files
- name: Add authorized SSH public keys for users
when: hostvars[inventory_hostname].groups.remote.group_name in item.value.groups and item.value.ssh_authorized_keys is not None and len(item.value.ssh_authorized_keys) > 0
ansible.builtin.copy:
backup: true
content: "{{ '\n'.join(item.value.ssh_authorized_keys) }}"
dest: "{{ item.value.home | default('/home/' ~ item.value.username) }}/.ssh/authorized_keys"
# follow: true
force: true
group: "{{ item.value.group | default(item.value.username) }}"
mode: "0600"
owner: "{{ item.value.username }}"
loop: "{{ lookup('ansible.builtin.dict', hostvars[inventory_hostname].users) }}"
tags:
- ensure_files
- name: Harden SSH security
block:
- name: Create public subdirectory for SSH's SFTP-exclusive user's chroot
when: "'sftp' in item.value.services"
ansible.builtin.file:
group: "{{ item.value.group | default(item.value.username) }}"
owner: "{{ item.value.username }}"
path: "{{ item.value.home | default('/home/' ~ item.value.username) }}/public"
state: directory
loop: "{{ lookup('ansible.builtin.dict', hostvars[inventory_hostname].users) }}"
- name: Set users in group ftp to only be usable with SSH's SFTP service
when: "'sftp' in item.value.services"
ansible.builtin.blockinfile:
backup: true
block: |2
Match User {{ item.value.username }}
ForceCommand internal-sftp -d /public
AuthorizedKeysFile {{ item.value.home | default('/home/' ~ item.value.username) }}/.ssh/authorized_keys
Match Group {{ item.value.group | default(item.value.username) }}
ForceCommand internal-sftp -d /%u
ChrootDirectory {{ item.value.home | default('/home/' ~ item.value.username) }}
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
create: true
group: root
insertafter: EOF
marker: "# {mark} ANSIBLE-MANAGED SFTP BLOCK"
marker_begin: BEGIN
marker_end: END
owner: root
path: /etc/ssh/sshd_config.d/sftp.conf
append_newline: true
state: present
validate: /bin/sshd -t
loop: "{{ lookup('ansible.builtin.dict', hostvars[inventory_hostname].users) }}"
tags:
- sftp_auth_step
- name: Switch to preferred SSH authentication method
ansible.builtin.template:
backup: true
comment_end_string: "#}"
comment_start_string: "{#"
dest: /etc/ssh/sshd_config.d/auth.conf
# follow: true
force: true
group: root
owner: root
src: sshd_config.d/auth.conf.j2
validate: /bin/sshd -t
vars:
empty_auth_used: false
pass_auth_used: false
pam_auth_used: true
key_auth_used: true
tags:
- ssh_auth_step
- name: Constrain idle online user accounts
ansible.builtin.template:
backup: true
comment_end_string: "#}"
comment_start_string: "{#"
dest: /etc/ssh/sshd_config.d/harden.conf
force: true
group: root
owner: root
src: sshd_config.d/harden.conf.j2
validate: /bin/sshd -t
vars:
client_subsistence: 900
client_subsist_warn_max: 3
tags:
- ssh_timeout_step
- name: Toggle ability to log in as root via SSH
when: "hostvars[inventory_hostname].vps_service.root_fate == 'disposal'"
ansible.builtin.template:
backup: true
comment_end_string: "#}"
comment_start_string: "{#"
dest: /etc/ssh/sshd_config.d/denyroot.conf
force: true
group: root
owner: root
src: sshd_config.d/denyroot.conf.j2
validate: /bin/sshd -t
vars:
root_login_allowed: false
tags:
- ssh_root_step
- name: Specify users or groups to whitelist or blacklist for SSH login
when: "hostvars[inventory_hostname].vps_service.root_fate == 'disposal'"
ansible.builtin.template:
backup: true
comment_end_string: "#}"
comment_start_string: "{#"
dest: /etc/ssh/sshd_config.d/allowance.conf
force: true
group: root
owner: root
src: sshd_config.d/allowance.conf.j2
validate: /bin/sshd -t
vars:
list_type: whitelist
policed_groups:
- "{{ hostvars[inventory_hostname].groups.remote.group_name }}"
tags:
- ssh_gate_step
tags:
- ssh_harden_step

View File

@@ -1,39 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
# tasks file for bootstrap
- name: Provide requisite SSL signed certificate for FQDN
ansible.builtin.copy:
backup: true
checksum: string
dest: "/usr/local/share/ca-certificates/{{ hostvars[inventory_hostname].fqdn }}.crt"
force: true
group: root
owner: root
src: "ca-certificates/{{ hostvars[inventory_hostname].fqdn }}.crt"
# validate: string
- name: Provide requisite SSL private key for FQDN
ansible.builtin.copy:
backup: true
dest: "/usr/local/share/ca-certificates/{{ hostvars[inventory_hostname].fqdn }}.key"
force: true
group: root
mode: "0600"
owner: root
src: "ca-certificates/{{ hostvars[inventory_hostname].fqdn }}.key"
# validate: string
- name: Provide requisite SSL public key for FQDN
ansible.builtin.copy:
backup: true
checksum: string
dest: "/usr/local/share/ca-certificates/{{ hostvars[inventory_hostname].fqdn }}.pem"
force: true
group: root
owner: root
src: "ca-certificates/{{ hostvars[inventory_hostname].fqdn }}.pem"
# validate: string
- name: Update system registration of SSL certificates
ansible.builtin.command:
cmd: update-ca-certificates
creates: "/etc/ssl/certs/{{ hostvars[inventory_hostname].fqdn }}.pem"

View File

@@ -1,65 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
# tasks file for bootstrap
- name: Create groups
ansible.builtin.group:
name: "{{ item.value.group_name }}"
state: present
system: "{{ item.value.type == 'system' }}"
loop: "{{ lookup('ansible.builtin.dict', hostvars[inventory_hostname].groups) }}"
- name: Create users
block:
- name: Create administrative users
when: "item.value.admin and item.value.type != 'system'"
ansible.builtin.user:
comment: "administrator for {{ fqdn.split('.')[0].lowercase }}"
create_home: false
home: "{{ item.value.home | default('/home/' ~ item.value.username) }}"
generate_ssh_key: true
ssh_key_comment: "ansible-generated for {{ item.value.username }}@{{ hostvars[inventory_hostname].fqdn.split('.')[0].lowercase() }}"
ssh_key_type: "ed25519"
group: "{{ item.value.group | default(item.value.username) }}"
name: "{{ item.value.username }}"
uid: "{{ item.value.id }}"
shell: "{{ item.value.shell }}"
password: "{{ item.value.password }}"
state: present
system: "{{ item.value.type == 'system' }}"
update_password: always
loop: "{{ lookup('ansible.builtin.dict', hostvars[inventory_hostname].users) }}"
- name: Create regular users
when: "not item.value.admin and item.value.type != 'system'"
ansible.builtin.user:
comment: "user of {{ fqdn.split('.')[0].lowercase }}"
create_home: true
home: "{{ item.value.home | default('/home/' ~ item.value.username) }}"
generate_ssh_key: true
group: "{{ item.value.group | default(item.value.username) }}"
name: "{{ item.value.username }}"
uid: "{{ item.value.id }}"
shell: "{{ item.value.shell }}"
password: "{{ item.value.password }}"
state: present
system: "{{ item.value.type == 'system' }}"
update_password: always
loop: "{{ lookup('ansible.builtin.dict', hostvars[inventory_hostname].users) }}"
- name: Create users for managing data related to services
when: "not item.value.admin and item.value.type == 'system' and item.value.service is not None"
ansible.builtin.user:
comment: "service data user for {{ item.value.services | random }} at {{ hostvars[inventory_hostname].fqdn.split('.')[0].lowercase() }}"
create_home: false
home: "{{ item.value.home | default('/home/' ~ item.value.username) }}"
group: "{{ item.value.group | default(item.value.username) }}"
name: "{{ item.value.username }}"
uid: "{{ item.value.id }}"
shell: "{{ item.value.shell }}"
state: present
system: "{{ item.value.type == 'system' }}"
loop: "{{ lookup('ansible.builtin.dict', hostvars[inventory_hostname].users) }}"
- name: Adjust users' groups
when: item.value.groups is not None and len(item.value.groups) > 0
ansible.builtin.user:
name: "{{ item.value.username }}"
append: true
groups: "{{ item.value.groups }}"
loop: "{{ lookup('ansible.builtin.dict', hostvars[inventory_hostname].users) }}"

View File

@@ -1,12 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
# tasks file for bootstrap
- name: Populate system with groups and user accounts
ansible.builtin.import_tasks:
file: "create_users@{{ ansible_facts['system'].lowercase() }}.yml"
- name: Provide SSL certificate files
ansible.builtin.import_tasks:
file: "configure_ssl@{{ ansible_facts['system'].lowercase() }}.yml"
- name: Configure SSH for root
ansible.builtin.import_tasks:
file: "configure_ssh@{{ ansible_facts['system'].lowercase() }}.yml"

View File

@@ -1,87 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
# tasks file for bootstrap
# @TODO create bootstrap tasks for installation and configuration of software
- name: Update and upgrade software
block:
- name: Update Aptitude package cache and upgrade Aptitude packages
when: "ansible_facts['pkg_mgr'] == 'apt'"
become: true
ansible.builtin.apt:
upgrade: yes
update_cache: yes
cache_valid_time: 86400
- name: Install NeoVim editor
become: true
block:
- name: Install NeoVim using Aptitude package manager
when: "ansible_facts['pkg_mgr'] == 'apt'"
ansible.builtin.package:
name: neovim
use: "{{ ansible_facts['pkg_mgr'] }}"
state: present
# @TODO create handler to notify to for configuring neovim
# notify: neovim
- name: Install kitty-terminfo for SSH client xterm-kitty compatibility
become: true
block:
- name: Install kitty-terminfo using Aptitude package manager
when: "ansible_facts['pkg_mgr'] == 'apt'"
ansible.builtin.package:
name: kitty-terminfo
use: "{{ ansible_facts['pkg_mgr'] }}"
state: present
- name: Install necessary software managers and container engines
become: true
block:
- name: Install snapd
when: "ansible_facts['pkg_mgr'] == 'apt'"
block:
- name: Install snapd using Aptitude package manager
ansible.builtin.package:
name: snapd
use: "{{ ansible_facts['pkg_mgr'] }}"
state: present
notify: snapd
- name: Install flatpak
when: "ansible_facts['pkg_mgr'] == 'apt'"
block:
- name: Install flatpak using Aptitude package manager
ansible.builtin.package:
name: flatpak
use: "{{ ansible_facts['pkg_mgr'] }}"
state: present
- name: Install podman
when: "ansible_facts['pkg_mgr'] == 'apt'"
block:
- name: Install podman using Aptitude package manager
ansible.builtin.package:
name: podman
use: "{{ ansible_facts['pkg_mgr'] }}"
state: present
- name: Install podman-compose
when: "ansible_facts['pkg_mgr'] == 'apt'"
block:
- name: Install podman-compose using Aptitude package manager
ansible.builtin.package:
name: podman-compose
use: "{{ ansible_facts['pkg_mgr'] }}"
state: present
- name: Install git
block:
- name: Install git using Aptitude package manager
when: "ansible_facts['pkg_mgr'] == 'apt'"
ansible.builtin.package:
name: git
use: "{{ ansible_facts['pkg_mgr'] }}"
state: present
notify: git
- name: Install packages
when: ansible_facts['pkg_mgr'] in item.value.name
ansible.builtin.package:
name: "{{ item.value.name[ansible_facts['pkg_mgr']] }}"
use: "{{ ansible_facts['pkg_mgr'] }}"
state: present
# @TODO research what happens when nonexistent handler is called or notify field is null
notify: "{{ item.key }}"
loop: "{{ lookup('ansible.builtin.dict', software.pkgs) }}"

View File

@@ -1,9 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
# tasks file for bootstrap
- name: Configure GPG for user
ansible.builtin.import_tasks:
file: "configure_gpg@{{ ansible_facts['system'].lowercase() }}.yml"
- name: Install and configure software on system
ansible.builtin.import_tasks:
file: "install@{{ ansible_facts['system'].lowercase() }}.yml"

View File

@@ -1,83 +0,0 @@
# Global settings
continue=true
# check-integrity=true
daemon=true
human-readable=true
dir=~/downloads
file-allocation=falloc
log-level=warn
max-concurrent-downloads=3
max-overall-download-limit=0
# RPC settings
enable-rpc=true
rpc-allow-origin-all=true
rpc-max-request-size=10M
rpc-listen-all=true
rpc-listen-port=6800
rpc-secret={{ config['aria']['api_key'] }}
# rpc-certificate=
# rpc-private-key=
# rpc-secure=true
# HTTP/FTP/SFTP settings
connect-timeout=120
timeout=90
server-stat-of=~/.config/aria2/dl.log
server-stat-if=~/.config/aria2/dl.log
server-stat-timeout=86400
# checksum=sha-256={{ config.aria.checksum }}
max-connection-per-server=5
max-tries=10
max-file-not-found=7
min-split-size=100M
split=7
retry-wait=10
netrc-path=~/.netrc
reuse-uri=true
uri-selector=feedback
seed-ratio=1.5
seed-time=75
# HTTP settings
http-accept-gzip=true
http-auth-challenge=true
http-no-cache=true
enable-http-pipelining=true
enable-http-keep-alive=true
save-cookies=~/.config/aria2/cookie.txt
load-cookies=~/.config/aria2/cookie.txt
# user-agent=Mozilla/5.0
# FTP/SFTP settings
ftp-pasv=true
ftp-type=binary
ftp-reuse-connection=true
# ssh-host-key-md=sha-256=
# Bittorrent settings
listen-port=6881-6999
# bt-hash-check-seed=true
# bt-force-encryption=true
bt-save-metadata=true
bt-load-saved-metadata=true
bt-max-open-files=50
bt-max-peers=150
bt-stop-timeout=7200
bt-tracker=udp://93.158.213.92:1337/announce,udp://23.134.88.9:6969/announce,udp://23.134.88.9:1337/announce,udp://185.243.218.213:80/announce,udp://89.234.156.205:451/announce,udp://44.30.4.4:6969/announce,udp://23.175.184.30:23333/announce,udp://51.222.82.36:6969/announce,udp://211.75.205.189:80/announce,udp://77.91.85.95:6969/announce,udp://45.13.119.213:6969/announce,udp://43.154.112.29:17272/announce,udp://209.141.59.25:6969/announce,udp://5.255.124.190:6969/announce,udp://152.53.152.105:1984/announce,udp://109.201.134.183:80/announce,udp://111.90.151.241:6969/announce,udp://152.53.152.105:54123/announce,udp://189.69.171.209:6969/announce,udp://151.243.109.110:6969/announce
bt-tracker-connect-timeout=120
bt-tracker-timeout=333
bt-tracker-interval=0
enable-dht=true
dht-listen-port=6881-6999
dht-message-timeout=15
enable-peer-exchange=true
follow-torrent=mem
# Metalink settings
follow-metalink=mem
metalink-language=en,es,ja
metalink-location=jp,us,ch
# metalink-os=linux

View File

@@ -1,31 +0,0 @@
<Global>
# PassivePorts {{ pasv_ports }}
RequireValidShell off
{% if allow_symlinks %}
ShowSymlinks on
{% else %}
ShowSymlinks off
{% endif %}
AllowRetrieveRestart on
HiddenStores .%P- .frag
DisplayLogin /etc/proftpd/WELCOME.txt
DisplayChdir .README.md true
DisplayConnect /etc/proftpd/BANNER.txt
DisplayFileTransfer /etc/proftpd/SUCCESS.txt
DisplayReadme /etc/proftpd/ANNOUNCE.md
DisplayQuit /etc/proftpd/BYE.txt
TimeoutNoTransfer 3600
TimeoutStalled 210
TimeoutIdle 1400
Umask 0022 0022
AllowOverwrite on
<Directory />
<Limit ALL>
DenyAll
</Limit>
</Directory>
</Global>

View File

@@ -1,93 +0,0 @@
<IfModule !mod_tls.c>
LoadModule mod_tls.c
</IfModule>
<IfModule mod_tls.c>
<VirtualHost 0.0.0.0>
ServerName "{{ ftp_server_name }}"
ServerIdent on "Our head librarians Furcas and Marbas welcome you!"
ServerAlias {{ hostvars[inventory_hostname].fqdn }} ftp.{{ hostvars[inventory_hostname].fqdn }} {{ hostvars[inventory_hostname].fqdn.split('.')[0] }}
ServerLog /var/log/proftpd/{{ hostvars[inventory_hostname].fqdn }}.log
Protocols ftps
Port 990
DefaultRoot ~
# AllowStoreRestart on
MaxStoreFileSize 10 Gb
MaxTransfersPerUser STOR,RETR 9
MaxTransfersPerHost STOR,RETR 36
DirFakeUser on ~
DirFakeGroup on ~
# AuthOrder mod_auth_pam.c mod_auth_unix.c*
AuthOrder mod_auth_file.c
AuthUserFile {{ config.proftpd.auth_paths.users }}
AuthGroupFile {{ config.proftpd.auth_paths.groups }}
AuthFileOptions SyntaxCheck
TLSEngine on
TLSLog /var/log/proftpd/tls.log
# @NOTE: "SSLv23" means all SSL versions
TLSProtocol SSLv23
TLSOptions AllowClientRenegotiations
TLSVerifyClient off
TLSRequired on
TLSRenegotiate required off
TLSECCertificateFile {{ config.proftpd.tls_paths.cert }}
TLSECCertificateKeyFile {{ config.proftpd.tls_paths.privkey }}
TLSCACertificateFile {{ config.proftpd.tls_paths.cert }}
<Limit LOGIN>
AllowUser OR {{ allowed_users}}
</Limit>
<Directory ~>
<Limit READ DIRS>
AllowAll
</Limit>
</Directory>
<Directory ~/*>
UserOwner ftp
GroupOwner ftp
HideUser !~
HideFiles ^\.(.+)?
HideNoAccess on
<Limit ALL>
AllowAll
</Limit>
</Directory>
<Anonymous {{ anon_root }}>
User ftp
Group ftp
RequireValidShell off
DirFakeUser on anon
DirFakeGroup on anon
DirFakeMode 0444
UserAlias anon {{ anon_user }}
AllowStoreRestart off
MaxStoreFileSize 4 Gb
MaxTransfersPerUser STOR,RETR 3
MaxTransfersPerHost STOR,RETR 10
HideUser !~
HideNoAccess on
<Directory {{ anon_root }}>
<Limit READ DIRS>
AllowAll
</Limit>
</Directory>
<Directory {{ anon_root }}/*>
# <Limit READ DIRS MKD RMD XMKD XRMD>
<Limit READ DIRS>
AllowAll
</Limit>
HideFiles ^\.(.+)?
</Directory>
</Anonymous>
</VirtualHost>
</IfModule>

View File

@@ -1,185 +0,0 @@
#
# /etc/proftpd/proftpd.conf -- This is a basic ProFTPD configuration file.
# To really apply changes, reload proftpd after modifications, if
# it runs in daemon mode. It is not required in inetd/xinetd mode.
#
# Includes DSO modules
Include /etc/proftpd/modules.conf
# Set off to disable IPv6 support which is annoying on IPv4 only boxes.
UseIPv6 on
# If set on you can experience a longer connection delay in many cases.
<IfModule mod_ident.c>
IdentLookups on
</IfModule>
ServerName "{{ ftp_server_name }}"
# Set to inetd only if you would run proftpd by inetd/xinetd/socket.
# Read README.Debian for more information on proper configuration.
ServerType standalone
DeferWelcome off
MaxInstances {{ max_conns }}
# Disable MultilineRFC2228 per https://github.com/proftpd/proftpd/issues/1085
# MultilineRFC2228on
DefaultServer on
DefaultRoot ~
DenyFilter \*.*/
# Users require a valid shell listed in /etc/shells to login.
# Use this directive to release that constrain.
# RequireValidShell off
# Port 21 is the standard FTP port.
Port 21
# If your host was NATted, this option is useful in order to
# allow passive tranfers to work. You have to use your public
# address and opening the passive ports used on your firewall as well.
# MasqueradeAddress 1.2.3.4
# This is useful for masquerading address with dynamic IPs:
# refresh any configured MasqueradeAddress directives every 8 hours
# <IfModule mod_dynmasq.c>
# DynMasqRefresh 28800
# </IfModule>
# Set the user and group that the server normally runs at.
User proftpd
Group nogroup
# Uncomment this if you are using NIS or LDAP via NSS to retrieve passwords:
# PersistentPasswd off
# This is required to use both PAM-based authentication and local passwords
# AuthOrder mod_auth_pam.c* mod_auth_unix.c
# Be warned: use of this directive impacts CPU average load!
# Uncomment this if you like to see progress and transfer rate with ftpwho
# in downloads. That is not needed for uploads rates.
#
# UseSendFile off
TransferLog /var/log/proftpd/transfer.log
SystemLog /var/log/proftpd/connection.log
# Logging onto /var/log/lastlog is enabled but set to off by default
#UseLastlog on
# In order to keep log file dates consistent after chroot, use timezone info
# from /etc/localtime. If this is not set, and proftpd is configured to
# chroot (e.g. DefaultRoot or <Anonymous>), it will use the non-daylight
# savings timezone regardless of whether DST is in effect.
#SetEnv TZ :/etc/localtime
<IfModule mod_quotatab.c>
QuotaEngine off
</IfModule>
<IfModule mod_ratio.c>
Ratios off
</IfModule>
# Delay engine reduces impact of the so-called Timing Attack described in
# http://www.securityfocus.com/bid/11430/discuss
# It is on by default.
<IfModule mod_delay.c>
DelayEngine on
</IfModule>
<IfModule mod_ctrls.c>
ControlsEngine off
ControlsMaxClients 2
ControlsLog /var/log/proftpd/controls.log
ControlsInterval 5
ControlsSocket /var/run/proftpd/proftpd.sock
</IfModule>
<IfModule mod_ctrls_admin.c>
AdminControlsEngine off
</IfModule>
#
# Alternative authentication frameworks
#
#Include /etc/proftpd/ldap.conf
#Include /etc/proftpd/sql.conf
#
# This is used for FTPS connections
#
#Include /etc/proftpd/tls.conf
#
# This is used for SFTP connections
#
#Include /etc/proftpd/sftp.conf
#
# This is used for other add-on modules
#
#Include /etc/proftpd/dnsbl.conf
#Include /etc/proftpd/geoip.conf
#Include /etc/proftpd/snmp.conf
#
# Useful to keep VirtualHost/VirtualRoot directives separated
#
#Include /etc/proftpd/virtuals.conf
# A basic anonymous configuration, no upload directories.
# <Anonymous ~ftp>
# User ftp
# Group nogroup
# # We want clients to be able to login with "anonymous" as well as "ftp"
# UserAlias anonymous ftp
# # Cosmetic changes, all files belongs to ftp user
# DirFakeUser on ftp
# DirFakeGroup on ftp
#
# RequireValidShell off
#
# # Limit the maximum number of anonymous logins
# MaxClients 10
#
# # We want 'welcome.msg' displayed at login, and '.message' displayed
# # in each newly chdired directory.
# DisplayLogin welcome.msg
# DisplayChdir .message
#
# # Limit WRITE everywhere in the anonymous chroot
# <Directory *>
# <Limit WRITE>
# DenyAll
# </Limit>
# </Directory>
#
# # Uncomment this if you're brave.
# # <Directory incoming>
# # # Umask 022 is a good standard umask to prevent new files and dirs
# # # (second parm) from being group and world writable.
# # Umask 022 022
# # <Limit READ WRITE>
# # DenyAll
# # </Limit>
# # <Limit STOR>
# # AllowAll
# # </Limit>
# # </Directory>
#
# </Anonymous>
<Limit LOGIN>
DenyAll
</Limit>
# Include other custom configuration files
# !! Please note, that this statement will read /all/ file from this subdir,
# i.e. backup files created by your editor, too !!!
# Eventually create file patterns like this: /etc/proftpd/conf.d/*.conf
#
Include /etc/proftpd/conf.d/

View File

@@ -1,41 +0,0 @@
port = 873
use chroot = true
max connections = 17
ignore nonreadable = true
pid file = /var/run/rsyncd.pid
[{{ ansible_facts['user_id'] }}-dl]
path = {{ ansible_facts['user_dir'] }}/downloads/public
uid = rika
gid = rika
timeout = 90
comment = Personal download inventory
read only = true
exclude = .nextcloudsync.log .calnotes .caltrash .stfolder .stignore .directory .ssh *.pub
[{{ ansible_facts['user_id'] }}-public]
path = {{ ansible_facts['user_dir'] }}/public/rsync
uid = rika
gid = rika
timeout = 90
comment = Public share point
read only = true
exclude = .nextcloudsync.log .calnotes .caltrash .stfolder .stignore .directory .ssh *.pub
[{{ ansible_facts['user_id'] }}-soulseek]
path = {{ ansible_facts['user_dir'] }}/public/soulseek
uid = rika
gid = rika
timeout = 90
comment = Personal SoulSeek inventory
read only = true
exclude = .nextcloudsync.log .calnotes .caltrash .stfolder .stignore .directory .ssh *.pub
[{{ ansible_facts['user_id'] }}-portfolio]
path = {{ ansible_facts['user_dir'] }}/portfolio
uid = rika
gid = rika
timeout = 90
comment = Personal portfolio
read only = true
exclude = .nextcloudsync.log .calnotes .caltrash .stfolder .stignore .directory .ssh *.pub

View File

@@ -1,15 +0,0 @@
{% if list_type == 'whitelist' %}
{% if policed_groups is not None and len(policed_groups) > 0 %}
AllowGroups {{ ' '.join(policed_groups) }}
{% endif %}
{% if policed_users is not None and len(policed_users) > 0 %}
AllowUsers {{ ' '.join(policed_users) }}
{% endif %}
{% else %}
{% if policed_groups is not None and len(policed_groups) > 0 %}
DenyGroups {{ ' '.join(policed_groups) }}
{% endif %}
{% if policed_users is not None and len(policed_users) > 0 %}
DenyGroups {{ ' '.join(policed_users) }}
{% endif %}
{% endif %}

View File

@@ -1,28 +0,0 @@
{% if empty_auth_used %}
PermitEmptyPasswords yes
{% else %}
PermitEmptyPasswords no
{% endif %}
{% if pass_auth_used %}
PasswordAuthentication yes
{% else %}
PasswordAuthentication no
{% endif %}
{% if kbd_auth_used is not None %}
{% if kbd_auth_used %}
KbdInteractiveAuthentication yes
{% else %}
KbdInteractiveAuthentication no # enable if implementing TOTP 2FA
{% endif %}
{% endif %}
{% if pam_auth_used %}
UsePAM yes
{% else %}
UsePAM no # enable if implementing TOTP 2FA
{% endif %}
{% if key_auth_used %}
PubkeyAuthentication yes
{% else %}
PubkeyAuthentication no
{% endif %}
PrintMotd yes

View File

@@ -1,5 +0,0 @@
{% if root_login_allowed %}
PermitRootLogin yes
{% else %}
PermitRootLogin no
{% endif %}

View File

@@ -1,2 +0,0 @@
ClientAliveInterval {{ client_subsistence }}
ClientAliveCountMax {{ client_subsist_warn_max }}

View File

@@ -1,13 +0,0 @@
[Unit]
Description=aria2 Daemon
After=network.target
[Service]
Type=forking
ExecStart=/usr/bin/aria2c --conf-path={{ ansible_facts['user_dir'] }}/.config/aria2/aria2.conf
ExecReload=/usr/bin/kill -HUP $MAINPID
RestartSec=1min
Restart=on-failure
[Install]
WantedBy=default.target

View File

@@ -1,3 +0,0 @@
#SPDX-License-Identifier: MIT-0
localhost

View File

@@ -1,6 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
- hosts: localhost
remote_user: root
roles:
- bootstrap

View File

@@ -1,297 +0,0 @@
#SPDX-License-Identifier: MIT-0
---
# vars file for bootstrap
# @TODO make list or dictionary of software to be installed in bootstrap task
software:
pkgs:
# @NOTE keep fields or keys constant; otherwise will have to edit handler notifiers and listeners elsewhere
failtwoban:
name:
apt: fail2ban
gocryptfs:
name:
apt: gocryptfs
lua-lang:
name:
apt: lua5.4
lua-docs:
name:
apt: luadoc
lua-pkg:
name:
apt: luarocks
python-lang:
name:
apt: python3
python-pkg:
name:
apt: python3-pip
python-linter:
name:
apt: python3-doc8
python-docs:
name:
apt: python3-doc
rust-lang:
name:
apt: rustc # @NOTE alternative: rustup
rust-pkg:
name:
apt: cargo
rust-debugger:
name:
apt: rust-analyzer
rust-linter:
name:
apt: rust-clippy
rust-docs:
name:
apt: rust-doc
java-lang:
name:
apt: default-jdk-headless
java-docs:
name:
apt: default-jdk-doc
java-runtime:
name:
apt: default-jre-headless
kotlin-lang:
name:
apt: kotlin
swift-lang:
name:
apt: swiftlang
swift-docs:
name:
apt: swiftlang-doc
erlang-lang:
name:
apt: erlang
erlang-pkg:
name:
apt: erlang-hex
erlang-docs:
name:
apt: erlang-doc
elixir-lang:
name:
apt: elixir
crystal-lang:
name:
apt: crystal
crystal-docs:
name:
apt: crystal-doc
# @TODO replace below commented with an NVM-style installation (v22): https://nodejs.org/en/download
# javascript-lang:
# name:
# apt: nodejs
# javascript-pkg:
# name:
# apt: npm
# javascript-linter:
# name:
# apt: eslint
javascript-docs:
name:
apt: nodejs-doc
php-lang:
name:
apt: php
php-docs:
name:
apt: php-common
php-debugger:
name:
apt: php-xdebug
php-pkg:
name:
apt: composer
# php-ldap:
# name:
# apt: php-ldap
html-linter:
name:
apt: tidy
json-linter:
name:
apt: jsonlint
yaml-linter:
name:
apt: yamllint
pandoc:
name:
apt: pandoc
distrobox:
name:
apt: distrobox
fastfetch:
name:
apt: fastfetch
# @TODO manually install the commented below on current active new VPS, then uncomment
# duplicity:
# name:
# apt: duplicity
# pass:
# name:
# apt: pass
# sonicpi:
# name:
# apt: sonic-pi-server
# sonicpi-docs:
# name:
# apt: sonic-pi-server-doc
# supercollider:
# name:
# apt: supercollider
# supercollider-docs:
# name:
# apt: supercollider-common
# supercollider-plugins:
# name:
# apt: sc3-plugins-language
qrencode:
name:
apt: qrencode
ffmpeg:
name:
apt: ffmpeg
ffmpeg-docs:
name:
apt: ffmpeg-doc
graphicsmagick:
name:
apt: graphicsmagick
graphicsmagick-compatibility:
name:
apt: graphicsmagick-imagemagick-compat
timg:
name:
apt: timg
tmux:
name:
apt: tmux
# @TODO add glow apt repository in install@linux bootstrap role play before uncommenting the below
# glow:
# name:
# apt: glow
# @TODO add ZFS apt repository in install@linux bootstrap role play before uncommenting the below
# zfs:
# name:
# apt: zfsutils-linux
# @TODO manually install the commented below on current active new VPS, then uncomment
# dpkg-dev:
# name:
# apt: dpkg-dev
# ldap-utils:
# name:
# apt: ldap-utils
# slapd:
# name:
# apt: slapd
proftpd-mod-crypto:
name:
apt: proftpd-mod-crypto
# @TODO write configuration files and handler for below two package installations
# based on:
clamav:
name:
apt: clamav
clamd:
name:
apt: clamav-daemon
proftpd:
name:
apt: proftpd
proftpd-docs:
name:
apt: proftpd-doc
rsync:
name:
apt: rsync
# rclone:
# name:
# apt: rclone
aria:
name:
apt: aria2
# mopidy:
# name:
# apt: mopidy
# mopidy-mpd:
# name:
# apt: mopidy-mpd
# caddy:
# name:
# apt: caddy
snaps:
nextcloud:
name: nextcloud
channel: ~
opts:
- "nextcloud:php.memory-limit=512M"
- "nextcloud:nextcloud.cron-interval=10m"
- "nextcloud:http.compression=true"
- "nextcloud:ports.http=81"
# @TODO see how to set these options: https://help.nextcloud.com/t/how-to-configure-nextcloud-snap/216036#p-649442-trusted-domains-configuration-8
# @TODO see how to set these options: https://help.nextcloud.com/t/how-to-configure-nextcloud-snap/216036#p-649442-trusted-proxy-configuration-9
links:
quartz:
name: quartz
src: https://github.com/jackyzha0/quartz.git
branch: v4
version: ~
output: ~
config:
git:
sys:
editor: nvim
proftpd:
name: "{{ hostvars[inventory_hostname].fqdn.split('.')[0] }}"
auth_paths:
users: /etc/proftpd/ftpd.passwd
groups: /etc/proftpd/ftpd.group
msg:
welcome: "Our head librarians Furcas and Marbas welcome you!"
users:
webmaster:
username: webmaster
id: "{{ ['caddy', 'www-data'][0] }}"
gid: "{{ ['caddy', 'www-data'][0] }}"
# @TODO create vaulted password for this ProFTPd virtual user
password: !vault |
$ANSIBLE_VAULT;1.2;AES256;vps1-webmaster
63633938633139636663623166343836643839306538373762393834393230336334383334303163
3465323831366163386265353664313932383664373838660a363463303364373963353638396462
65356135623030653533333766623865643065303739386538636662303537376466333039613363
3932313334643163650a303336623031613964356433363536373236303266663735343939383930
3636
services: [http,https]
smuggler:
username: smuggler
id: "{{ hostvars[inventory_hostname].users.ftp.username }}"
gid: "{{ hostvars[inventory_hostname].users.ftp.group | default(hostvars[inventory_hostname].users.ftp.username) }}"
# @TODO create vaulted password for this ProFTPd virtual user
password: !vault |
$ANSIBLE_VAULT;1.2;AES256;vps1-smuggler
38396565313866383761303137343431613830643436666431316434393362623035623031656263
6537313630393433336133643166363564383163616232320a623034636664353864613862353366
38303663363665663366336131663431383936306131616262376162653837326163393561323465
3734333031323330300a353562353035323731303732323534613938353935393433646235356137
62336333666362383665623466353337303134623966663061366235303261653333
services: []
tls_paths:
cert: "/usr/local/share/ca-certificates/{{ hostvars[inventory_hostname].fqdn }}.crt"
privkey: "/usr/local/share/ca-certificates/{{ hostvars[inventory_hostname].fqdn }}.key"
nextcloud:
users:
admin:
username: admin
# @TODO change this password to ansible-vaulted actual choice password later
password: password123 # @NOTE placeholder
phone_region: US
aria:
checksum: ~
api_key: ~

View File

@@ -1,157 +0,0 @@
from typing import Self, Never, Callable, Sequence
from custtypes import Roles, Scopes, PathCollection, PathRoles
from custtypes import Software, SoftwareRoles, ExecutedPath
from custtypes import PacMans, UserName, GroupName, IdlePath
from custtypes import ExecutedPath, AnsibleRoles
from sshkey import SSHKeyCollection, SSHKeyType, SSHKey
from whereami import PROJ_ROLES
class App:
def __init__(self, name: Software, role: SoftwareRoles = SoftwareRoles.client, paths: PathRoles | None = None):
self.__name = name.name.lower().replace("_", "-")
# @TODO create dict type hint for below data struct
self.alt_names = dict()
self.alt_names[PacMans.APT.name.lower()] = self.__name
self.role = role.name.lower()
if paths is not None:
if Roles.EXE in paths:
setattr(self, "_" + Roles.EXE.name.lower(), paths[Roles.EXE.name.lower()])
if Roles.CONF in paths:
setattr(self, "_" + Roles.CONF.name.lower(), paths[Roles.CONF.name.lower()])
if Roles.DATA in paths:
setattr(self, "_" + Roles.DATA.name.lower(), paths[Roles.DATA.name.lower()])
if Roles.MEM in paths:
setattr(self, "_" + Roles.MEM.name.lower(), paths[Roles.MEM.name.lower()])
self.__parents: tuple[Self] | None = None
self.__children: tuple[Self| None] = []
self.__api: str | None = None
self.__current_filepath: IdlePath | ExecutedPath | None = None
self.__content: str | None = None
@property
def conf_paths(self):
if hasattr(self, "_" + Roles.CONF.name.lower()):
return self._conf
else:
raise Exception
@property
def data_paths(self):
if hasattr(self, "_" + Roles.DATA.name.lower()):
return self._data
else:
raise Exception
@property
def exec_paths(self):
if hasattr(self, "_" + Roles.EXE.name.lower()):
return self._exe
else:
raise Exception
@property
def mem_paths(self):
if hasattr(self, "_" + Roles.MEM.name.lower()):
return self._mem
else:
raise Exception
def get_paths(self, role: Roles = Roles.CONF):
if hasattr(self, "_" + role.name.lower()):
return getattr(self, "_" + role.name.lower())
else:
raise Exception
def append(self, datatype: Roles = Roles.CONF, scope: Scopes | None = None, path: IdlePath | ExecutedPath | str | PathCollection | None = None):
if path is None:
raise TypeError
datatype = datatype.name.lower()
if hasattr(self, "_" + datatype):
paths = getattr(self, "_" + datatype)
else:
setattr(self, "_" + datatype, dict())
paths = getattr(self, "_" + datatype)
if scope is not None:
if isinstance(path, str):
path: ExecutedPath = Path(path)
if scope.name.lower() not in paths:
paths[scope.name.lower()] = []
paths[scope.name.lower()].append(path)
else:
paths: PathCollection = path
setattr(self, "_" + datatype, paths)
def inherit(self, other):
if other._App__children is None:
other._App__children = tuple()
if self not in other._App__children:
other.adopt(self)
self.__parents = (*self.__parents, other)
def adopt(self, other: Self):
if other._App__parents is None:
other._App__parents = tuple()
if self not in other._App__parent:
other.inherit(self)
self.__children = (*self.__children, other)
def __enter__(self) -> dict | Sequence:
self.__content = self.__current_filepath.read_text()
return self.__content
def __exit__(self, exc_type, exc_value, exc_traceback) -> None:
# txt = yams.dump(self.__content)
# self.__file.write(txt)
# del txt
self.__file.close()
def __call__(self, path = str, mode = "r+", scope: Scopes = Scopes.PROJ, role: Roles = Roles.CONF, index: int = 0) -> Callable:
if not hasattr(self, "_" + role.name.lower()):
raise Exception
else:
config = getattr(self, "_" + role.name.lower())
conf_coll = config[scope.name.lower()]
if isinstance(conf_coll, Sequence):
conf_coll = conf_coll[index]
if isinstance(conf_coll, str):
conf_coll = Path(conf_coll)
filepath = conf_coll / path
self.__current_filepath = filepath
self.__file = open(str(filepath), mode)
return self
# @TODO write below method to duplicate file or template in local to project role file/template
def clone(self, source_scope: Scopes = Scopes.SYS, target_scope: Scopes = Scopes.PROJ, index: int = 0) -> Never:
raise NotImplementedError
def declare(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
sshd_proj_files = map(lambda r: r / AnsibleRoles.bootstrap.name.lower() / "files" / "sshd_config.d", PROJ_ROLES)
sshd_proj_files = list(filter(lambda p: p.exists(), sshd_proj_files))
sshd_proj_templates = map(lambda r: r / AnsibleRoles.bootstrap.name.lower() / "templates" / "sshd_config.d", PROJ_ROLES)
sshd_proj_templates = list(filter(lambda p: p.exists(), sshd_proj_templates))
# @TODO rewrite below using DIR_ROOTS var from whereami module
sshd_paths: PathRoles = {
Roles.CONF.name.lower(): {
Scopes.PROJ.name.lower(): sshd_proj_files + sshd_proj_templates
}
}
sshd = App(Software.openssh_server, SoftwareRoles.server, sshd_paths)

660
sshkey.py
View File

@@ -1,660 +0,0 @@
from re import Pattern as RegEx
from re import fullmatch as Match
from pathlib import Path, PurePath
from custtypes import ExecutedPath, IdlePath
from enum import StrEnum, auto
from random import choice as gamble
# from collections.abc import Sequence, Iterable
from typing import Never, Self, Callable, Iterable, Sequence
from whereami import USER_PATH
from itertools import chain
# import os
class SSHKeyType(StrEnum):
pubkey = auto()
privkey = auto()
dual = auto()
# @TODO create unit tests for below class
class SSHKey:
def __init__(self, *path: ExecutedPath | str):
if len(path) > 2 or len(path) < 1:
raise ValueError
path = tuple(map(lambda s: Path(s) if isinstance(s, str) else s, path))
self.__idx: int = 0
self.__prev: Self | None = None
self.__next: Self | None = None
self.category: SSHKeyType | None = None
if len(path) < 2:
self.__value: ExecutedPath | tuple[ExecutedPath] = path[0]
else:
self.category = SSHKeyType.dual.name.lower()
self.__value: ExecutedPath | tuple[ExecutedPath] = path
def __int__(self) -> int:
return self.__idx
def update_status(self) -> None:
if isinstance(self.__value, tuple):
privkey_present = False
pubkey_present = False
for p in self.__value:
if "-----BEGIN OPENSSH PRIVATE KEY-----" in p.read_text():
privkey_present = True
else:
pubkey_present = True
if pubkey_present and privkey_present:
self.category = SSHKeyType.dual.name.lower()
elif pubkey_present or privkey_present:
if pubkey_present:
self.category = SSHKeyType.pubkey.name.lower()
if privkey_present:
self.category = SSHKeyType.privkey.name.lower()
elif isinstance(self.__value, ExecutedPath):
if "-----BEGIN OPENSSH PRIVATE KEY-----" in self.__value.read_text():
self.category = SSHKeyType.privkey.name.lower()
else:
self.category = SSHKeyType.pubkey.name.lower()
def __str__(self) -> str:
if isinstance(self.__value, tuple):
key_basename = Path(str(self.__value[0])).stem + "." + self.category
else:
key_basename = Path(str(self.__value)).name
return "🔑" + key_basename
def __repr__(self) -> str:
return "%s(%r)" % (self.__class__.__name__, self.__value)
def __nonzero__(self) -> bool:
return True
def __format__(self, formatstr) -> str:
match formatstr:
case "item":
return str(self.__idx) + ": " + str(self.__value)
case "int":
return str(self.__idx)
case _:
return str(self)
def __next__(self) -> ExecutedPath | tuple[ExecutedPath]:
return self.__next
def __prev__(self) -> ExecutedPath | tuple[ExecutedPath]:
return self.__prev
def __call__(self, *path: ExecutedPath | str | None) -> ExecutedPath | tuple[ExecutedPath]:
if path is not None or len(path) > 0:
if len(path) > 2:
raise ValueError
path = tuple(map(lambda s: Path(s) if isinstance(s, str) else s, path))
if len(path) < 2:
self.__value = path[0]
else:
self.__value = path
return self.__value
def __eq__(self, other: Self) -> bool:
return self.__value == other._SSHKey__value
def __ne__(self, other: Self) -> bool | Never:
return self.__value != other._SSHKey__value
def __eqcontent__(self, other: Self) -> bool:
return self.__value.read_text() == other._SSHKey__value.read_text()
def __neqcontent__(self, other: Self) -> bool:
return self.__value.read_text() != other._SSHKey__value.read_text()
def __len__(self):
if isinstance(self.__value, tuple):
return len(self.__value)
else:
return 1
def update(self, *path: ExecutedPath | str) -> Self | Never:
if len(path) > 2 or len(path) < 1:
raise ValueError
path = tuple(map(lambda s: Path(s) if isinstance(s, str) else s, path))
if len(path) < 2:
self.__value = path[0]
else:
self.__value = path
return self
def __add__(self, other: Self | ExecutedPath | str) -> Self:
if isinstance(other, (str, ExecutedPath)):
if isinstance(self.__value, tuple):
self.update(*self.__value, other)
else:
self.update(*self.__value, other)
else:
if isinstance(other._SSHKey__value, tuple):
if isinstance(self.__value, tuple):
self.update(*self.__value, *other._SSHKey__value)
else:
self.update(self.__value, *other._SSHKey__value)
else:
if isinstance(self.__value, tuple):
self.update(*self.__value, other._SSHKey__value)
else:
self.update(self.__value, other._SSHKey__value)
self.update_status()
return self
def __radd__(self, other: Self | ExecutedPath | str) -> Self:
if isinstance(self.__value, tuple):
if isinstance(other, (ExecutedPath, str)):
other.update(other, *self.__value)
else:
if isinstance(other._SSHKey__value, tuple):
other.update(*other._SSHKey__value, *self.__value)
else:
other.update(other._SSHKey__value, *self.__value)
else:
if isinstance(other, (ExecutedPath, str)):
other.update(other, self.__value)
else:
if isinstance(other._SSHKey__value, tuple):
other.update(*other._SSHKey__value, self.__value)
else:
other.update(other._SSHKey__value, self.__value)
other.update_status()
return self
# @TODO write following 2 subtraction algorithms using 'set' data type conversion and methods
def __sub__(self, other: Self | ExecutedPath | str) -> Never:
raise NotImplementedError
def __rsub__(self, other: Self | ExecutedPath | str) -> Never:
raise NotImplementedError
def __getitem__(self, key: int) -> ExecutedPath | str | Never:
if isinstance(self.__value, tuple):
return self.__value[key]
else:
raise KeyError
def __setitem__(self, key: int, value: ExecutedPath | str) -> None:
if isinstance(self.__value, tuple):
new_entry = list(self.__value)
if isinstance(value, str):
value = Path(value)
new_entry[key] = value
self.__value = tuple(new_entry)
else:
raise KeyError
def replace(self, old: ExecutedPath | str | tuple[ExecutedPath | str] | list[ExecutedPath | str], new: ExecutedPath | str | tuple[ExecutedPath | str] | list[ExecutedPath | str]) -> Self | Never:
if isinstance(old, str):
old = Path(old)
if isinstance(new, str):
new = Path(new)
if isinstance(old, (list, tuple)):
if len(old) > 2 or len(old) < 1:
raise ValueError
old = tuple(map(lambda p: Path(p) if isinstance(p, str) else p, old))
if isinstance(new, (list, tuple)):
if len(new) > 2 or len(new) < 1:
raise ValueError
new = tuple(map(lambda p: Path(p) if isinstance(p, str) else p, new))
if isinstance(self.__value, (tuple, list)):
if isinstance(old, tuple):
remaining_value = list(filter(lambda p: p not in old, self.__value))
if isinstance(new, tuple):
self.__value = (*remaining_value, *new)
else:
self.__value = (*remaining_value, new)
else:
remaining_value = list(filter(lambda p: p != old, self.__value))
if isinstance(new, tuple):
self.__value = (*remaining_value, *new)
else:
self.__value = (*remaining_value, new)
if len(self.__value) > 2:
self.__value = self.__value[0]
elif isinstance(self.__value, ExecutedPath):
if isinstance(old, tuple):
remaining_value = None if self.__value in old else self.__value
else:
remaining_value = None if self.__value == old else self.__value
if remaining_value is None:
self.__value = new
else:
raise ValueError
return self
def read(self, idx: int | None = None) -> str | tuple[str]:
if idx is not None and isinstance(self.__value, tuple):
result = self.__value[idx]
else:
if idx is not None:
raise KeyError
result = self.__value
if isinstance(result, tuple):
result = tuple(map(lambda p: p.read_text(), result))
else:
result = result.read_text()
return result
@property
def status(self) -> str:
self.update_status()
return self.category
def reverse(self) -> Never:
if isinstance(self.__value, tuple):
v1 = self.__value[0]
v2 = self.__value[1]
result = self.update(v2, v1)
else:
result = self
return result
def prev(arg):
if isinstance(arg, SSHKey):
return arg._SSHKey__prev__()
else:
raise TypeError
def stream_equal(s1, s2) -> bool | Never:
if isinstance(s1, SSHKey) and isinstance(s2, SSHKey):
return s1._SSHKey__eqcontent__(s2)
else:
raise TypeError
def stream_unequal(s1, s2) -> bool | Never:
if isinstance(s1, SSHKey) and isinstance(s2, SSHKey):
return s1._SSHKey__neqcontent__(s2)
else:
raise TypeError
# @TODO create unit tests for below class
class SSHKeyCollection(Sequence):
__user_path: ExecutedPath = USER_PATH()
__ssh_path: ExecutedPath = __user_path / ".ssh"
def __init__(self):
self.__current: SSHKey | None = None
self.__first: SSHKey | None = None
self.__last: SSHKey | None = None
self.__indices: range | None = None
# @TODO allow initialization with unpacked parameter or sequence/iterable argument
def __getitem__(self, key: int | slice) -> SSHKey | Never:
self.__current = self.__first
if self.__current is None:
raise KeyError
if isinstance(key, int):
if int(self.__current) == key:
return self.__current
else:
while int(self.__current) != key:
if self.__current is None:
raise KeyError
self.__current = next(self.__current)
result = self.__current
elif isinstance(key, slice):
step = key.step
sshkcoll = SSHKeyCollection()
if hasattr(key, "start"):
if getattr(key, "start") is None:
start = 0
else:
start = key.start
if hasattr(key, "stop"):
if getattr(key, "stop") is None:
stop = len(self.__indices)
else:
stop = key.stop
if hasattr(key, "step"):
if getattr(key, "step") is None:
step = 1
else:
step = key.step
indices = range(start, stop, step)
# test_coll = []
while int(self.__current) < stop:
if int(self.__current) < start:
continue
elif int(self.__current) >= start:
if int(self.__current) in indices:
sshkcoll.append(self.__current)
# test_coll.append(self.__current)
else:
continue
self.__current = next(self.__current)
if self.__current is None:
break
# print(test_coll)
result = sshkcoll
return result
def __len__(self) -> int:
if self.__indices is None:
return 0
return len(self.__indices)
def pop(self, key: int = -1) -> Never:
self.__current = self.__first
if self.__current is None:
raise KeyError
if key == -1:
if self.__last is not None:
past = self.__last
self.__last._SSHKey__prev._SSHKey__next = None
self.__last = self.__last._SSHKey__prev
self.__current = self.__last
else:
past = self.__first
self.__first = None
return past
elif key <= -2:
raise NotImplementedError
else:
while int(self.__current) != key:
self.__current = next(self.__current)
if self.__current is None:
raise KeyError
past = self.__current
count = self.__current._SSHKey__idx
prior = self.__current._SSHKey__prev
posterior = self.__current._SSHKey__next
posterior._SSHKey__prev = prior
posterior._SSHKey__prev._SSHKey__next = posterior
self.__current = posterior
while self.__current is not None:
self.__current._SSHKey__idx = count
self.__current = next(self.__current)
count += 1
return past
def remove(self) -> Never:
raise NotImplementedError
def append(self, *value: ExecutedPath | str) -> SSHKey:
if len(value) < 1 or len(value) > 2:
raise ValueError
value = tuple(map(lambda s: Path(s) if isinstance(s, str) else s, value))
ssh_key = SSHKey(*value)
if self.__first is None:
# print("branch1")
ssh_key._SSHKey__idx = 0
# print(ssh_key._SSHKey__idx)
ssh_key.update_status()
self.__indices = range(ssh_key._SSHKey__idx + 1)
self.__first = ssh_key
self.__current = self.__first
else:
# print("branch2")
if self.__last is not None:
# print("branch2.1")
ssh_key._SSHKey__idx = self.__last._SSHKey__idx + 1
# print(ssh_key._SSHKey__idx)
ssh_key.update_status()
self.__last._SSHKey__next = ssh_key
self.__last._SSHKey__next._SSHKey__prev = self.__last
self.__last = next(self.__last)
else:
# print("branch2.2")
ssh_key._SSHKey__idx = self.__first._SSHKey__idx + 1
# print(ssh_key._SSHKey__idx)
ssh_key.update_status()
self.__first._SSHKey__next = ssh_key
self.__first._SSHKey__next._SSHKey__prev = self.__first
self.__last = self.__first._SSHKey__next
self.__indices = range(ssh_key._SSHKey__idx + 1)
self.__current = self.__last
#print(self.__current)
return self.__current
def __setitem__(self, key: int | slice, *value: ExecutedPath | str) -> None | Never:
if len(value) < 1 or len(value) > 2:
raise ValueError
value = tuple(map(lambda s: Path(s) if isinstance(s, str) else s, value))
self.__current = self.__first
if self.__current is None:
raise KeyError
if isinstance(key, int):
if int(self.__current) == key:
if self.__current() is None or len(self.__current()) < 1:
self.__current(*value)
else:
if int(self.__current) == key:
return self.__current(*value)
while int(self.__current) != key:
if self.__current is None:
raise KeyError
self.__current = next(self.__current)
self.__current(*value)
elif isinstance(key, slice):
raise NotImplementedError
def __delitem__(self, key: int | slice) -> None | Never:
self.__current = self.__first
if self.__current is None:
raise KeyError
if isinstance(key, int):
if key == -1:
if self.__last is not None:
self.__last._SSHKey__prev._SSHKey__next = None
self.__last = self.__last._SSHKey__prev
self.__current = self.__last
else:
self.__first = None
return past
elif key <= -2:
raise NotImplementedError
else:
while int(self.__current) != key:
self.__current = next(self.__current)
if self.__current is None:
raise KeyError
count = self.__current._SSHKey__idx
prior = self.__current._SSHKey__prev
posterior = self.__current._SSHKey__next
posterior._SSHKey__prev = prior
posterior._SSHKey__prev._SSHKey__next = posterior
self.__current = posterior
while self.__current is not None:
self.__current._SSHKey__idx = count
self.__current = next(self.__current)
count += 1
elif isinstance(key, slice):
raise NotImplementedError
@property
def head(self) -> SSHKey | None:
return self.__first
@property
def tail(self) -> SSHKey | None:
if self.__last is None:
return self.__first
return self.__last
def __contains__(self, value: ExecutedPath | str) -> bool:
self.__current = self.__first
if isinstance(value, ExecutedPath):
value = str(value)
is_contained = False
while self.__current is not None:
if str(self.__current._SSHKey__value) == value:
is_contained = True
break
self.__current = next(self.__current)
return is_contained
def __missing__(self, value: ExecutedPath | str) -> Never:
raise NotImplementedError
def __next__(self):
self.__current = next(self.__current)
if self.__current is not None:
return self.__current
else:
raise StopIteration
def __iter__(self) -> Self | Never:
self.__current = self.__first
# return self.__current
return self
def count(self, query: RegEx | str) -> int | Never:
raise NotImplementedError
def pull(self, query: RegEx | str = "*") -> None:
if isinstance(query, RegEx):
keypaths = self.__ssh_path.glob("*")
for p in keypaths:
if query.fullmatch(p.name):
if not Match("(known_hosts|authorized_keys|config).*", p.name):
self.append(p)
else:
continue
else:
keypaths = self.__ssh_path.glob(query)
for p in keypaths:
if not Match("(known_hosts|authorized_keys|config).*", p.name):
self.append(p)
def reverse(self) -> None | Never:
raise NotImplementedError
def sort(self, key: Callable = (lambda e: e), reverse: bool = False) -> None | Never:
raise NotImplementedError
def __str__(self) -> str:
prefix = "[("
postfix = "|]"
self.__current = self.__first
concat = lambda s: str(s) + ", "
content = str()
count = 0
while self.__current is not None:
content += str(count) + ">" + concat(self.__current)
self.__current = next(self.__current)
count += 1
content = content[0:len(content)-2]
return prefix + content + postfix
def index(self, item: str | ExecutedPath) -> Never:
raise NotImplementedError
def publish(self, category: SSHKeyType | str | None = SSHKeyType.pubkey, pref: int | None = None, datatype = list):
privkey = list()
pubkey = list()
self.__current = self.__first
# @TODO create conditional case that publishes all keys
if datatype == list:
while self.__current is not None:
# print(self.__current)
if self.__current.category == SSHKeyType.privkey.name.lower():
privkey.append(self.__current._SSHKey__value)
elif self.__current.category == SSHKeyType.pubkey.name.lower():
pubkey.append(self.__current._SSHKey__value)
elif self.__current.category == SSHKeyType.dual.name.lower():
privkey.append(self.__current._SSHKey__value[0])
pubkey.append(self.__current._SSHKey__value[1])
self.__current = next(self.__current)
# print("publish running...")
if pref is None:
preference = gamble(range(len(privkey)))
else:
preference = pref
# print(category)
if category.name.lower() == SSHKeyType.pubkey.name.lower():
return pubkey
elif category.name.lower() == SSHKeyType.privkey.name.lower():
return (privkey, preference)
else:
return (privkey, pubkey, preference)
elif datatype == dict:
# @TODO have result var equal to instance of a yaml.YAMLObject class from parse module
raise NotImplementedError
return result
def __repr__(self) -> str:
return "%s()" % (self.__class__.__name__)

View File

@@ -1,15 +0,0 @@
#+author: Alex Tavarez
#+email: ajt95@prole.biz
#+language: en
* PLANNED
** DONE [#A] Write documentation on the expected conventional names to be used in the inventory file
** DONE [#A] Write documentation on the expected conventional paths to be used in the inventory file
** TODO [#A] Create Python Click library/package- based CLI
** TODO [#A] Soft-code relative paths for role files/templates in Ansible tasks/plays
** TODO [#A] Soft-code project root and paths to passwords/secrets files for Ansible tasks/plays
** TODO [#A] Rewrite dot notation usage of keys for accessing values in custom dictionary variables to bracket notation usage of keys across whole project
* IN PROGRESS
* FINISHED

View File

@@ -1,62 +0,0 @@
"""
Library of path constants to be used or referenced elsewhere.
"""
from custtypes import ExecutedPath, Roles, Scopes, AnsibleScopes, NodeType, UserName
from pathlib import Path
from configparser import ConfigParser as cfg
from itertools import chain
from typing import Callable
def get_home(node: NodeType = NodeType.control, home: UserName | str | None = None) -> ExecutedPath:
if node == NodeType.control:
return Path.home()
else:
if home is None:
return Path("~")
else:
if isinstance(home, UserName):
return Path("/home") / home.name
else:
return Path(home)
USER_PATH: Callable = get_home
PROJ_ROOT: ExecutedPath = Path(__file__).parent.resolve()
config = cfg()
ANSIBLE_CONFIG = PROJ_ROOT / "ansible.cfg"
if ANSIBLE_CONFIG.exists():
config.read(str(ANSIBLE_CONFIG))
role_candidates = config["defaults"]["roles_path"].split(":")
role_candidates = map(lambda s: PROJ_ROOT / s, role_candidates)
role_paths = list(filter(lambda p: p.exists(), role_candidates))
inv_candidates = config["defaults"]["inventory"].split(",")
inv_candidates = map(lambda s: PROJ_ROOT / s, inv_candidates)
inv_paths = list(filter(lambda p: p.exists(), inv_candidates))
else:
role_paths = [PROJ_ROOT / "roles"]
inv_paths = PROJ_ROOT.glob("hosts*.*")
PROJ_ROLES: list[ExecutedPath] = role_paths
PROJ_INVENTORIES: list[ExecutedPath] = inv_paths
proj_paths = map(lambda r: r.glob("**/files"), PROJ_ROLES)
proj_paths = list(chain.from_iterable(proj_paths))
template_paths = map(lambda r: r.glob("**/templates"), PROJ_ROLES)
template_paths = list(chain.from_iterable(template_paths))
APP_ROOTS = {
Roles.CONF.name.lower(): {
Scopes.SYS.name.lower(): Path("/etc"),
Scopes.USER.name.lower(): USER_PATH(NodeType.remote) / ".config",
Scopes.SHARED.name.lower(): Path("/usr/share"),
Scopes.PROJ.name.lower(): tuple(proj_paths + template_paths)
}
}
ANSIBLE_ROOTS = {
AnsibleScopes.GROUPVARS.name.lower(): PROJ_ROOT / "group_vars",
AnsibleScopes.HOSTVARS.name.lower(): PROJ_ROOT / "host_vars",
AnsibleScopes.INVENTORY.name.lower(): tuple(PROJ_INVENTORIES),
AnsibleScopes.ROLE.name.lower(): tuple(PROJ_ROLES)
}