├── .ansible-lint ├── .github ├── code_of_conduct.md ├── img │ └── header.png └── workflows │ ├── ci.yml │ ├── release.yml │ └── scheduled-task_update-sponsors.yml ├── .gitignore ├── .spin.example.yml ├── .yamllint ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── dev.sh ├── galaxy.yml ├── meta └── runtime.yml ├── molecule └── default │ ├── converge.yml │ ├── inventory.ini │ ├── molecule.yml │ ├── vars.yml │ └── verify.yml ├── new-version.sh ├── playbooks ├── get_variable.yml ├── maintain.yml ├── prepare_ci_environment.yml └── provision.yml ├── plugins └── inventory │ └── spin-dynamic-inventory.sh ├── requirements.txt └── roles ├── create_server ├── README.md ├── requirements.yml └── tasks │ ├── create-servers.yml │ ├── main.yml │ └── providers │ ├── digitalocean.yml │ ├── hetzner.yml │ └── vultr.yml ├── docker_user ├── README.md ├── defaults │ └── main.yml ├── requirements.yml └── tasks │ └── main.yml ├── linux_common ├── README.md ├── defaults │ └── main.yml ├── handlers │ └── main.yml ├── requirements.yml ├── tasks │ ├── email-alerts.yml │ ├── main.yml │ ├── motd.yml │ ├── security.yml │ ├── setup-Debian.yml │ ├── users.yml │ └── validate-inputs.yml ├── templates │ └── etc │ │ ├── apt │ │ └── apt.conf.d │ │ │ ├── 20auto-upgrades.j2 │ │ │ └── 50unattended-upgrades.j2 │ │ ├── ssh │ │ └── sshd_config.d │ │ │ ├── 01-spin-secure-ssh.conf.j2 │ │ │ └── 02-spin-ssh-tunnels.conf.j2 │ │ └── update-motd.d │ │ ├── 30-motd-header.j2 │ │ ├── 35-sysinfo.j2 │ │ └── 40-services.j2 └── vars │ └── main.yml ├── swarm ├── README.md ├── defaults │ └── main.yml ├── handlers │ └── main.yml ├── requirements.yml └── tasks │ ├── configure-swarm.yml │ ├── main.yml │ └── setup-Debian.yml └── update_server ├── README.md └── tasks └── main.yml /.ansible-lint: -------------------------------------------------------------------------------- 1 | skip_list: 2 | - 'no-changed-when' 3 | - 'package-latest' 4 | - 'var-naming[no-role-prefix]' 5 | - 'no-handler' 6 | - 'galaxy[no-changelog]' -------------------------------------------------------------------------------- /.github/code_of_conduct.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | We as members, contributors, and leaders pledge to make participation in our 7 | community a harassment-free experience for everyone, regardless of age, body 8 | size, visible or invisible disability, ethnicity, sex characteristics, gender 9 | identity and expression, level of experience, education, socio-economic status, 10 | nationality, personal appearance, race, caste, color, religion, or sexual 11 | identity and orientation. 12 | 13 | We pledge to act and interact in ways that contribute to an open, welcoming, 14 | diverse, inclusive, and healthy community. 15 | 16 | ## Our Standards 17 | 18 | Examples of behavior that contributes to a positive environment for our 19 | community include: 20 | 21 | * Demonstrating empathy and kindness toward other people 22 | * Being respectful of differing opinions, viewpoints, and experiences 23 | * Giving and gracefully accepting constructive feedback 24 | * Accepting responsibility and apologizing to those affected by our mistakes, 25 | and learning from the experience 26 | * Focusing on what is best not just for us as individuals, but for the overall 27 | community 28 | 29 | Examples of unacceptable behavior include: 30 | 31 | * The use of sexualized language or imagery, and sexual attention or advances of 32 | any kind 33 | * Trolling, insulting or derogatory comments, and personal or political attacks 34 | * Public or private harassment 35 | * Publishing others' private information, such as a physical or email address, 36 | without their explicit permission 37 | * Other conduct which could reasonably be considered inappropriate in a 38 | professional setting 39 | 40 | ## Enforcement Responsibilities 41 | 42 | Community leaders are responsible for clarifying and enforcing our standards of 43 | acceptable behavior and will take appropriate and fair corrective action in 44 | response to any behavior that they deem inappropriate, threatening, offensive, 45 | or harmful. 46 | 47 | Community leaders have the right and responsibility to remove, edit, or reject 48 | comments, commits, code, wiki edits, issues, and other contributions that are 49 | not aligned to this Code of Conduct, and will communicate reasons for moderation 50 | decisions when appropriate. 51 | 52 | ## Scope 53 | 54 | This Code of Conduct applies within all community spaces, and also applies when 55 | an individual is officially representing the community in public spaces. 56 | Examples of representing our community include using an official e-mail address, 57 | posting via an official social media account, or acting as an appointed 58 | representative at an online or offline event. 59 | 60 | ## Enforcement 61 | 62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 63 | reported to the community leaders responsible for enforcement at 64 | [INSERT CONTACT METHOD]. 65 | All complaints will be reviewed and investigated promptly and fairly. 66 | 67 | All community leaders are obligated to respect the privacy and security of the 68 | reporter of any incident. 69 | 70 | ## Enforcement Guidelines 71 | 72 | Community leaders will follow these Community Impact Guidelines in determining 73 | the consequences for any action they deem in violation of this Code of Conduct: 74 | 75 | ### 1. Correction 76 | 77 | **Community Impact**: Use of inappropriate language or other behavior deemed 78 | unprofessional or unwelcome in the community. 79 | 80 | **Consequence**: A private, written warning from community leaders, providing 81 | clarity around the nature of the violation and an explanation of why the 82 | behavior was inappropriate. A public apology may be requested. 83 | 84 | ### 2. Warning 85 | 86 | **Community Impact**: A violation through a single incident or series of 87 | actions. 88 | 89 | **Consequence**: A warning with consequences for continued behavior. No 90 | interaction with the people involved, including unsolicited interaction with 91 | those enforcing the Code of Conduct, for a specified period of time. This 92 | includes avoiding interactions in community spaces as well as external channels 93 | like social media. Violating these terms may lead to a temporary or permanent 94 | ban. 95 | 96 | ### 3. Temporary Ban 97 | 98 | **Community Impact**: A serious violation of community standards, including 99 | sustained inappropriate behavior. 100 | 101 | **Consequence**: A temporary ban from any sort of interaction or public 102 | communication with the community for a specified period of time. No public or 103 | private interaction with the people involved, including unsolicited interaction 104 | with those enforcing the Code of Conduct, is allowed during this period. 105 | Violating these terms may lead to a permanent ban. 106 | 107 | ### 4. Permanent Ban 108 | 109 | **Community Impact**: Demonstrating a pattern of violation of community 110 | standards, including sustained inappropriate behavior, harassment of an 111 | individual, or aggression toward or disparagement of classes of individuals. 112 | 113 | **Consequence**: A permanent ban from any sort of public interaction within the 114 | community. 115 | 116 | ## Attribution 117 | 118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 119 | version 2.1, available at 120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 121 | 122 | Community Impact Guidelines were inspired by 123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 124 | 125 | For answers to common questions about this code of conduct, see the FAQ at 126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at 127 | [https://www.contributor-covenant.org/translations][translations]. 128 | 129 | [homepage]: https://www.contributor-covenant.org 130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 131 | [Mozilla CoC]: https://github.com/mozilla/diversity 132 | [FAQ]: https://www.contributor-covenant.org/faq 133 | [translations]: https://www.contributor-covenant.org/translations 134 | 135 | -------------------------------------------------------------------------------- /.github/img/header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/serversideup/ansible-collection-spin/53ecd9724437b7eb47d83f620fcd25552834c6cf/.github/img/header.png -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: CI 3 | 'on': 4 | pull_request: 5 | push: 6 | branches: 7 | - main 8 | tags: 9 | - '*' 10 | 11 | jobs: 12 | 13 | lint: 14 | name: Lint 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Check out the codebase. 18 | uses: actions/checkout@v4 19 | 20 | - name: Set up Python 3. 21 | uses: actions/setup-python@v5 22 | with: 23 | python-version: '3.x' 24 | 25 | - name: Install test dependencies. 26 | run: pip3 install yamllint ansible-lint 27 | 28 | - name: Run YAML Lint. 29 | run: yamllint . 30 | 31 | - name: Run ansible-lint. 32 | run: ansible-lint ./roles/ 33 | 34 | molecule: 35 | name: Molecule 36 | runs-on: ubuntu-latest 37 | strategy: 38 | matrix: 39 | distro: 40 | - ubuntu2204 41 | - ubuntu2404 42 | 43 | steps: 44 | - name: Check out the codebase. 45 | uses: actions/checkout@v4 46 | 47 | - name: Set up Python 3. 48 | uses: actions/setup-python@v5 49 | with: 50 | python-version: '3.x' 51 | 52 | - name: Install test dependencies. 53 | run: pip3 install -r requirements.txt 54 | 55 | - name: Run Molecule tests. 56 | run: molecule test 57 | env: 58 | PY_COLORS: '1' 59 | ANSIBLE_FORCE_COLOR: '1' 60 | MOLECULE_DISTRO: ${{ matrix.distro }} 61 | 62 | release: 63 | if: ${{ github.ref_type == 'tag' }} 64 | needs: [lint, molecule] 65 | uses: ./.github/workflows/release.yml 66 | secrets: inherit -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | workflow_call: 4 | 5 | jobs: 6 | release: 7 | runs-on: ubuntu-22.04 8 | steps: 9 | - name: Check out the codebase. 10 | uses: actions/checkout@v4 11 | 12 | - name: Set up Python 3. 13 | uses: actions/setup-python@v5 14 | with: 15 | python-version: '3.x' 16 | 17 | - name: Install Ansible. 18 | run: pip3 install ansible-core 19 | 20 | - name: Build Collection 21 | run: ansible-galaxy collection build 22 | 23 | - name: Publish Collection to Ansible Galaxy 24 | run: ansible-galaxy collection publish ./serversideup-spin-*.tar.gz --api-key ${{ secrets.GALAXY_API_KEY }} 25 | -------------------------------------------------------------------------------- /.github/workflows/scheduled-task_update-sponsors.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Generate Sponsors README 3 | 'on': 4 | workflow_dispatch: 5 | schedule: 6 | - cron: 0 12 * * 1 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout 🛎️ 12 | uses: actions/checkout@v4 13 | 14 | - name: Generate Sponsors 💖 15 | uses: JamesIves/github-sponsors-readme-action@v1 16 | with: 17 | organization: true 18 | maximum: 500 19 | fallback: '

Sponsors

' 20 | token: ${{ secrets.SPONSORS_README_ACTION_PERSONAL_ACCESS_TOKEN }} 21 | marker: 'supporters' 22 | template: '{{{ login }}}  ' 23 | file: 'README.md' 24 | 25 | - name: Deploy to GitHub Pages 🚀 26 | uses: JamesIves/github-pages-deploy-action@v4 27 | with: 28 | branch: main 29 | folder: '.' 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.tar.gz 2 | test/results 3 | .spin.yml 4 | .vault-password -------------------------------------------------------------------------------- /.spin.example.yml: -------------------------------------------------------------------------------- 1 | ############################################################## 2 | # 👇 Users - You must set at least one user 3 | ############################################################## 4 | 5 | users: 6 | # - username: alice 7 | # name: Alice Smith 8 | # groups: ['sudo'] 9 | # authorized_keys: 10 | # - public_key: "ssh-ed25519 AAAAC3NzaC1lmyfakeublickeyMVIzwQXBzxxD9b8Erd1FKVvu alice" 11 | 12 | # - username: bob 13 | # name: Bob Smith 14 | # state: present 15 | # password: "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1" 16 | # groups: ['sudo'] 17 | # shell: "/bin/bash" 18 | # authorized_keys: 19 | # - public_key: "ssh-ed25519 AAAAC3NzaC1anotherfakekeyIMVIzwQXBzxxD9b8Erd1FKVvu bob" 20 | 21 | ############################################################## 22 | # 👇 Providers - You must set at least one provider 23 | ############################################################## 24 | 25 | providers: 26 | # - name: digitalocean 27 | # api_token: Set token here OR delete this line and set environment variable DO_API_TOKEN 28 | 29 | # - name: hetzner 30 | # api_token: Set token here OR delete this line and set environment variable HCLOUD_TOKEN 31 | 32 | # - name: vultr 33 | # api_token: Set token here OR delete this line and set environment variable VULTR_API_KEY 34 | 35 | ############################################################## 36 | # 👇 Servers - You must set at least one server 37 | ############################################################## 38 | 39 | servers: 40 | # - server_name: ubuntu-2gb-ash-1 41 | # environment: production 42 | # hardware_profile: hetzner_2c_2gb_ubuntu2404 43 | 44 | # - server_name: ubuntu-1gb-ord-2 45 | # environment: staging 46 | # hardware_profile: vultr_1c_1gb_ubuntu2404 47 | 48 | ############################################################## 49 | # 🤖 Hardware Profiles 50 | ############################################################## 51 | 52 | hardware_profiles: 53 | # Hetzner 54 | - name: hetzner_2c_2gb_ubuntu2404 55 | provider: hetzner 56 | profile_config: 57 | location: ash 58 | server_type: cpx11 59 | image: ubuntu-24.04 60 | backups: true 61 | 62 | # Vultr 63 | - name: vultr_1c_1gb_ubuntu2404 64 | provider: vultr 65 | profile_config: 66 | region: ord 67 | plan: vc2-1c-1gb 68 | os: "Ubuntu 24.04 LTS x64" 69 | backups: true 70 | 71 | # DigitalOcean 72 | - name: digitalocean_1c_1gb_ubuntu2404 73 | provider: digitalocean 74 | profile_config: 75 | region: nyc3 76 | size: s-1vcpu-1gb 77 | image: ubuntu-24-04-x64 78 | backups: true 79 | 80 | ############################################################## 81 | # 🌎 Environments 82 | ############################################################## 83 | environments: 84 | - name: production 85 | - name: staging 86 | - name: development 87 | 88 | ############################################################## 89 | # 🤓 Advanced Server Configuration 90 | ############################################################## 91 | 92 | # Timezone and contact settings 93 | server_timezone: "Etc/UTC" 94 | server_contact: changeme@example.com 95 | 96 | # If you the SSH port below, you may need to run `spin provision -p ` 97 | # to get a connection on your first provision. Otherwise, SSH will try connecting 98 | # to your new port before the SSH server configuration is updated. 99 | ssh_port: "22" 100 | 101 | ## You can set this to false to require a password for sudo. 102 | ## If you disable passwordless sudo, you must set a password for all sudo users. 103 | ## generate an encrypted hash with `spin mkpasswd`. Learn more: 104 | ## https://serversideup.net/open-source/spin/docs/command-reference/mkpasswd 105 | use_passwordless_sudo: true 106 | 107 | ## Email Notifications 108 | postfix_hostname: "{{ inventory_hostname }}" 109 | 110 | ## Set variables below to enable external SMTP relay 111 | # postfix_relayhost: "smtp.example.com" 112 | # postfix_relayhost_port: "587" 113 | # postfix_relayhost_username: "myusername" 114 | # postfix_relayhost_password: "mysupersecretpassword" 115 | 116 | ## Deploy user customization - You can customize the deploy user below if you'd like 117 | # docker_user: 118 | # username: deploy 119 | # home: /opt/deploy 120 | # authorized_ssh_keys: 121 | # - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKNJGtd7a4DBHsQi7HGrC5xz0eAEFHZ3Ogh3FEFI2345 fake@key" 122 | # - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFRfXxUZ8q9vHRcQZ6tLb0KwGHu8xjQHfYopZKLmnopQ anotherfake@key" 123 | -------------------------------------------------------------------------------- /.yamllint: -------------------------------------------------------------------------------- 1 | --- 2 | # Based on ansible-lint config 3 | extends: default 4 | 5 | rules: 6 | braces: 7 | max-spaces-inside: 1 8 | level: error 9 | brackets: 10 | max-spaces-inside: 1 11 | level: error 12 | colons: 13 | max-spaces-after: -1 14 | level: error 15 | commas: 16 | max-spaces-after: -1 17 | level: error 18 | comments: disable 19 | comments-indentation: disable 20 | document-start: disable 21 | empty-lines: 22 | max: 3 23 | level: error 24 | hyphens: 25 | level: error 26 | indentation: disable 27 | key-duplicates: enable 28 | line-length: disable 29 | new-line-at-end-of-file: disable 30 | new-lines: 31 | type: unix 32 | trailing-spaces: disable 33 | truthy: disable 34 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | The Spin Ansible Collection is an open-source project that aims to provide a seamless and efficient way to provision and manage servers. This collection is designed to work seamlessly with the Spin command-line tool to automate server setup, configuration, and deployment. 3 | 4 | ## Preparing a virtual python environment 5 | You can use [`pipx`](https://pipx.pypa.io/stable/) to install `virtualenv` and create a virtual environment. 6 | 7 | ```bash 8 | pipx install virtualenv 9 | ``` 10 | 11 | Create a virtual environment in your home directory: 12 | 13 | ```bash 14 | virtualenv ~/.py 15 | ``` 16 | 17 | Activate the virtual environment: 18 | 19 | ```bash 20 | source ~/.py/bin/activate 21 | ``` 22 | 23 | If you want to make the virtual environment available to all users, you can activate it in your `.bashrc` or `.zshrc` file. 24 | 25 | ```bash 26 | source ~/.py/bin/activate 27 | ``` 28 | 29 | Use the `pip3` command to install Ansible and Molecule: 30 | 31 | ```bash 32 | pip3 install -r requirements.txt 33 | ``` 34 | 35 | ## Running tests 36 | We use [Molecule](https://molecule.readthedocs.io/en/latest/) to test the role. 37 | 38 | ```bash 39 | molecule test 40 | ``` 41 | 42 | ## Advanced usage 43 | Instead of running `molecule test` to run the tests (which will destroy and recreate the test environment), you can use the following commands to test the role in a container: 44 | 45 | ```bash 46 | molecule create # Builds the container 47 | molecule converge # Runs the playbook 48 | molecule verify # Runs the tests 49 | molecule destroy # Destroys the container 50 | ``` 51 | 52 | ## Testing the collection 53 | Instead of committing to a brach and testing on another machine, it might be easier to just build the collection and install it locally. This will build and install the collection locally on your machine. Look at the file `dev.sh` to see how this is done. 54 | 55 | ```bash 56 | bash dev.sh 57 | ``` -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Spin Ansible Collection Header 3 |

4 |

5 | Build Status 6 | License 7 | Support us 8 | Discord 9 |

10 | 11 | ## Introduction 12 | The Spin Ansible Collection is the secret magic that powers the [`spin provision`](https://serversideup.net/open-source/spin/docs/command-reference/provision) command. This collection has been specifically designed to optimize developer workflow for Spin users. 13 | 14 | ## Installation & Usage 15 | To use this collection, it is recommended to install `spin` via the [official installation instructions](https://serversideup.net/open-source/spin/docs/). Once installed, you can use the `spin provision` command to provision your servers. This command will automatically install the collection for you. 16 | 17 | ## Requirements 18 | In the early phases of this project, we will be supporting **Ubuntu 22.04** and **Ubuntu 24.04** only. We do intend to support other operating systems as we continue to develop this project. 19 | 20 | ## Demo 21 | Here's a demo showing a process of creating a new Laravel project and deploying it to production: 22 | 23 | 24 | 25 | ## Resources 26 | - **[Website](https://serversideup.net/open-source/spin/)** overview of the product. 27 | - **[Docs](https://serversideup.net/open-source/spin/docs)** for a deep-dive on how to use the product. 28 | - **[Discord](https://serversideup.net/discord)** for friendly support from the community and the team. 29 | - **[GitHub](https://github.com/serversideup/ansible-collection-spin)** for source code, bug reports, and project management. 30 | - **[Get Professional Help](https://serversideup.net/professional-support)** - Get video + screen-sharing help directly from the core contributors. 31 | 32 | ## Contributing 33 | As an open-source project, we strive for transparency and collaboration in our development process. We greatly appreciate any contributions members of our community can provide. Whether you're fixing bugs, proposing features, improving documentation, or spreading awareness - your involvement strengthens the project. Please review our [contribution guidelines](https://serversideup.net/open-source/spin/docs/community/contributing) and [code of conduct](./.github/code_of_conduct.md) to understand how we work together respectfully. 34 | 35 | - **Bug Report**: If you're experiencing an issue while using these images, please [create an issue](https://github.com/serversideup/ansible-collection-spin/issues/new/choose). 36 | - **Feature Request**: Make this project better by [submitting a feature request](https://github.com/serversideup/spin/discussions/9). 37 | - **Documentation**: Improve our documentation by [submitting a documentation change](./docs/README.md). 38 | - **Community Support**: Help others on [GitHub Discussions](https://github.com/serversideup/spin/discussions) or [Discord](https://serversideup.net/discord). 39 | - **Security Report**: Report critical security issues via [our responsible disclosure policy](https://www.notion.so/Responsible-Disclosure-Policy-421a6a3be1714d388ebbadba7eebbdc8). 40 | 41 | Need help getting started? Join our Discord community and we'll help you out! 42 | 43 | 44 | 45 | ## Our Sponsors 46 | All of our software is free an open to the world. None of this can be brought to you without the financial backing of our sponsors. 47 | 48 |

Sponsors

49 | 50 | #### Individual Supporters 51 | GeekDougle  JQuilty  MaltMethodDev   52 | 53 | ## About Us 54 | We're [Dan](https://twitter.com/danpastori) and [Jay](https://twitter.com/jaydrogers) - a two person team with a passion for open source products. We created [Server Side Up](https://serversideup.net) to help share what we learn. 55 | 56 |
57 | 58 | |
Dan Pastori
|
Jay Rogers
| 59 | | ----------------------------- | ------------------------------------------ | 60 | |

|

| 61 | 62 |
63 | 64 | ### Find us at: 65 | 66 | * **📖 [Blog](https://serversideup.net)** - Get the latest guides and free courses on all things web/mobile development. 67 | * **🙋 [Community](https://community.serversideup.net)** - Get friendly help from our community members. 68 | * **🤵‍♂️ [Get Professional Help](https://serversideup.net/professional-support)** - Get video + screen-sharing support from the core contributors. 69 | * **💻 [GitHub](https://github.com/serversideup)** - Check out our other open source projects. 70 | * **📫 [Newsletter](https://serversideup.net/subscribe)** - Skip the algorithms and get quality content right to your inbox. 71 | * **🐥 [Twitter](https://twitter.com/serversideup)** - You can also follow [Dan](https://twitter.com/danpastori) and [Jay](https://twitter.com/jaydrogers). 72 | * **❤️ [Sponsor Us](https://github.com/sponsors/serversideup)** - Please consider sponsoring us so we can create more helpful resources. 73 | 74 | ## Our products 75 | If you appreciate this project, be sure to check out our other projects. 76 | 77 | ### 📚 Books 78 | - **[The Ultimate Guide to Building APIs & SPAs](https://serversideup.net/ultimate-guide-to-building-apis-and-spas-with-laravel-and-nuxt3/)**: Build web & mobile apps from the same codebase. 79 | 80 | ### 🛠️ Software-as-a-Service 81 | - **[Bugflow](https://bugflow.io/)**: Get visual bug reports directly in GitHub, GitLab, and more. 82 | - **[SelfHost Pro](https://selfhostpro.com/)**: Connect Stripe or Lemonsqueezy to a private docker registry for self-hosted apps. 83 | 84 | ### 🌍 Open Source 85 | - **[serversideup/php Docker Images](https://serversideup.net/open-source/docker-php/)**: PHP Docker images optimized for Laravel and running PHP applications in production. 86 | - **[Financial Freedom](https://github.com/serversideup/financial-freedom)**: Open source alternative to Mint, YNAB, & Monarch Money. 87 | - **[AmplitudeJS](https://521dimensions.com/open-source/amplitudejs)**: Open-source HTML5 & JavaScript Web Audio Library. -------------------------------------------------------------------------------- /dev.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -x 3 | 4 | # Parse command line arguments 5 | while [[ $# -gt 0 ]]; do 6 | case $1 in 7 | --debug) 8 | export ANSIBLE_STDOUT_CALLBACK=debug 9 | shift 10 | ;; 11 | *) 12 | extra_arguments+=("$1") 13 | shift 14 | ;; 15 | esac 16 | done 17 | 18 | # Set environment variables 19 | export ANSIBLE_WORK_DIR="${ANSIBLE_WORK_DIR:-$(pwd)}" 20 | export ANSIBLE_VARIABLE_FILE_NAME="${ANSIBLE_VARIABLE_FILE_NAME:-".spin.yml"}" 21 | export ANSIBLE_VARIABLE_FILEPATH="${ANSIBLE_VARIABLE_FILEPATH:-"${ANSIBLE_WORK_DIR}/${ANSIBLE_VARIABLE_FILE_NAME}"}" 22 | 23 | # Use ANSIBLE_VARIABLE_FILEPATH instead of variable_file_path 24 | variable_file_path="${ANSIBLE_VARIABLE_FILEPATH}" 25 | 26 | version=$(awk '/version:/ {print $2; exit}' galaxy.yml) 27 | ansible-galaxy collection build --force 28 | ansible-galaxy collection install "serversideup-spin-${version}.tar.gz" --force 29 | ansible-playbook -i plugins/inventory/spin-dynamic-inventory.sh playbooks/provision.yml --extra-vars "@${variable_file_path}" "${extra_arguments[@]}" 30 | -------------------------------------------------------------------------------- /galaxy.yml: -------------------------------------------------------------------------------- 1 | --- 2 | namespace: serversideup 3 | name: spin 4 | version: 2.1.2 5 | readme: README.md 6 | authors: 7 | - Jay Rogers (https://x.com/jaydrogers) 8 | description: The Spin Collection is a collection of Ansible roles that can be used to spin up a Linux server with Docker Swarm. 9 | license_file: LICENSE 10 | tags: 11 | - serversideup 12 | - spin 13 | - linux 14 | - docker 15 | - swarm 16 | dependencies: 17 | ansible.posix: '*' 18 | community.general: '*' 19 | community.docker: '*' 20 | hetzner.hcloud: '*' 21 | vultr.cloud: '*' 22 | community.digitalocean: '*' 23 | repository: https://github.com/serversideup/ansible-collection-spin 24 | documentation: https://serversideup.net/open-source/spin/docs/ 25 | homepage: https://serversideup.net/open-source/spin/ 26 | issues: https://github.com/serversideup/ansible-collection-spin/issues 27 | build_ignore: 28 | - 'new-version.sh' 29 | -------------------------------------------------------------------------------- /meta/runtime.yml: -------------------------------------------------------------------------------- 1 | --- 2 | requires_ansible: '>=2.15.0' 3 | -------------------------------------------------------------------------------- /molecule/default/converge.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Converge 3 | hosts: all 4 | become: true 5 | vars_files: 6 | - vars.yml 7 | 8 | pre_tasks: 9 | - name: Update apt cache. 10 | ansible.builtin.apt: 11 | update_cache: yes 12 | cache_valid_time: 600 13 | when: ansible_os_family == 'Debian' 14 | 15 | - name: Install PIP dependencies. 16 | ansible.builtin.pip: 17 | name: docker 18 | state: present 19 | 20 | - name: Wait for systemd to complete initialization. # noqa 303 21 | ansible.builtin.command: systemctl is-system-running 22 | register: systemctl_status 23 | until: > 24 | 'running' in systemctl_status.stdout or 25 | 'degraded' in systemctl_status.stdout 26 | retries: 30 27 | delay: 5 28 | when: ansible_service_mgr == 'systemd' 29 | changed_when: false 30 | failed_when: systemctl_status.rc > 1 31 | 32 | roles: 33 | - role: serversideup.spin.linux_common 34 | - role: serversideup.spin.swarm 35 | -------------------------------------------------------------------------------- /molecule/default/inventory.ini: -------------------------------------------------------------------------------- 1 | #################### 2 | # Host Types 3 | #################### 4 | 5 | [production_manager_servers] 6 | instance 7 | 8 | [staging_manager_servers] 9 | # server02.example.com 10 | 11 | #################### 12 | # Swarm Roles 13 | #################### 14 | [swarm_managers:children] 15 | production_manager_servers 16 | staging_manager_servers 17 | 18 | #################### 19 | # Environment 20 | #################### 21 | [production:children] 22 | production_manager_servers 23 | 24 | [staging:children] 25 | staging_manager_servers 26 | 27 | [all_servers:children] 28 | production 29 | staging -------------------------------------------------------------------------------- /molecule/default/molecule.yml: -------------------------------------------------------------------------------- 1 | --- 2 | dependency: 3 | name: galaxy 4 | options: 5 | requirements-file: requirements.yml 6 | driver: 7 | name: docker 8 | platforms: 9 | - name: instance 10 | image: geerlingguy/docker-${MOLECULE_DISTRO:-ubuntu2404}-ansible:latest 11 | command: ${MOLECULE_DOCKER_COMMAND:-""} 12 | volumes: 13 | - /sys/fs/cgroup:/sys/fs/cgroup:rw 14 | cgroupns_mode: host 15 | privileged: true 16 | pre_build_image: true 17 | provisioner: 18 | name: ansible 19 | inventory: 20 | links: 21 | hosts: inventory.ini 22 | verifier: 23 | name: ansible 24 | lint: | 25 | set -e 26 | yamllint . 27 | ansible-lint . -------------------------------------------------------------------------------- /molecule/default/vars.yml: -------------------------------------------------------------------------------- 1 | server_timezone: "America/Chicago" 2 | server_contact: "otheremail@example.com" 3 | use_passwordless_sudo: false 4 | 5 | users: 6 | - username: alice 7 | name: Alice Smith 8 | state: present 9 | groups: ['sudo'] 10 | password: "$6$IXlCqhTY2T$nDnDJRcvk59V2yb3O4Z9n0zO70z/xVCllphjrJ.L618OvHfSs1hciwtxUS/UxR7tF5xWcwzRr3eHboiSHFG7I1" 11 | shell: "/bin/bash" 12 | authorized_keys: 13 | - public_key: "ssh-ed25519 AAAAC3NzaC1lmyfakeublickeyMVIzwQXBzxxD9b8Erd1FKVvu alice" 14 | 15 | - username: bob 16 | name: Bob Smith 17 | state: present 18 | password: "$6$IXlCqhTY2T$nDnDJRcvk59V2yb3O4Z9n0zO70z/xVCllphjrJ.L618OvHfSs1hciwtxUS/UxR7tF5xWcwzRr3eHboiSHFG7I1" 19 | groups: ['sudo'] 20 | shell: "/bin/bash" 21 | authorized_keys: 22 | - public_key: "ssh-ed25519 AAAAC3NzaC1anotherfakekeyIMVIzwQXBzxxD9b8Erd1FKVvu bob" 23 | 24 | additional_users: 25 | - username: charlie 26 | groups: ['sudo'] 27 | password: "$6$IXlCqhTY2T$nDnDJRcvk59V2yb3O4Z9n0zO70z/xVCllphjrJ.L618OvHfSs1hciwtxUS/UxR7tF5xWcwzRr3eHboiSHFG7I1" 28 | authorized_keys: 29 | - public_key: "ssh-ed25519 AAAAC3NzaC1lmyfakeublickeyMVIzwQXBzxxD9b8Erd1FKVvu charlie" 30 | 31 | - username: dana 32 | name: Dana Smith 33 | state: present 34 | password: "$6$IXlCqhTY2T$nDnDJRcvk59V2yb3O4Z9n0zO70z/xVCllphjrJ.L618OvHfSs1hciwtxUS/UxR7tF5xWcwzRr3eHboiSHFG7I1" 35 | groups: ['sudo'] 36 | shell: "/bin/bash" 37 | authorized_keys: 38 | - public_key: "ssh-ed25519 AAAAC3NzaC1anotherfakekeyIMVIzwQXBzxxD9b8Erd1FKVvu dana" 39 | 40 | - username: nopassword 41 | name: No Password Test 42 | state: present 43 | groups: ['users'] 44 | shell: "/bin/bash" 45 | authorized_keys: 46 | - public_key: "ssh-ed25519 AAAAC3NzaC1anotherfakekeyIMVIzwQXBzxxD9b8Erd1FKVvu nopassword" 47 | 48 | docker_user: 49 | username: dockeruser 50 | authorized_keys: 51 | - public_key: "ssh-ed25519 AAAAC3NzaC1anotherfakekeyIMVIzwQXBzxxD9b8Erd1FKVvu dockeruser" 52 | 53 | common_additional_packages: 54 | - python3-jsondiff 55 | - python3-yaml 56 | -------------------------------------------------------------------------------- /molecule/default/verify.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Verify 3 | hosts: all 4 | gather_facts: false 5 | vars_files: 6 | - vars.yml 7 | tasks: 8 | - name: Check current timezone 9 | command: timedatectl show --property=Timezone --value 10 | register: current_timezone 11 | changed_when: false 12 | 13 | - name: Assert timezone is correct 14 | assert: 15 | that: 16 | - current_timezone.stdout == server_timezone 17 | fail_msg: "Timezone is not set correctly" 18 | 19 | - name: Get Charlie user info. 20 | ansible.builtin.user: 21 | name: charlie 22 | register: charlie_user_test 23 | 24 | - name: Assert charlie user exists. 25 | assert: 26 | that: 27 | - charlie_user_test.name == 'charlie' 28 | - charlie_user_test.changed == false 29 | fail_msg: "Failed to assert the user 'charlie' exists." 30 | 31 | - name: Check to see if the user "deploy" exists. 32 | command: whoami 33 | become_user: deploy 34 | register: deploy_whoami 35 | changed_when: false 36 | 37 | - name: Get Docker user info. 38 | ansible.builtin.user: 39 | name: "{{ docker_user.username }}" 40 | register: docker_user_test 41 | 42 | - name: Assert docker user exists. 43 | assert: 44 | that: 45 | - docker_user_test.name == docker_user.username 46 | - docker_user_test.changed == false 47 | fail_msg: "Failed to assert the Docker user exists." 48 | 49 | - name: Get Docker & Docker Swarm info. 50 | community.docker.docker_swarm_info: 51 | ignore_errors: true 52 | register: docker_info 53 | 54 | - name: Assert Docker is installed and it's a swarm manager. 55 | assert: 56 | that: 57 | - docker_info.docker_swarm_active == true 58 | - docker_info.docker_swarm_manager == true 59 | fail_msg: "Failed to assert Docker Swarm was initialized." -------------------------------------------------------------------------------- /new-version.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | check_pending_changes() { 6 | if ! git diff-index --quiet HEAD --; then 7 | echo "❌ There are uncommitted changes in the repository." 8 | echo "👉 Please commit or stash them before running this script." 9 | exit 1 10 | fi 11 | } 12 | 13 | confirm() { 14 | read -r -p "${1:-Are you sure? [y/N]} " response 15 | case "$response" in 16 | [yY][eE][sS]|[yY]) 17 | true 18 | ;; 19 | *) 20 | false 21 | ;; 22 | esac 23 | } 24 | 25 | show_help() { 26 | echo "Version Bumper Script" 27 | echo "Usage: $0 " 28 | echo "" 29 | echo "This script is used for bumping the version number in the galaxy.yml file following semantic versioning." 30 | echo "" 31 | echo "Commands:" 32 | echo " major Bumps the major version (e.g., 1.2.3 -> 2.0.0)" 33 | echo " minor Bumps the minor version (e.g., 1.2.3 -> 1.3.0)" 34 | echo " patch Bumps the patch version (e.g., 1.2.3 -> 1.2.4)" 35 | echo " premajor Creates a pre-release major version (e.g., 1.2.3 -> 2.0.0-0)" 36 | echo " preminor Creates a pre-release minor version (e.g., 1.2.3 -> 1.3.0-0)" 37 | echo " prepatch Creates a pre-release patch version (e.g., 1.2.3 -> 1.2.4-0)" 38 | echo " prerelease Bumps the pre-release version (e.g., 1.2.3-0 -> 1.2.3-1)" 39 | echo "" 40 | echo "Examples:" 41 | echo " $0 patch # Bumps the patch version" 42 | echo " $0 minor # Bumps the minor version" 43 | echo " $0 major # Bumps the major version" 44 | echo " $0 prerelease # Bumps the prerelease version" 45 | echo "" 46 | echo "Note: Make sure that 'yq' is installed and functioning properly." 47 | } 48 | 49 | bump_version() { 50 | local version=$1 51 | local type=$2 52 | 53 | # Break the version number into its components 54 | local major=$(echo $version | cut -d. -f1) 55 | local minor=$(echo $version | cut -d. -f2) 56 | local patch=$(echo $version | cut -d. -f3) 57 | 58 | # Remove any pre-release or build metadata 59 | patch=${patch%%[-+]*} 60 | 61 | # Increment the appropriate part of the version number 62 | case $type in 63 | major) 64 | major=$((major + 1)) 65 | minor=0 66 | patch=0 67 | ;; 68 | minor) 69 | minor=$((minor + 1)) 70 | patch=0 71 | ;; 72 | patch) 73 | patch=$((patch + 1)) 74 | ;; 75 | premajor) 76 | major=$((major + 1)) 77 | minor=0 78 | patch=0 79 | version="$major.$minor.$patch-0" 80 | ;; 81 | preminor) 82 | minor=$((minor + 1)) 83 | patch=0 84 | version="$major.$minor.$patch-0" 85 | ;; 86 | prepatch) 87 | patch=$((patch + 1)) 88 | version="$major.$minor.$patch-0" 89 | ;; 90 | prerelease) 91 | if [[ $version =~ "-" ]]; then 92 | local number=$(echo $version | cut -d- -f2) 93 | number=$((number + 1)) 94 | version="$major.$minor.$patch-$number" 95 | else 96 | version="$major.$minor.$patch-0" 97 | fi 98 | ;; 99 | *) 100 | echo "Invalid version type: $type" 101 | exit 1 102 | ;; 103 | esac 104 | 105 | if [ "$type" != "prerelease" ] && [ "$type" != "premajor" ] && [ "$type" != "preminor" ] && [ "$type" != "prepatch" ]; then 106 | version="$major.$minor.$patch" 107 | fi 108 | 109 | echo $version 110 | } 111 | 112 | # Check if argument is provided 113 | if [ $# -ne 1 ]; then 114 | show_help 115 | exit 1 116 | fi 117 | 118 | check_pending_changes 119 | 120 | # Read the current version 121 | current_version=$(yq e '.version' galaxy.yml) 122 | 123 | # Bump the version 124 | new_version=$(bump_version $current_version $1) 125 | 126 | if confirm "You are about to change the version to $new_version. Do you want to continue? [y/N]"; then 127 | # Update galaxy.yml with the new version 128 | yq e ".version = \"$new_version\"" -i galaxy.yml 129 | 130 | # # Commit and tag 131 | # git add galaxy.yml 132 | # git commit -m "Bump version to $new_version" 133 | # git tag $new_version 134 | 135 | # # Push changes 136 | # git push origin main 137 | # git push origin --tags 138 | 139 | echo "🚀 Updated galaxy.yml to $new_version!" 140 | else 141 | echo "🛑 Version update aborted." 142 | exit 1 143 | fi -------------------------------------------------------------------------------- /playbooks/get_variable.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Get variable value 3 | hosts: localhost 4 | gather_facts: false 5 | tasks: 6 | - name: Display failure if variable_name is not set 7 | ansible.builtin.fail: 8 | msg: "variable_name is not set. Use -e variable_name=" 9 | when: variable_name is not defined 10 | run_once: true 11 | 12 | - name: Output variable value 13 | ansible.builtin.debug: 14 | msg: "{{ lookup('vars', variable_name) }}" 15 | when: variable_name in vars 16 | run_once: true -------------------------------------------------------------------------------- /playbooks/maintain.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Perform server maintenance tasks. 3 | hosts: "{{ target | default('all') }}" 4 | remote_user: "{{ spin_remote_user | default('root') }}" 5 | become: true 6 | vars: 7 | ansible_port: "{{ ssh_port }}" 8 | ansible_ssh_common_args: "-o IgnoreUnknown=UseKeychain -o StrictHostKeyChecking=accept-new" 9 | ansible_python_interpreter: auto_silent 10 | roles: 11 | - serversideup.spin.update_server -------------------------------------------------------------------------------- /playbooks/prepare_ci_environment.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Prepare CI environment. 3 | hosts: localhost 4 | gather_facts: false 5 | tasks: 6 | - name: Display failure if required variables are not set. 7 | ansible.builtin.fail: 8 | msg: "{{ item }} variable is not set. Use -e {{ item }}=" 9 | when: item is not defined 10 | loop: 11 | - spin_environment 12 | - spin_ci_folder 13 | tags: 14 | - always 15 | - get-host 16 | 17 | # Support for Spin v2 inventory names, add them to the new managers group 18 | - name: Add hosts from manager_servers group to managers group if it exists 19 | ansible.builtin.add_host: 20 | name: "{{ item }}" 21 | groups: "{{ spin_environment }}_managers" 22 | when: groups[spin_environment + '_manager_servers'] is defined 23 | loop: "{{ groups[spin_environment + '_manager_servers'] | default([]) }}" 24 | tags: 25 | - always 26 | - get-host 27 | 28 | - name: Validate inventory groups exist 29 | ansible.builtin.fail: 30 | msg: "Required inventory group '{{ spin_environment }}_managers' is empty or not defined. Verify your .spin.yml file or custom inventory file." 31 | when: >- 32 | groups[spin_environment + '_managers'] is not defined or 33 | groups[spin_environment + '_managers'] | length == 0 34 | tags: 35 | - always 36 | - get-host 37 | 38 | - name: Set fact of full path to CI folder 39 | ansible.builtin.set_fact: 40 | spin_ci_folder_full_path: "{{ spin_ci_folder_full_path | default('/ansible/' + spin_ci_folder) }}" 41 | tags: 42 | - always 43 | - get-host 44 | 45 | - name: Set {{ spin_environment | upper }}_SSH_REMOTE_HOSTNAME with first manager host 46 | ansible.builtin.copy: 47 | content: "{{ groups[spin_environment + '_managers'][0] }}" 48 | dest: "{{ spin_ci_folder_full_path }}/{{ spin_environment | upper }}_SSH_REMOTE_HOSTNAME" 49 | when: groups[spin_environment + '_managers'] is defined and groups[spin_environment + '_managers'] | length > 0 50 | tags: 51 | - always 52 | - get-host 53 | 54 | - name: Set AUTHORIZED_KEYS file with sudo users' SSH keys 55 | ansible.builtin.copy: 56 | content: "{{ users | selectattr('groups', 'contains', 'sudo') | map(attribute='authorized_keys') | flatten | map(attribute='public_key') | join('\n') }}\n" 57 | dest: "{{ spin_ci_folder_full_path }}/AUTHORIZED_KEYS" 58 | mode: '0600' 59 | tags: 60 | - always 61 | - get-authorized-keys 62 | 63 | - name: Run ssh-keyscan on manager hosts. 64 | ansible.builtin.shell: >- 65 | ssh-keyscan -p {{ ssh_port }} {{ groups['swarm_managers'] | join(' ') }} | sort 66 | register: keyscan_result 67 | when: groups['swarm_managers'] is defined and groups['swarm_managers'] | length > 0 68 | changed_when: false 69 | 70 | - name: Write SSH_REMOTE_KNOWN_HOSTS file 71 | ansible.builtin.copy: 72 | content: "{{ keyscan_result.stdout }}\n" 73 | dest: "{{ spin_ci_folder_full_path }}/SSH_REMOTE_KNOWN_HOSTS" 74 | mode: '0600' 75 | when: keyscan_result.stdout is defined 76 | 77 | 78 | - name: Update deploy user authorized keys. 79 | hosts: "{{ target | default('all') }}" 80 | remote_user: "{{ spin_remote_user | default('root') }}" 81 | gather_facts: false 82 | become: true 83 | vars: 84 | ansible_port: "{{ ssh_port }}" 85 | ansible_ssh_common_args: "-o IgnoreUnknown=UseKeychain -o StrictHostKeyChecking=accept-new" 86 | ansible_python_interpreter: auto_silent 87 | pre_tasks: 88 | - name: Display failure if deploy_public_key is not set. 89 | ansible.builtin.fail: 90 | msg: "deploy_public_key variable is not set. Use -e deploy_public_key=" 91 | when: deploy_public_key is not defined 92 | roles: 93 | - role: serversideup.spin.docker_user -------------------------------------------------------------------------------- /playbooks/provision.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Create servers with the VPS provider of your choice. 3 | hosts: localhost 4 | gather_facts: false 5 | vars: 6 | ansible_ssh_common_args: "-o IgnoreUnknown=UseKeychain -o StrictHostKeyChecking=accept-new" 7 | tasks: 8 | - name: Ensure providers, servers, and hardware profiles are defined 9 | ansible.builtin.fail: 10 | msg: "You have an invalid configuration in your variables file (usually '.spin.yml'). Be sure providers, servers, and hardware_profiles are defined." 11 | when: > 12 | (servers | selectattr('address', 'undefined') | list | length > 0) and 13 | (providers is not defined or 14 | providers is none or 15 | (providers | default([]) | length == 0) or 16 | hardware_profiles is not defined or 17 | hardware_profiles is none or 18 | (hardware_profiles | default([]) | length == 0)) 19 | 20 | - name: Create servers 21 | ansible.builtin.include_role: 22 | name: serversideup.spin.create_server 23 | when: servers | selectattr('address', 'undefined') | list | length > 0 24 | 25 | - name: Update newly created servers 26 | hosts: newly_created_servers 27 | gather_facts: false 28 | remote_user: "{{ initial_ssh_user | default('root') }}" 29 | become: true 30 | vars: 31 | ansible_port: "{{ ssh_port }}" 32 | ansible_ssh_common_args: "-o IgnoreUnknown=UseKeychain -o StrictHostKeyChecking=accept-new" 33 | ansible_python_interpreter: auto_silent 34 | roles: 35 | - serversideup.spin.update_server 36 | 37 | - name: Configure Docker Swarm servers. 38 | hosts: "{{ hostvars['localhost'].newly_created_servers | default([]) if hostvars['localhost'].newly_created_servers is defined else (target | default('all')) }}" 39 | remote_user: "{{ (inventory_hostname in (hostvars['localhost'].newly_created_servers | default([]))) | ternary(initial_ssh_user | default('root'), spin_remote_user | default('root')) }}" 40 | become: true 41 | vars: 42 | ansible_port: "{{ ssh_port }}" 43 | ansible_ssh_common_args: "-o IgnoreUnknown=UseKeychain -o StrictHostKeyChecking=accept-new" 44 | ansible_python_interpreter: auto_silent 45 | pre_tasks: 46 | - name: Show error if no hosts found in the target group. 47 | ansible.builtin.fail: 48 | msg: "No hosts found in the target group '{{ hostvars['localhost'].newly_created_servers | default([]) if hostvars['localhost'].newly_created_servers is defined else (target | default('all')) }}'. Check your inventory configuration." 49 | when: groups[target | default('all')] | length == 0 50 | run_once: true 51 | delegate_to: localhost 52 | 53 | - name: Show groups for current host 54 | ansible.builtin.debug: 55 | msg: 56 | - "Host: {{ inventory_hostname }}" 57 | - "Groups: {{ group_names }}" 58 | 59 | roles: 60 | - serversideup.spin.linux_common 61 | - serversideup.spin.swarm 62 | -------------------------------------------------------------------------------- /plugins/inventory/spin-dynamic-inventory.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ANSIBLE_WORK_DIR="${ANSIBLE_WORK_DIR:-$(pwd)}" 3 | ANSIBLE_VARIABLE_FILE_NAME="${ANSIBLE_VARIABLE_FILE_NAME:-".spin.yml"}" 4 | ANSIBLE_VARIABLE_FILEPATH="${ANSIBLE_VARIABLE_FILEPATH:-"${ANSIBLE_WORK_DIR}/${ANSIBLE_VARIABLE_FILE_NAME}"}" 5 | ANSIBLE_VAULT_PASSWORD_FILE="${ANSIBLE_VAULT_PASSWORD_FILE:-"${ANSIBLE_WORK_DIR}/.vault-password"}" 6 | ANSIBLE_VAULT_ENCRYPTED=false 7 | 8 | ############################################################## 9 | # Functions 10 | ############################################################## 11 | is_vault_encrypted() { 12 | local file="$1" 13 | # If already determined that a file is encrypted, return true 14 | if $ANSIBLE_VAULT_ENCRYPTED; then 15 | return 0 16 | fi 17 | 18 | # Perform the check 19 | if head -n1 "$file" | grep -q '^$ANSIBLE_VAULT;'; then 20 | if [ -f "$ANSIBLE_VAULT_PASSWORD_FILE" ]; then 21 | # Attempt to decrypt the file to validate the password 22 | if ansible-vault view --vault-password-file="$ANSIBLE_VAULT_PASSWORD_FILE" "$file" >/dev/null 2>&1; then 23 | ANSIBLE_VAULT_ENCRYPTED=true 24 | return 0 25 | else 26 | echo "[ERROR] Invalid vault password provided for file $file" 27 | exit 1 28 | fi 29 | else 30 | echo "[ERROR] Vault encrypted file found, but no vault password file found at $ANSIBLE_VAULT_PASSWORD_FILE" 31 | exit 1 32 | fi 33 | else 34 | return 1 35 | fi 36 | } 37 | 38 | yq_eval() { 39 | local query="$1" 40 | local file="$2" 41 | 42 | if is_vault_encrypted "$file"; then 43 | ansible-vault view --vault-password-file="$ANSIBLE_VAULT_PASSWORD_FILE" "$file" | yq eval "$query" - 44 | else 45 | yq eval "$query" "$file" 46 | fi 47 | } 48 | 49 | generate_inventory() { 50 | validate_inventory 51 | yq_eval -o=json "$ANSIBLE_VARIABLE_FILEPATH" | jq ' 52 | # Helper functions 53 | def remove_null_hosts: 54 | walk(if type == "object" and has("hosts") and (.hosts | all(. == null)) then del(.hosts) else . end); 55 | 56 | def add_server_to_groups($server): 57 | if $server.address and $server.environment then 58 | if ($server.environment | endswith("_workers")) then 59 | {($server.environment): {hosts: ((.[$server.environment].hosts // []) + [$server.address])}} 60 | else 61 | {($server.environment + "_managers"): {hosts: ((.[$server.environment + "_managers"].hosts // []) + [$server.address])}} 62 | end 63 | else 64 | {} 65 | end; 66 | 67 | def merge_vars($server): 68 | (.["provider_" + ($server.provider // "")].vars // {}) * 69 | (.["hardware_profile_" + ($server.hardware_profile // "")].vars // {}) * 70 | (.["environment_" + ($server.environment // "")].vars // {}) * 71 | $server; 72 | 73 | # Base structure 74 | { 75 | _meta: {hostvars: {}}, 76 | all: {children: ["ungrouped"], hosts: []}, 77 | ungrouped: {hosts: []} 78 | } as $initial_base | 79 | 80 | # Build dynamic base structure from environments 81 | (.environments // [] | reduce .[] as $env ( 82 | $initial_base; 83 | . * { 84 | ($env.name + "_managers"): {hosts: []}, 85 | ($env.name + "_workers"): {hosts: []}, 86 | ($env.name): {children: [ 87 | ($env.name + "_managers"), 88 | ($env.name + "_workers") 89 | ]}, 90 | "all": { 91 | children: (.all.children + [$env.name]) 92 | }, 93 | "swarm_managers": { 94 | children: ((.swarm_managers.children // []) + [($env.name + "_managers")]) 95 | }, 96 | "swarm_workers": { 97 | children: ((.swarm_workers.children // []) + [($env.name + "_workers")]) 98 | } 99 | } 100 | )) as $base | 101 | 102 | # Process providers 103 | ((.providers // []) | reduce .[] as $provider ( 104 | {}; 105 | . * {("provider_" + $provider.name): {vars: ($provider | del(.name))}} 106 | )) as $provider_result | 107 | 108 | # Process hardware profiles 109 | ((.hardware_profiles // []) | reduce .[] as $profile ( 110 | {}; 111 | . * { 112 | ("hardware_profile_" + $profile.name): { 113 | hosts: [], 114 | vars: $profile.profile_config 115 | }, 116 | ("provider_" + $profile.provider): { 117 | children: [("hardware_profile_" + $profile.name)] 118 | } 119 | } 120 | )) as $hardware_profile_result | 121 | 122 | # Process servers 123 | ((.servers // []) | reduce .[] as $server ( 124 | {}; 125 | if $server.address then 126 | . * { 127 | ("hardware_profile_" + ($server.hardware_profile // "")): { 128 | hosts: ( 129 | (.[("hardware_profile_" + ($server.hardware_profile // ""))].hosts // []) + 130 | [$server.address] 131 | ) 132 | }, 133 | _meta: { 134 | hostvars: { 135 | ($server.address): merge_vars($server) 136 | } 137 | } 138 | } * 139 | add_server_to_groups($server) 140 | else 141 | . 142 | end 143 | )) as $server_result | 144 | 145 | # Combine all results 146 | ($base * $provider_result * $hardware_profile_result * $server_result) | 147 | remove_null_hosts | 148 | .all.hosts = ((.servers // []) | map(select(.address)) | map(.address)) | 149 | .ungrouped.hosts = (.all.hosts - ( 150 | [ 151 | (.environments // [] | .[].name | . as $env | 152 | [([$env + "_managers", $env + "_workers"] | 153 | map(.[].hosts // [])[])] 154 | )[] 155 | ] | flatten | unique 156 | )) | 157 | # Ensure ALL groups have a hosts key with empty array if missing 158 | walk( 159 | if type == "object" and (has("children") | not) and (has("hosts") | not) then 160 | . + {hosts: []} 161 | else 162 | . 163 | end 164 | ) | 165 | # Add _meta.hostvars if not present 166 | ._meta.hostvars //= {} 167 | ' 168 | } 169 | 170 | is_valid_ipv4() { 171 | echo "$1" | awk -F. '{ 172 | if (NF != 4) exit 1 173 | for (i=1; i<=4; i++) { 174 | if ($i !~ /^[0-9]+$/ || $i < 0 || $i > 255) exit 1 175 | } 176 | exit 0 177 | }' 178 | } 179 | 180 | is_valid_ipv6() { 181 | echo "$1" | awk -F: '{ 182 | if (NF < 3 || NF > 8) exit 1 183 | for (i=1; i<=NF; i++) { 184 | if ($i !~ /^[0-9a-fA-F]{0,4}$/) exit 1 185 | } 186 | exit 0 187 | }' 188 | } 189 | 190 | validate_inventory() { 191 | file="$ANSIBLE_VARIABLE_FILEPATH" 192 | 193 | # Extract server addresses and names using the new path structure 194 | addresses=$(yq_eval '.servers[] | select(.address != null) | .address' "$file") 195 | server_names=$(yq_eval '.servers[] | select(.server_name != null) | .server_name' "$file") 196 | environments=$(yq_eval '.servers[] | select(.environment != null) | .environment' "$file") 197 | hardware_profiles=$(yq_eval '.servers[] | select(.hardware_profile != null) | .hardware_profile' "$file") 198 | 199 | # Validate server addresses 200 | invalid_addresses=$(echo "$addresses" | while read -r address; do 201 | if [ -n "$address" ] && ! (is_valid_ipv4 "$address" || is_valid_ipv6 "$address" || echo "$address" | grep -Eq '^([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$'); then 202 | echo "$address" 203 | fi 204 | done) 205 | 206 | if [ -n "$invalid_addresses" ]; then 207 | echo "[ERROR] Invalid inventory file. Invalid server addresses found:" 208 | echo "$invalid_addresses" 209 | exit 1 210 | fi 211 | 212 | # Check for unique server names 213 | duplicate_names=$(echo "$server_names" | sort | uniq -d) 214 | if [ -n "$duplicate_names" ]; then 215 | echo "[ERROR] Invalid inventory file. Duplicate server names found:" 216 | echo "$duplicate_names" 217 | exit 1 218 | fi 219 | 220 | # Check for unique server addresses (only for non-empty addresses) 221 | duplicate_addresses=$(echo "$addresses" | grep -v '^$' | sort | uniq -d) 222 | if [ -n "$duplicate_addresses" ]; then 223 | echo "[ERROR] Invalid inventory file. Duplicate server addresses found:" 224 | echo "$duplicate_addresses" 225 | exit 1 226 | fi 227 | 228 | # Validate environments against defined environments 229 | defined_environments=$(yq_eval '.environments[].name' "$file") 230 | # Create extended environment list with _workers and _managers variants 231 | extended_environments=$(echo "$defined_environments" | while read -r env; do 232 | echo "$env" 233 | echo "${env}_workers" 234 | echo "${env}_managers" 235 | done) 236 | 237 | invalid_environments=$(echo "$environments" | while read -r env; do 238 | if ! echo "$extended_environments" | grep -q "^${env}$"; then 239 | echo "$env" 240 | fi 241 | done) 242 | 243 | if [ -n "$invalid_environments" ]; then 244 | echo "[ERROR] Invalid inventory file. Undefined environments found:" 245 | echo "$invalid_environments" 246 | echo "" 247 | echo "Make sure your server environments match the defined environments in your .spin.yml file." 248 | exit 1 249 | fi 250 | 251 | # Validate hardware profiles against defined profiles 252 | defined_profiles=$(yq_eval '.hardware_profiles[].name' "$file") 253 | invalid_profiles=$(echo "$hardware_profiles" | while read -r profile; do 254 | if ! echo "$defined_profiles" | grep -q "^${profile}$"; then 255 | echo "$profile" 256 | fi 257 | done) 258 | 259 | if [ -n "$invalid_profiles" ]; then 260 | echo "[ERROR] Invalid inventory file. Undefined hardware profiles found:" 261 | echo "$invalid_profiles" 262 | exit 1 263 | fi 264 | 265 | # Validate names against Ansible standards 266 | validate_ansible_name() { 267 | local name="$1" 268 | local type="$2" 269 | if ! echo "$name" | grep -Eq '^[a-zA-Z_][a-zA-Z0-9_]*$'; then 270 | echo "$name ($type)" 271 | fi 272 | } 273 | 274 | # Check server names 275 | invalid_ansible_names=$( 276 | # Check environment names 277 | yq_eval '.environments[].name' "$file" | while read -r name; do 278 | validate_ansible_name "$name" "environment" 279 | done 280 | 281 | # Check hardware profile names 282 | yq_eval '.hardware_profiles[].name' "$file" | while read -r name; do 283 | validate_ansible_name "$name" "hardware_profile" 284 | done 285 | 286 | # Check provider names 287 | yq_eval '.providers[].name' "$file" | while read -r name; do 288 | validate_ansible_name "$name" "provider" 289 | done 290 | ) 291 | 292 | if [ -n "$invalid_ansible_names" ]; then 293 | echo "[ERROR] Invalid inventory file. Names not following Ansible standards (must start with letter/underscore, contain only letters/numbers/underscores):" 294 | echo "$invalid_ansible_names" 295 | exit 1 296 | fi 297 | } 298 | 299 | ############################################################## 300 | # Main 301 | ############################################################## 302 | 303 | case "$1" in 304 | --list|"") 305 | generate_inventory 306 | ;; 307 | --host) 308 | if [ -z "$2" ]; then 309 | echo "Usage: $0 --host " >&2 310 | exit 1 311 | fi 312 | generate_inventory | jq --arg hostname "$2" '._meta.hostvars[$hostname] // {}' 313 | ;; 314 | *) 315 | echo "Usage: $0 [--list|--host ]" >&2 316 | exit 1 317 | ;; 318 | esac 319 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | ansible 2 | molecule 3 | molecule-plugins[docker] 4 | docker -------------------------------------------------------------------------------- /roles/create_server/README.md: -------------------------------------------------------------------------------- 1 | # Server Creation Ansible Role 2 | 3 | Easily create and configure servers across multiple cloud providers (DigitalOcean, Hetzner, and Vultr). This role handles server provisioning, SSH key management, and firewall configuration automatically. 4 | 5 | ## Requirements 6 | 7 | For now, this role supports the following cloud providers: 8 | - DigitalOcean 9 | - Hetzner Cloud 10 | - Vultr 11 | 12 | You'll need API credentials for whichever provider you choose to use. 13 | 14 | ## Role Variables 15 | 16 | The role expects server configurations to be defined in your playbook or inventory. Here's an example structure: 17 | 18 | ```yaml 19 | servers: 20 | - server_name: "web-1" 21 | hardware_profile: "standard-2gb" # Must match a profile in hardware_profiles 22 | environment: "production" # Must match an environment name 23 | backups: true # Optional, defaults to true 24 | 25 | hardware_profiles: 26 | - name: "standard-2gb" 27 | provider: "digitalocean" # One of: digitalocean, hetzner, vultr 28 | profile_config: 29 | region: "nyc1" # Provider-specific configuration 30 | size: "s-2vcpu-2gb" # Varies by provider 31 | image: "ubuntu-22-04-x64" 32 | 33 | providers: 34 | - name: "digitalocean" 35 | api_token: "your_token_here" # Can also use DO_API_TOKEN env var 36 | ``` 37 | 38 | ## Environment Variables 39 | 40 | The role supports the following environment variables for API authentication: 41 | 42 | - `DO_API_TOKEN` - DigitalOcean API token 43 | - `HCLOUD_TOKEN` - Hetzner Cloud API token 44 | - `VULTR_API_KEY` - Vultr API key 45 | 46 | ## Dependencies 47 | 48 | Required Ansible collections (see `requirements.yml`): 49 | - `hetzner.hcloud` 50 | - `vultr.cloud` 51 | - `community.digitalocean` 52 | 53 | To install dependencies: 54 | ```bash 55 | ansible-galaxy install -r requirements.yml 56 | ``` 57 | 58 | ## Features 59 | 60 | - Multi-provider support (DigitalOcean, Hetzner, Vultr) 61 | - Automatic SSH key management 62 | - Standard firewall configuration across providers 63 | - IPv4 and IPv6 support 64 | - Configurable hardware profiles 65 | - Environment tagging 66 | - Backup configuration 67 | 68 | ## Example Playbook 69 | 70 | ```yaml 71 | - hosts: localhost 72 | roles: 73 | - role: create_server 74 | vars: 75 | servers: 76 | - server_name: "web-1" 77 | hardware_profile: "standard-2gb" 78 | environment: "production" 79 | 80 | hardware_profiles: 81 | - name: "standard-2gb" 82 | provider: "digitalocean" 83 | profile_config: 84 | region: "nyc1" 85 | size: "s-2vcpu-2gb" 86 | image: "ubuntu-22-04-x64" 87 | ``` 88 | 89 | ## Firewall Configuration 90 | 91 | The role automatically configures a standard firewall for web applications with the following rules: 92 | 93 | - ICMP (ping) from anywhere 94 | - SSH (port 22) from anywhere 95 | - HTTP (port 80) from anywhere 96 | - HTTPS (port 443) from anywhere 97 | - SSH tunnel (port 2222) from anywhere 98 | - All outbound traffic allowed -------------------------------------------------------------------------------- /roles/create_server/requirements.yml: -------------------------------------------------------------------------------- 1 | --- 2 | collections: 3 | - name: hetzner.hcloud 4 | - name: vultr.cloud 5 | - name: community.digitalocean 6 | -------------------------------------------------------------------------------- /roles/create_server/tasks/create-servers.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Gather sudo users with their SSH keys 3 | ansible.builtin.set_fact: 4 | sudo_users: "{{ users | selectattr('groups', 'contains', 'sudo') | list }}" 5 | 6 | - name: Get unique providers from servers 7 | ansible.builtin.set_fact: 8 | unique_providers: "{{ hardware_profiles | 9 | selectattr('name', 'in', servers_missing_addresses | map(attribute='hardware_profile') | list) | map(attribute='provider') | list }}" 10 | 11 | - name: Include provider-specific tasks 12 | ansible.builtin.include_tasks: "providers/{{ provider }}.yml" 13 | loop: "{{ unique_providers }}" 14 | loop_control: 15 | loop_var: provider 16 | vars: 17 | provider_servers: >- 18 | {%- set result = [] -%} 19 | {%- for server in servers_missing_addresses -%} 20 | {%- if server.hardware_profile in (hardware_profiles | selectattr('provider', 'equalto', provider) | map(attribute='name') | list) -%} 21 | {%- set profile_config = (hardware_profiles | selectattr('name', 'equalto', server.hardware_profile) | first).profile_config -%} 22 | {{- result.append(server | combine({'hardware_profile_config': profile_config})) -}} 23 | {%- endif -%} 24 | {%- endfor -%} 25 | {{- result -}} 26 | provider_config: "{{ providers | selectattr('name', 'equalto', provider) | first }}" 27 | 28 | - name: Write newly created server addresses to .spin.yml 29 | ansible.builtin.lineinfile: 30 | path: "{{ lookup('env', 'PWD') }}/.spin.yml" 31 | insertafter: "server_name: {{ item }}" 32 | line: " address: {{ hostvars[item].ansible_host }}" 33 | loop: "{{ groups['newly_created_servers'] }}" 34 | 35 | - name: Store newly created servers in fact 36 | ansible.builtin.set_fact: 37 | newly_created_servers: >- 38 | {{ 39 | groups['newly_created_servers'] | map('extract', hostvars) | 40 | map(attribute='ansible_host') | list 41 | }} 42 | delegate_facts: true 43 | 44 | - name: Refresh inventory 45 | ansible.builtin.meta: refresh_inventory 46 | run_once: true -------------------------------------------------------------------------------- /roles/create_server/tasks/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - name: Validate servers configuration 4 | ansible.builtin.assert: 5 | that: 6 | - item.hardware_profile is defined 7 | - item.hardware_profile | string | length > 0 8 | - item.hardware_profile in (hardware_profiles | map(attribute='name') | list) 9 | - item.environment is defined 10 | - item.environment | string | length > 0 11 | - (item.environment in (environments | map(attribute='name') | list)) or 12 | (item.environment | regex_replace('_workers$', '') in (environments | map(attribute='name') | list)) 13 | fail_msg: >- 14 | Server '{{ item.server_name }}' validation failed: 15 | {% if item.hardware_profile is not defined or not item.hardware_profile %} 16 | - Missing required 'hardware_profile' 17 | {% endif %} 18 | {% if item.hardware_profile is defined and item.hardware_profile not in (hardware_profiles | map(attribute='name') | list) %} 19 | - Invalid hardware_profile '{{ item.hardware_profile }}'. Available profiles are: {{ hardware_profiles | map(attribute='name') | list }} 20 | {% endif %} 21 | {% if item.environment is not defined or not item.environment %} 22 | - Missing required 'environment' 23 | {% endif %} 24 | {% if item.environment is defined and 25 | item.environment not in (environments | map(attribute='name') | list) and 26 | item.environment | regex_replace('_workers$', '') not in (environments | map(attribute='name') | list) %} 27 | - Invalid environment '{{ item.environment }}'. Available environments are: {{ environments | map(attribute='name') | list }} 28 | (or any of these with '_workers' suffix) 29 | {% endif %} 30 | loop: "{{ servers }}" 31 | run_once: true 32 | delegate_to: localhost 33 | 34 | - name: Check if any servers are missing an address 35 | ansible.builtin.set_fact: 36 | servers_missing_addresses: >- 37 | {{ 38 | servers | selectattr('address', 'undefined') | map('combine', { 39 | 'provider': hardware_profiles | 40 | selectattr('name', 'equalto', item.hardware_profile) | 41 | map(attribute='provider') | first 42 | }) | list 43 | }} 44 | loop: "{{ servers }}" 45 | 46 | - name: Create servers if any addresses are missing 47 | ansible.builtin.include_tasks: "create-servers.yml" 48 | when: servers_missing_addresses | length > 0 49 | -------------------------------------------------------------------------------- /roles/create_server/tasks/providers/digitalocean.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Set Digital Ocean API token 3 | ansible.builtin.set_fact: 4 | do_api_token: "{{ provider_config.api_token | default(lookup('env', 'DO_API_TOKEN')) }}" 5 | no_log: true 6 | 7 | - name: Get existing SSH keys from Digital Ocean 8 | community.digitalocean.digital_ocean_sshkey_info: 9 | oauth_token: "{{ do_api_token }}" 10 | register: do_existing_ssh_keys 11 | 12 | - name: Create SSH keys for sudo users if they don't exist in Digital Ocean 13 | community.digitalocean.digital_ocean_sshkey: 14 | oauth_token: "{{ do_api_token }}" 15 | name: "{{ item.0.username }}-{{ item.1.public_key | hash('md5') }}" 16 | ssh_pub_key: "{{ item.1.public_key }}" 17 | state: present 18 | loop: "{{ sudo_users | subelements('authorized_keys') }}" 19 | register: do_created_ssh_keys 20 | when: > 21 | item.1.public_key not in 22 | (do_existing_ssh_keys.data | map(attribute='public_key') | list) 23 | 24 | - name: Set SSH key IDs for server creation 25 | ansible.builtin.set_fact: 26 | sudo_user_do_ssh_key_fingerprints: >- 27 | {{ 28 | (do_existing_ssh_keys.data | map(attribute='fingerprint') | list) + 29 | (do_created_ssh_keys.results | selectattr('changed', 'true') | map(attribute='data.ssh_key.fingerprint') | list) 30 | }} 31 | 32 | - name: Get existing firewall configuration 33 | community.digitalocean.digital_ocean_firewall_info: 34 | oauth_token: "{{ do_api_token }}" 35 | name: "spin-web-firewall" 36 | register: existing_firewall 37 | ignore_errors: true # In case firewall doesn't exist yet 38 | 39 | - name: Create Digital Ocean droplet 40 | community.digitalocean.digital_ocean_droplet: 41 | oauth_token: "{{ do_api_token }}" 42 | name: "{{ server.server_name }}" 43 | region: "{{ server.hardware_profile_config.region }}" 44 | size: "{{ server.hardware_profile_config.size }}" 45 | image: "{{ server.hardware_profile_config.image }}" 46 | ssh_keys: "{{ sudo_user_do_ssh_key_fingerprints }}" 47 | backups: "{{ server.backups | default(true) }}" 48 | register: do_droplet 49 | loop: "{{ provider_servers }}" 50 | loop_control: 51 | loop_var: server 52 | 53 | - name: Ensure firewall exists and is assigned to droplet 54 | community.digitalocean.digital_ocean_firewall: 55 | name: "spin-web-firewall" 56 | oauth_token: "{{ do_api_token }}" 57 | droplet_ids: >- 58 | {{ 59 | (existing_firewall.data[0].droplet_ids | default([])) + 60 | (do_droplet.results | map(attribute='data.droplet.id') | list) 61 | }} 62 | inbound_rules: 63 | - protocol: icmp 64 | ports: "1-65535" 65 | sources: 66 | addresses: ["0.0.0.0/0", "::/0"] 67 | - protocol: tcp 68 | ports: "22" 69 | sources: 70 | addresses: ["0.0.0.0/0", "::/0"] 71 | - protocol: tcp 72 | ports: "80" 73 | sources: 74 | addresses: ["0.0.0.0/0", "::/0"] 75 | - protocol: tcp 76 | ports: "443" 77 | sources: 78 | addresses: ["0.0.0.0/0", "::/0"] 79 | - protocol: tcp 80 | ports: "2222" 81 | sources: 82 | addresses: ["0.0.0.0/0", "::/0"] 83 | outbound_rules: 84 | - protocol: tcp 85 | ports: "1-65535" 86 | destinations: 87 | addresses: ["0.0.0.0/0", "::/0"] 88 | - protocol: udp 89 | ports: "1-65535" 90 | destinations: 91 | addresses: ["0.0.0.0/0", "::/0"] 92 | - protocol: icmp 93 | ports: "1-65535" 94 | destinations: 95 | addresses: ["0.0.0.0/0", "::/0"] 96 | state: present 97 | 98 | - name: Validate IP addresses for created servers 99 | ansible.builtin.assert: 100 | that: 101 | - item.data.droplet.networks.v4 | length > 0 or item.data.droplet.networks.v6 | length > 0 102 | fail_msg: "Server {{ item.data.droplet.name }} has no IP addresses assigned" 103 | success_msg: "Server {{ item.data.droplet.name }} has valid IP configuration" 104 | loop: "{{ do_droplet.results }}" 105 | when: not item.skipped | default(false) 106 | 107 | - name: Set main IP address and add servers to in-memory inventory 108 | ansible.builtin.add_host: 109 | name: "{{ item.data.droplet.name }}" 110 | ansible_host: >- 111 | {{ 112 | item.data.droplet.networks.v4 | selectattr('type', 'eq', 'public') | map(attribute='ip_address') | first | 113 | default(item.data.droplet.networks.v6 | selectattr('type', 'eq', 'public') | map(attribute='ip_address') | first) 114 | }} 115 | groups: newly_created_servers 116 | loop: "{{ do_droplet.results }}" 117 | when: not item.skipped | default(false) 118 | -------------------------------------------------------------------------------- /roles/create_server/tasks/providers/hetzner.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Set Hetzner API token 3 | ansible.builtin.set_fact: 4 | hetzner_api_token: "{{ provider_config.api_token | default(lookup('env', 'HCLOUD_TOKEN')) }}" 5 | no_log: true 6 | 7 | - name: Get existing SSH keys from Hetzner Cloud 8 | hetzner.hcloud.ssh_key_info: 9 | api_token: "{{ hetzner_api_token }}" 10 | register: hetzner_existing_ssh_keys 11 | 12 | - name: Create SSH keys for sudo users if they don't exist in Hetzner Cloud 13 | hetzner.hcloud.ssh_key: 14 | api_token: "{{ hetzner_api_token }}" 15 | name: "{{ item.0.username }}-{{ item.1.public_key | hash('md5') }}" 16 | public_key: "{{ item.1.public_key }}" 17 | state: present 18 | loop: "{{ sudo_users | subelements('authorized_keys') }}" 19 | register: hetzner_created_ssh_keys 20 | when: > 21 | item.1.public_key not in 22 | (hetzner_existing_ssh_keys.hcloud_ssh_key_info | map(attribute='public_key') | map('regex_replace', '"$', '') | list) 23 | 24 | - name: Set SSH key IDs for server creation 25 | ansible.builtin.set_fact: 26 | sudo_user_hetzner_ssh_key_ids: >- 27 | {{ 28 | (hetzner_existing_ssh_keys.hcloud_ssh_key_info | map(attribute='id') | list) + 29 | (hetzner_created_ssh_keys.results | selectattr('changed', 'true') | map(attribute='hcloud_ssh_key.id') | list) 30 | }} 31 | 32 | - name: Ensure firewall exists. 33 | hetzner.hcloud.firewall: 34 | name: spin-web-firewall 35 | api_token: "{{ hetzner_api_token }}" 36 | rules: 37 | - description: allow icmp from everywhere 38 | direction: in 39 | protocol: icmp 40 | source_ips: 41 | - 0.0.0.0/0 42 | - ::/0 43 | - description: allow ssh from everywhere 44 | direction: in 45 | protocol: tcp 46 | port: 22 47 | source_ips: 48 | - 0.0.0.0/0 49 | - ::/0 50 | - description: allow http from everywhere 51 | direction: in 52 | protocol: tcp 53 | port: 80 54 | source_ips: 55 | - 0.0.0.0/0 56 | - ::/0 57 | - description: allow https from everywhere 58 | direction: in 59 | protocol: tcp 60 | port: 443 61 | source_ips: 62 | - 0.0.0.0/0 63 | - ::/0 64 | - description: allow ssh tunnel from everywhere 65 | direction: in 66 | protocol: tcp 67 | port: 2222 68 | source_ips: 69 | - 0.0.0.0/0 70 | - ::/0 71 | state: present 72 | 73 | - name: Create Hetzner server 74 | hetzner.hcloud.server: 75 | name: "{{ server.server_name }}" 76 | api_token: "{{ hetzner_api_token }}" 77 | server_type: "{{ server.hardware_profile_config.server_type }}" 78 | image: "{{ server.hardware_profile_config.image }}" 79 | location: "{{ server.hardware_profile_config.location }}" 80 | backups: "{{ server.backups | default(true) }}" 81 | ssh_keys: "{{ sudo_user_hetzner_ssh_key_ids }}" 82 | firewalls: 83 | - spin-web-firewall 84 | register: hetzner_created_servers 85 | loop: "{{ provider_servers }}" 86 | loop_control: 87 | loop_var: server 88 | 89 | - name: Validate IP addresses for created servers 90 | ansible.builtin.assert: 91 | that: 92 | - item.hcloud_server.ipv4_address is defined or item.hcloud_server.ipv6 is defined 93 | fail_msg: "Server {{ item.hcloud_server.name }} has no IP addresses assigned" 94 | success_msg: "Server {{ item.hcloud_server.name }} has valid IP configuration" 95 | loop: "{{ hetzner_created_servers.results }}" 96 | when: not item.failed 97 | 98 | - name: Set main IP address and add servers to in-memory inventory 99 | ansible.builtin.add_host: 100 | name: "{{ item.hcloud_server.name }}" 101 | ansible_host: "{{ item.hcloud_server.ipv4_address or item.hcloud_server.ipv6 }}" 102 | groups: newly_created_servers 103 | loop: "{{ hetzner_created_servers.results }}" 104 | when: not item.failed 105 | -------------------------------------------------------------------------------- /roles/create_server/tasks/providers/vultr.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Set Vultr API token 3 | ansible.builtin.set_fact: 4 | vultr_api_token: "{{ provider_config.api_token | default(lookup('env', 'VULTR_API_KEY')) }}" 5 | no_log: true 6 | 7 | - name: Get existing SSH keys from Vultr 8 | vultr.cloud.ssh_key_info: 9 | api_key: "{{ vultr_api_token }}" 10 | register: vultr_existing_ssh_keys 11 | 12 | - name: Create SSH keys for sudo users if they don't exist in Vultr 13 | vultr.cloud.ssh_key: 14 | api_key: "{{ vultr_api_token }}" 15 | name: "{{ item.0.username }}-{{ item.1.public_key | hash('md5') }}" 16 | ssh_key: "{{ item.1.public_key }}" 17 | state: present 18 | loop: "{{ sudo_users | subelements('authorized_keys') }}" 19 | register: vultr_created_ssh_keys 20 | when: > 21 | item.1.public_key not in (vultr_existing_ssh_keys.vultr_ssh_key_info | map(attribute='ssh_key') | list) 22 | 23 | - name: Set SSH key names for server creation 24 | ansible.builtin.set_fact: 25 | sudo_user_vultr_ssh_key_names: >- 26 | {{ 27 | (vultr_existing_ssh_keys.vultr_ssh_key_info | map(attribute='name') | list) + 28 | (vultr_created_ssh_keys.results | selectattr('changed', 'true') | map(attribute='vultr_ssh_key.name') | list) 29 | }} 30 | 31 | - name: Ensure firewall group is present. 32 | vultr.cloud.firewall_group: 33 | api_key: "{{ vultr_api_token }}" 34 | description: "spin-web-firewall" 35 | 36 | - name: Ensure firewall rules are present 37 | vultr.cloud.firewall_rule: 38 | api_key: "{{ vultr_api_token }}" 39 | group: "spin-web-firewall" 40 | protocol: "{{ item.protocol }}" 41 | port: "{{ item.port | default(omit) }}" 42 | ip_type: "{{ item.ip_type }}" 43 | subnet: "{{ item.subnet }}" 44 | subnet_size: "{{ item.subnet_size }}" 45 | notes: "{{ item.description }}" 46 | loop: 47 | # ICMP (IPv4) 48 | - protocol: icmp 49 | ip_type: v4 50 | subnet: "0.0.0.0" 51 | subnet_size: 0 52 | description: "allow icmp from everywhere" 53 | # ICMP (IPv6) 54 | - protocol: icmp 55 | ip_type: v6 56 | subnet: "::" 57 | subnet_size: 0 58 | description: "allow icmp from everywhere" 59 | # SSH (IPv4) 60 | - protocol: tcp 61 | port: "22" 62 | ip_type: v4 63 | subnet: "0.0.0.0" 64 | subnet_size: 0 65 | description: "allow ssh from everywhere" 66 | # SSH (IPv6) 67 | - protocol: tcp 68 | port: "22" 69 | ip_type: v6 70 | subnet: "::" 71 | subnet_size: 0 72 | description: "allow ssh from everywhere" 73 | # HTTP (IPv4) 74 | - protocol: tcp 75 | port: "80" 76 | ip_type: v4 77 | subnet: "0.0.0.0" 78 | subnet_size: 0 79 | description: "allow http from everywhere" 80 | # HTTP (IPv6) 81 | - protocol: tcp 82 | port: "80" 83 | ip_type: v6 84 | subnet: "::" 85 | subnet_size: 0 86 | description: "allow http from everywhere" 87 | # HTTPS (IPv4) 88 | - protocol: tcp 89 | port: "443" 90 | ip_type: v4 91 | subnet: "0.0.0.0" 92 | subnet_size: 0 93 | description: "allow https from everywhere" 94 | # HTTPS (IPv6) 95 | - protocol: tcp 96 | port: "443" 97 | ip_type: v6 98 | subnet: "::" 99 | subnet_size: 0 100 | description: "allow https from everywhere" 101 | # SSH Tunnel (IPv4) 102 | - protocol: tcp 103 | port: "2222" 104 | ip_type: v4 105 | subnet: "0.0.0.0" 106 | subnet_size: 0 107 | description: "allow ssh tunnel from everywhere" 108 | # SSH Tunnel (IPv6) 109 | - protocol: tcp 110 | port: "2222" 111 | ip_type: v6 112 | subnet: "::" 113 | subnet_size: 0 114 | description: "allow ssh tunnel from everywhere" 115 | 116 | - name: Create Vultr server 117 | vultr.cloud.instance: 118 | api_key: "{{ vultr_api_token }}" 119 | label: "{{ server.server_name }}" 120 | region: "{{ server.hardware_profile_config.region }}" 121 | plan: "{{ server.hardware_profile_config.plan }}" 122 | os: "{{ server.hardware_profile_config.os }}" 123 | backups: "{{ server.backups | default(true) }}" 124 | ssh_keys: "{{ sudo_user_vultr_ssh_key_names }}" 125 | firewall_group: "spin-web-firewall" 126 | activation_email: "{{ server.hardware_profile_config.activation_email | default(true) }}" 127 | tags: "{{ server.environment | default('') }}" 128 | register: vultr_created_servers 129 | loop: "{{ provider_servers }}" 130 | loop_control: 131 | loop_var: server 132 | 133 | - name: Validate IP addresses for created servers 134 | ansible.builtin.assert: 135 | that: 136 | - item.vultr_instance.main_ip is defined 137 | fail_msg: "Server {{ item.vultr_instance.label }} has no IP addresses assigned" 138 | success_msg: "Server {{ item.vultr_instance.label }} has valid IP configuration" 139 | loop: "{{ vultr_created_servers.results }}" 140 | when: not item.failed 141 | 142 | - name: Set main IP address and add servers to in-memory inventory 143 | ansible.builtin.add_host: 144 | name: "{{ item.vultr_instance.label }}" 145 | ansible_host: "{{ item.vultr_instance.main_ip }}" 146 | groups: newly_created_servers 147 | loop: "{{ vultr_created_servers.results }}" 148 | when: not item.failed 149 | -------------------------------------------------------------------------------- /roles/docker_user/README.md: -------------------------------------------------------------------------------- 1 | # Docker User Ansible Role 2 | 3 | Create and configure a dedicated user for Docker operations with proper permissions and SSH access. This role handles user creation, group management, and SSH key configuration. 4 | 5 | ## Requirements 6 | 7 | This role is designed to work on Unix-like systems that support user and group management. It requires: 8 | - Ansible 2.9 or higher 9 | - Root or sudo access on the target system 10 | 11 | ## Role Variables 12 | 13 | All configuration is handled through the `docker_user` dictionary in `defaults/main.yml`: 14 | 15 | ```yaml 16 | docker_user: 17 | username: deploy # Username for the Docker user 18 | uid: 9999 # User ID 19 | group: deploy # Primary group name 20 | secondary_groups: "docker" # Additional groups (comma-separated) 21 | gid: 9999 # Group ID 22 | # Optional: Configure SSH keys directly in vars 23 | # authorized_ssh_keys: 24 | # - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKNJGtd7a4DBHsQi7HGrC5xz0eAEFHZ3Ogh3FEFI2345 fake@key" 25 | ``` 26 | 27 | The role also supports these additional variables: 28 | - `deploy_public_key`: SSH public key added via "spin configure" command 29 | - `users`: List of admin/sudo users whose SSH keys should be added to the Docker user 30 | 31 | ## Dependencies 32 | 33 | Required Ansible collections (see `requirements.yml`): 34 | ```yaml 35 | collections: 36 | - name: ansible.posix 37 | ``` 38 | 39 | To install dependencies: 40 | ```bash 41 | ansible-galaxy install -r requirements.yml 42 | ``` 43 | 44 | ## Features 45 | 46 | - Creates a dedicated user for Docker operations 47 | - Configures primary and secondary group memberships 48 | - Manages SSH key access through multiple methods: 49 | - Direct configuration via `authorized_ssh_keys` 50 | - Integration with "spin configure" command 51 | - Automatic import of admin/sudo users' SSH keys 52 | - Customizable user/group IDs and home directory 53 | - Bash shell configuration 54 | 55 | ## Example Playbook 56 | 57 | Basic usage: 58 | ```yaml 59 | - hosts: servers 60 | roles: 61 | - role: docker_user 62 | ``` 63 | 64 | With custom configuration: 65 | ```yaml 66 | - hosts: servers 67 | roles: 68 | - role: docker_user 69 | vars: 70 | docker_user: 71 | username: dockerops 72 | uid: 8888 73 | group: dockerops 74 | secondary_groups: "docker,www-data" 75 | gid: 8888 76 | authorized_ssh_keys: 77 | - "ssh-ed25519 AAAAC3... user@host" 78 | ``` 79 | 80 | ## SSH Key Management 81 | 82 | The role supports three methods for SSH key management, in order of precedence: 83 | 84 | 1. Keys specified in `docker_user.authorized_ssh_keys` 85 | 2. Key provided via `deploy_public_key` variable 86 | 3. SSH keys from users with sudo privileges 87 | 88 | All valid keys will be added to the Docker user's `authorized_keys` file. -------------------------------------------------------------------------------- /roles/docker_user/defaults/main.yml: -------------------------------------------------------------------------------- 1 | docker_user: 2 | username: deploy 3 | uid: 9999 4 | group: deploy 5 | secondary_groups: "docker" 6 | gid: 9999 7 | ## Uncomment to set authorized SSH keys for the docker user. 8 | # authorized_ssh_keys: 9 | # - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKNJGtd7a4DBHsQi7HGrC5xz0eAEFHZ3Ogh3FEFI2345 fake@key" 10 | # - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFRfXxUZ8q9vHRcQZ6tLb0KwGHu8xjQHfYopZKLmnopQ anotherfake@key" 11 | -------------------------------------------------------------------------------- /roles/docker_user/requirements.yml: -------------------------------------------------------------------------------- 1 | --- 2 | collections: 3 | - name: ansible.posix -------------------------------------------------------------------------------- /roles/docker_user/tasks/main.yml: -------------------------------------------------------------------------------- 1 | - name: Ensure the Docker user's group exists with the correct GID. 2 | ansible.builtin.group: 3 | name: "{{ docker_user.group | default('deploy') }}" 4 | gid: "{{ docker_user.gid | default('9999') }}" 5 | state: present 6 | 7 | - name: Ensure the Docker user is created. 8 | ansible.builtin.user: 9 | name: "{{ docker_user.username }}" 10 | create_home: yes 11 | group: "{{ docker_user.group | default('deploy') }}" 12 | groups: "{{ docker_user.secondary_groups | default('docker') }}" 13 | home: "{{ docker_user.home | default(omit) }}" 14 | shell: /bin/bash 15 | state: present 16 | system: no 17 | uid: "{{ docker_user.uid | default('9999') }}" 18 | 19 | - name: Set the authorized SSH keys for the Docker user from the variable file. 20 | ansible.posix.authorized_key: 21 | user: "{{ docker_user.username }}" 22 | state: present 23 | key: "{{ item }}" 24 | with_items: "{{ docker_user.authorized_ssh_keys }}" 25 | when: docker_user.authorized_ssh_keys is defined 26 | 27 | - name: Set the authorized SSH keys for the Docker user from the "spin configure" command. 28 | ansible.posix.authorized_key: 29 | user: "{{ docker_user.username }}" 30 | state: present 31 | key: "{{ deploy_public_key }}" 32 | when: deploy_public_key is defined 33 | 34 | - name: Add public keys of admin or sudo users to Docker user 35 | ansible.posix.authorized_key: 36 | user: "{{ docker_user.username }}" 37 | state: present 38 | key: "{{ item.authorized_keys.0.public_key }}" 39 | loop: "{{ users }}" 40 | when: "'sudo' in item.groups" -------------------------------------------------------------------------------- /roles/linux_common/README.md: -------------------------------------------------------------------------------- 1 | Linux Common 2 | ========= 3 | 4 | A simple playbook to secure your server, prep your users, and prepare your server for other uses. 5 | 6 | Requirements 7 | ------------ 8 | 9 | For now, this project focuses on supporting **Ubuntu 22.04** only. Choose any host that you'd like. All this role needs is an SSH connection to a user that has `sudo` privileges. 10 | 11 | Role Variables 12 | -------------- 13 | 14 | You can find all variables organized and documented in `defaults/main.yml`. Feel free to override any variable of your choice. 15 | 16 | ```yml 17 | --- 18 | ########################################### 19 | # Basic Server Configuration 20 | ########################################### 21 | server_timezone: "Etc/UTC" 22 | server_contact: changeme@example.com 23 | 24 | # SSH 25 | ssh_port: "22" 26 | 27 | ## Email Notifications 28 | postfix_hostname: "{{ inventory_hostname }}" 29 | 30 | ## Set variables below to enable external SMTP relay 31 | # postfix_relayhost: "smtp.example.com" 32 | # postfix_relayhost_port: "587" 33 | # postfix_relayhost_username: "myusername" 34 | # postfix_relayhost_password: "mysupersecretpassword" 35 | 36 | ########################################### 37 | # Install Packages Configuration 38 | ########################################### 39 | 40 | # Base packages that will always be installed 41 | common_installed_packages: 42 | - cron 43 | - curl 44 | - figlet 45 | - fail2ban 46 | - git 47 | - htop 48 | - logrotate 49 | - mailutils 50 | - ncdu 51 | - ntp 52 | - python3-minimal 53 | - python3-pip 54 | - ssh 55 | - tzdata 56 | - ufw 57 | - unattended-upgrades 58 | - unzip 59 | - wget 60 | - zip 61 | 62 | # Additional packages that users can define 63 | common_additional_packages: 64 | - python3-jsondiff 65 | - python3-yaml 66 | 67 | # PIP - Python Packages (examples below if you need them) 68 | # pip_packages: 69 | # - jsondiff 70 | # - pyyaml 71 | 72 | # APT - Automatic Update Configuration 73 | apt_periodic_update_package_lists: "1" 74 | apt_periodic_download_upgradeable_packages: "1" 75 | apt_periodic_autoclean_interval: "7" 76 | apt_periodic_unattended_upgrade: "1" 77 | 78 | ########################################### 79 | # Fun Terminal Customizations 80 | ########################################### 81 | motd_header_text: "ServerSideUp" 82 | motd_header_text_color: '\e[38;5;255m' 83 | motd_header_background_color: '\e[48;5;34m' 84 | motd_hostname_text_color: '\e[38;5;202m' 85 | motd_services: 86 | - ufw 87 | - fail2ban 88 | - postfix 89 | 90 | ############################################################## 91 | # Users 92 | ############################################################## 93 | 94 | ### Use the template below to set users and their authorized keys 95 | ## Passwords must be set with an encrypted hash. To do this, see the Ansible FAQ 96 | ## https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#how-do-i-generate-encrypted-passwords-for-the-user-module 97 | 98 | # users: 99 | # - username: alice 100 | # name: Alice Smith 101 | # state: present 102 | # groups: ['adm','sudo'] 103 | # password: "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1" 104 | # shell: "/bin/bash" 105 | # authorized_keys: 106 | # - public_key: "ssh-ed25519 AAAAC3NzaC1lmyfakeublickeyMVIzwQXBzxxD9b8Erd1FKVvu alice" 107 | 108 | # - username: bob 109 | # name: Bob Smith 110 | # state: present 111 | # password: "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1" 112 | # groups: ['adm','sudo'] 113 | # shell: "/bin/bash" 114 | # authorized_keys: 115 | # - public_key: "ssh-ed25519 AAAAC3NzaC1anotherfakekeyIMVIzwQXBzxxD9b8Erd1FKVvu bob" 116 | 117 | ### Additional users 118 | ## You can also set additional users (great if you're working with contractors or clients on certain groups of servers) 119 | ## These users will be flattened into the users list (if you set any settings below) 120 | 121 | # additional_users: 122 | # - username: charlie 123 | # name: Charlie Smith 124 | # state: present 125 | # groups: ['adm','sudo'] 126 | # password: "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1" 127 | # shell: "/bin/bash" 128 | # authorized_keys: 129 | # - public_key: "ssh-ed25519 AAAAC3NzaC1lmyfakeublickeyMVIzwQXBzxxD9b8Erd1FKVvu alice" 130 | 131 | # - username: dana 132 | # name: Dana Smith 133 | # state: present 134 | # password: "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1" 135 | # groups: ['adm','sudo'] 136 | # shell: "/bin/bash" 137 | # authorized_keys: 138 | # - public_key: "ssh-ed25519 AAAAC3NzaC1anotherfakekeyIMVIzwQXBzxxD9b8Erd1FKVvu bob" 139 | ``` 140 | 141 | Dependencies 142 | ------------ 143 | See [`requirements.yml`](./requirements.yml) for all collection dependencies. 144 | 145 | To install all dependencies, run: 146 | 147 | ```bash 148 | ansible-galaxy install -r requirements.yml 149 | ``` 150 | 151 | Example Playbook 152 | ---------------- 153 | 154 | ```yml 155 | - hosts: servers 156 | roles: 157 | - { role: serversideup.spin.linux_common, server_timezone: 'America/Chicago' } 158 | ``` -------------------------------------------------------------------------------- /roles/linux_common/defaults/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | ########################################### 3 | # Basic Server Configuration 4 | ########################################### 5 | server_timezone: "Etc/UTC" 6 | server_contact: changeme@example.com 7 | 8 | # SSH 9 | ssh_port: "22" 10 | ssh_permit_root_login: "no" 11 | ssh_password_authentication: "no" 12 | ssh_allow_tcp_forwarding: "yes" 13 | ssh_gateway_ports: "yes" 14 | 15 | 16 | ## Email Notifications 17 | postfix_hostname: "{{ inventory_hostname }}" 18 | 19 | ## Set variables below to enable external SMTP relay 20 | # postfix_relayhost: "smtp.example.com" 21 | # postfix_relayhost_port: "587" 22 | # postfix_relayhost_username: "myusername" 23 | # postfix_relayhost_password: "mysupersecretpassword" 24 | 25 | ########################################### 26 | # Install Packages Configuration 27 | ########################################### 28 | 29 | # Base packages that will always be installed 30 | common_installed_packages: 31 | - cron 32 | - curl 33 | - figlet 34 | - fail2ban 35 | - git 36 | - htop 37 | - logrotate 38 | - mailutils 39 | - ncdu 40 | - ntp 41 | - python3-minimal 42 | - python3-pip 43 | - ssh 44 | - tzdata 45 | - ufw 46 | - unattended-upgrades 47 | - unzip 48 | - wget 49 | - zip 50 | 51 | # Additional packages that users can define 52 | common_additional_packages: [] 53 | 54 | # PIP - Python Packages (examples below if you need them) 55 | 56 | # pip_packages: 57 | # - jsondiff 58 | # - pyyaml 59 | 60 | # APT - Automatic Update Configuration 61 | apt_periodic_update_package_lists: "1" 62 | apt_periodic_download_upgradeable_packages: "1" 63 | apt_periodic_autoclean_interval: "7" 64 | apt_periodic_unattended_upgrade: "1" 65 | 66 | ########################################### 67 | # Fun Terminal Customizations 68 | ########################################### 69 | motd_header_text: "Spin" 70 | motd_header_text_color: '\e[38;5;255m' 71 | motd_header_background_color: '\e[48;5;34m' 72 | motd_hostname_text_color: '\e[38;5;202m' 73 | motd_services: 74 | - ufw 75 | - fail2ban 76 | - postfix 77 | 78 | ############################################################## 79 | # Users 80 | ############################################################## 81 | 82 | ### Use the template below to set users and their authorized keys 83 | ## Passwords must be set with an encrypted hash. To do this, see the Ansible FAQ 84 | ## https://docs.ansible.com/ansible/latest/reference_appendices/faq.html#how-do-i-generate-encrypted-passwords-for-the-user-module 85 | 86 | # users: 87 | # - username: alice 88 | # name: Alice Smith 89 | # state: present 90 | # groups: ['adm','sudo'] 91 | # password: "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1" 92 | # shell: "/bin/bash" 93 | # authorized_keys: 94 | # - public_key: "ssh-ed25519 AAAAC3NzaC1lmyfakeublickeyMVIzwQXBzxxD9b8Erd1FKVvu alice" 95 | 96 | # - username: bob 97 | # name: Bob Smith 98 | # state: present 99 | # password: "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1" 100 | # groups: ['adm','sudo'] 101 | # shell: "/bin/bash" 102 | # authorized_keys: 103 | # - public_key: "ssh-ed25519 AAAAC3NzaC1anotherfakekeyIMVIzwQXBzxxD9b8Erd1FKVvu bob" 104 | 105 | ### Additional users 106 | ## You can also set additional users (great if you're working with contractors or clients on certain groups of servers) 107 | ## These users will be flattened into the users list (if you set any settings below) 108 | 109 | # additional_users: 110 | # - username: charlie 111 | # name: Charlie Smith 112 | # state: present 113 | # groups: ['adm','sudo'] 114 | # password: "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1" 115 | # shell: "/bin/bash" 116 | # authorized_keys: 117 | # - public_key: "ssh-ed25519 AAAAC3NzaC1lmyfakeublickeyMVIzwQXBzxxD9b8Erd1FKVvu alice" 118 | 119 | # - username: dana 120 | # name: Dana Smith 121 | # state: present 122 | # password: "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1" 123 | # groups: ['adm','sudo'] 124 | # shell: "/bin/bash" 125 | # authorized_keys: 126 | # - public_key: "ssh-ed25519 AAAAC3NzaC1anotherfakekeyIMVIzwQXBzxxD9b8Erd1FKVvu bob" -------------------------------------------------------------------------------- /roles/linux_common/handlers/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Create postmap hash 3 | ansible.builtin.command: postmap /etc/postfix/sasl_passwd 4 | when: postfix_relayhost is defined 5 | notify: Restart postfix 6 | 7 | - name: Enable ufw 8 | community.general.ufw: 9 | state: enabled 10 | 11 | - name: Restart cron 12 | ansible.builtin.service: 13 | name: cron 14 | state: restarted 15 | 16 | - name: Restart postfix 17 | ansible.builtin.service: 18 | name: postfix 19 | state: restarted 20 | 21 | - name: Restart ssh 22 | ansible.builtin.service: 23 | name: ssh 24 | state: restarted 25 | 26 | - name: Run newaliases 27 | ansible.builtin.command: newaliases -------------------------------------------------------------------------------- /roles/linux_common/requirements.yml: -------------------------------------------------------------------------------- 1 | --- 2 | collections: 3 | - name: ansible.posix 4 | - name: community.general -------------------------------------------------------------------------------- /roles/linux_common/tasks/email-alerts.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Disable Postfix port listening. 3 | ansible.builtin.lineinfile: 4 | dest: /etc/postfix/main.cf 5 | regexp: ^inet_interfaces 6 | line: "inet_interfaces = loopback-only" 7 | state: present 8 | backrefs: yes 9 | notify: Restart postfix 10 | 11 | - name: Configure Postfix hostname. 12 | ansible.builtin.lineinfile: 13 | dest: /etc/postfix/main.cf 14 | regexp: ^myhostname 15 | line: "myhostname = {{ postfix_hostname }}" 16 | state: present 17 | backrefs: yes 18 | notify: Restart postfix 19 | when: not postfix_hostname is match("^\d{1,3}(\.\d{1,3}){3}$") # If not an IP address. 20 | 21 | - name: Prevent Postfix from listening on ports. 22 | ansible.builtin.lineinfile: 23 | dest: /etc/postfix/master.cf 24 | regexp: ^smtp inet 25 | line: "#smtp inet" 26 | state: present 27 | backrefs: yes 28 | notify: Restart postfix 29 | 30 | - name: Configure Postfix relayhost (if set). 31 | ansible.builtin.lineinfile: 32 | dest: /etc/postfix/main.cf 33 | regexp: ^relayhost 34 | line: "relayhost = [{{ postfix_relayhost }}]:{{ postfix_relayhost_port }}" 35 | state: present 36 | backrefs: yes 37 | notify: Restart postfix 38 | when: postfix_relayhost is defined 39 | 40 | - name: Set Postfix Sasl password (if set). 41 | ansible.builtin.lineinfile: 42 | dest: /etc/postfix/sasl_passwd 43 | regexp: ^\[{{ postfix_relayhost }}\]:{{ postfix_relayhost_port }} 44 | line: "[{{ postfix_relayhost }}]:{{ postfix_relayhost_port }} {{ postfix_relayhost_username }}:{{ postfix_relayhost_password }}" 45 | state: present 46 | backrefs: yes 47 | notify: Create postmap hash 48 | when: postfix_relayhost is defined 49 | 50 | - name: Set Postfix aliases for root user email notifications. 51 | ansible.builtin.lineinfile: 52 | dest: /etc/aliases 53 | regexp: "^root:" 54 | line: "root: {{ server_contact }}" 55 | notify: Run newaliases -------------------------------------------------------------------------------- /roles/linux_common/tasks/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Validate inputs. 3 | ansible.builtin.import_tasks: validate-inputs.yml 4 | 5 | - name: Set up Debian (when OS is Debian based) 6 | ansible.builtin.include_tasks: setup-Debian.yml 7 | when: ansible_os_family == 'Debian' 8 | 9 | - name: Configure email alerts. 10 | ansible.builtin.include_tasks: email-alerts.yml 11 | 12 | - name: Setup MOTD. 13 | ansible.builtin.include_tasks: motd.yml 14 | 15 | - name: Apply security policies to the server. 16 | ansible.builtin.include_tasks: security.yml 17 | 18 | - name: Configure server users. 19 | ansible.builtin.include_tasks: users.yml -------------------------------------------------------------------------------- /roles/linux_common/tasks/motd.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Remove any unnecessary MOTD files 3 | ansible.builtin.file: 4 | path: "{{ item }}" 5 | state: absent 6 | with_items: 7 | - "/etc/motd" 8 | - "/etc/update-motd.d/10-help-text" 9 | - "/etc/update-motd.d/50-motd-news" 10 | - "/etc/update-motd.d/51-cloudguest" 11 | - "/etc/update-motd.d/80-livepatch" 12 | 13 | - name: Apply custom MOTD messages 14 | ansible.builtin.template: 15 | src: "etc/update-motd.d/{{ item }}.j2" 16 | dest: "/etc/update-motd.d/{{ item }}" 17 | mode: 0755 18 | with_items: 19 | - 30-motd-header 20 | - 35-sysinfo 21 | - 40-services -------------------------------------------------------------------------------- /roles/linux_common/tasks/security.yml: -------------------------------------------------------------------------------- 1 | - name: Ensure SSH configurations are up to date. 2 | ansible.builtin.template: 3 | src: "etc/ssh/sshd_config.d/{{ item }}.j2" 4 | dest: "/etc/ssh/sshd_config.d/{{ item }}" 5 | owner: root 6 | group: root 7 | mode: 0600 8 | notify: Restart ssh 9 | with_items: 10 | - 01-spin-secure-ssh.conf 11 | - 02-spin-ssh-tunnels.conf 12 | 13 | - name: Ensure PermitRootLogin is removed from sshd_config 14 | ansible.builtin.lineinfile: 15 | path: /etc/ssh/sshd_config 16 | regexp: '^PermitRootLogin' 17 | state: absent 18 | notify: Restart ssh 19 | 20 | - name: Configure sudo access for sudo group 21 | ansible.builtin.lineinfile: 22 | dest: /etc/sudoers 23 | state: "{{ 'present' if use_passwordless_sudo | default(false) else 'absent' }}" 24 | regexp: '^%sudo\s+ALL=\(ALL\)\s+NOPASSWD:\s+ALL' 25 | line: '%sudo ALL=(ALL) NOPASSWD: ALL' 26 | validate: '/usr/sbin/visudo -cf %s' 27 | 28 | - name: Open the firewall port for SSH. 29 | community.general.ufw: 30 | rule: allow 31 | port: "{{ ssh_port }}" 32 | proto: "tcp" 33 | comment: "Allow SSH connections." 34 | notify: Enable ufw 35 | 36 | - name: Ensure umask is set in /etc/login.defs 37 | ansible.builtin.lineinfile: 38 | path: /etc/login.defs 39 | regexp: '^UMASK' 40 | line: 'UMASK 022' 41 | state: present 42 | 43 | - name: Disable USERGROUPS_ENAB in /etc/login.defs 44 | ansible.builtin.lineinfile: 45 | path: /etc/login.defs 46 | regexp: '^USERGROUPS_ENAB' 47 | line: 'USERGROUPS_ENAB no' 48 | state: present 49 | 50 | - name: Set umask in /etc/profile 51 | ansible.builtin.lineinfile: 52 | path: /etc/profile 53 | line: 'umask 022' 54 | state: present -------------------------------------------------------------------------------- /roles/linux_common/tasks/setup-Debian.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Install latest versions of common packages. 3 | ansible.builtin.apt: 4 | name: "{{ common_installed_packages + common_additional_packages }}" 5 | state: latest 6 | update_cache: yes 7 | 8 | - name: Install Python PIP packages (if defined). 9 | ansible.builtin.pip: 10 | name: "{{ pip_packages }}" 11 | state: latest 12 | when: pip_packages is defined 13 | 14 | # Related GitHub issue: https://github.com/geerlingguy/docker-ubuntu2404-ansible/issues/2 15 | - name: Ensure Python system warning is removed. 16 | ansible.builtin.file: 17 | path: /usr/lib/python3.12/EXTERNALLY-MANAGED 18 | state: absent 19 | 20 | - name: Configure server to automatically install security updates. 21 | ansible.builtin.template: 22 | src: "etc/apt/apt.conf.d/{{ item }}.j2" 23 | dest: "/etc/apt/apt.conf.d/{{ item }}" 24 | owner: root 25 | group: root 26 | mode: 0644 27 | with_items: 28 | - 20auto-upgrades 29 | - 50unattended-upgrades 30 | 31 | - name: "Set timezone to {{ server_timezone }}." 32 | community.general.timezone: 33 | name: "{{ server_timezone }}" 34 | notify: Restart cron -------------------------------------------------------------------------------- /roles/linux_common/tasks/users.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Set users variable when there are NOT any additional users. 3 | ansible.builtin.set_fact: 4 | flattend_users: "{{ users }}" 5 | when: additional_users is not defined 6 | 7 | - name: Set users variable when there ARE additional users. 8 | ansible.builtin.set_fact: 9 | flattend_users: "{{ users + additional_users }}" 10 | when: additional_users is defined 11 | 12 | - name: Configure users. 13 | ansible.builtin.user: 14 | name: '{{ item.username }}' 15 | comment: '{{ item.name | default(omit) }}' 16 | groups: '{{ item.groups | join(",") | default(omit) }}' 17 | home: '{{ item.homedir | default(omit) }}' 18 | password: '{{ item.password | default(omit) }}' 19 | shell: '{{ item.shell | default("/bin/bash") }}' 20 | state: '{{ item.state | default("present") }}' 21 | uid: '{{ item.uid | default(omit) }}' 22 | update_password: '{{ item.update_password | default("on_create") }}' 23 | with_items: "{{ flattend_users }}" 24 | register: created_users 25 | 26 | - name: Force password change on next login. 27 | ansible.builtin.command: chage -d 0 {{ item.item.username }} 28 | with_items: "{{ created_users.results }}" 29 | when: 30 | - item.changed 31 | - item.item.password is defined 32 | - item.item.password | length > 0 33 | 34 | - name: Configure authorized keys. 35 | ansible.posix.authorized_key: 36 | user: '{{item.0.username}}' 37 | key: '{{item.1.public_key}}' 38 | state: '{{item.1.state | default ("present")}}' 39 | with_subelements: 40 | - "{{ flattend_users }}" 41 | - authorized_keys 42 | - skip_missing: true 43 | when: item.0.state | default("present") != 'absent' -------------------------------------------------------------------------------- /roles/linux_common/tasks/validate-inputs.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | - name: Show error if no users are set. 4 | ansible.builtin.fail: 5 | msg: "No users are set. You must set at least one user under 'users' or 'additional_users' in '.spin.yml'." 6 | when: > 7 | ((users | default([])) + (additional_users | default([]))) | length == 0 8 | run_once: true 9 | delegate_to: localhost 10 | connection: local 11 | 12 | - name: Show error if user is missing a password and passwordless sudo is disabled. 13 | ansible.builtin.fail: 14 | msg: "User '{{ item.username }}' is missing a password. Passwords are required for sudo users when passwordless sudo is disabled." 15 | when: 16 | - not use_passwordless_sudo | default(true) 17 | - "'sudo' in (item.groups | default([]))" 18 | - item.password is not defined or item.password | length == 0 19 | loop: "{{ users + additional_users | default([]) }}" 20 | loop_control: 21 | label: "{{ item.username }}" 22 | run_once: true 23 | delegate_to: localhost 24 | connection: local 25 | 26 | - name: Show error if no users belong to the sudo group. 27 | ansible.builtin.fail: 28 | msg: "No users are assigned to the sudo group. At least one user must belong to the sudo group." 29 | when: > 30 | ((users | default([])) + (additional_users | default([]))) | selectattr('groups', 'defined') | 31 | selectattr('groups', 'contains', 'sudo') | list | length == 0 32 | run_once: true 33 | delegate_to: localhost 34 | connection: local 35 | 36 | - name: Show warning if server_contact is unchanged. 37 | ansible.builtin.assert: 38 | that: 39 | - server_contact is defined 40 | - server_contact != 'changeme@example.com' 41 | fail_msg: "⚠️ WARNING: The server_contact is set to the default value. Please update it with a valid contact email." 42 | success_msg: "✅ Server notifications will be sent to {{ server_contact }}" 43 | register: server_contact_check 44 | failed_when: false 45 | changed_when: server_contact_check is failed 46 | run_once: true 47 | delegate_to: localhost 48 | connection: local 49 | 50 | - name: Display warning if server_contact is not changed 51 | ansible.builtin.debug: 52 | msg: "{{ server_contact_check.fail_msg }}" 53 | when: server_contact_check is failed 54 | run_once: true 55 | delegate_to: localhost 56 | connection: local 57 | -------------------------------------------------------------------------------- /roles/linux_common/templates/etc/apt/apt.conf.d/20auto-upgrades.j2: -------------------------------------------------------------------------------- 1 | APT::Periodic::Update-Package-Lists "{{ apt_periodic_update_package_lists }}"; 2 | APT::Periodic::Download-Upgradeable-Packages "{{ apt_periodic_download_upgradeable_packages }}"; 3 | APT::Periodic::AutocleanInterval "{{ apt_periodic_autoclean_interval }}"; 4 | APT::Periodic::Unattended-Upgrade "{{ apt_periodic_unattended_upgrade }}"; -------------------------------------------------------------------------------- /roles/linux_common/templates/etc/apt/apt.conf.d/50unattended-upgrades.j2: -------------------------------------------------------------------------------- 1 | // Automatically upgrade packages from these (origin, archive) pairs 2 | Unattended-Upgrade::Allowed-Origins { 3 | // ${distro_id} and ${distro_codename} will be automatically expanded 4 | "${distro_id} stable"; 5 | "${distro_id} ${distro_codename}-security"; 6 | // "${distro_id} ${distro_codename}-updates"; 7 | // "${distro_id} ${distro_codename}-proposed-updates"; 8 | }; 9 | 10 | // List of packages to not update 11 | Unattended-Upgrade::Package-Blacklist { 12 | // "vim"; 13 | // "libc6"; 14 | // "libc6-dev"; 15 | // "libc6-i686"; 16 | }; 17 | 18 | // Send email to this address for problems or packages upgrades 19 | // If empty or unset then no email is sent, make sure that you 20 | // have a working mail setup on your system. The package 'mailx' 21 | // must be installed or anything that provides /usr/bin/mail. 22 | Unattended-Upgrade::Mail "{{ server_contact }}"; 23 | 24 | // Do automatic removal of new unused dependencies after the upgrade 25 | // (equivalent to apt-get autoremove) 26 | //Unattended-Upgrade::Remove-Unused-Dependencies "false"; 27 | 28 | // Automatically reboot *WITHOUT CONFIRMATION* if a 29 | // the file /var/run/reboot-required is found after the upgrade 30 | //Unattended-Upgrade::Automatic-Reboot "false"; -------------------------------------------------------------------------------- /roles/linux_common/templates/etc/ssh/sshd_config.d/01-spin-secure-ssh.conf.j2: -------------------------------------------------------------------------------- 1 | # {{ ansible_managed }} 2 | Port {{ ssh_port }} 3 | PermitRootLogin {{ ssh_permit_root_login }} 4 | PasswordAuthentication {{ ssh_password_authentication }} -------------------------------------------------------------------------------- /roles/linux_common/templates/etc/ssh/sshd_config.d/02-spin-ssh-tunnels.conf.j2: -------------------------------------------------------------------------------- 1 | # {{ ansible_managed }} 2 | AllowTcpForwarding {{ ssh_allow_tcp_forwarding }} 3 | GatewayPorts {{ ssh_gateway_ports }} -------------------------------------------------------------------------------- /roles/linux_common/templates/etc/update-motd.d/30-motd-header.j2: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Set colors 4 | HEADER_TEXT_COLOR="{{ motd_header_text_color }}" 5 | HEADER_BACKGROUND_COLOR="{{ motd_header_background_color }}" 6 | HOSTNAME_TEXT_COLOR=" {{ motd_hostname_text_color }}" 7 | 8 | STOP="\e[0m" 9 | 10 | # Configure header colors 11 | printf "${HEADER_BACKGROUND_COLOR}" 12 | printf "${HEADER_TEXT_COLOR}" 13 | printf "\n" 14 | 15 | # Print header text 16 | /usr/bin/env figlet "{{ motd_header_text }}" 17 | printf "Brought to you by serversideup.net" 18 | 19 | #Reset Terminal color 20 | printf "${STOP}" 21 | printf "\n" 22 | 23 | #Start showing the host name 24 | printf "You are connected to: " 25 | 26 | # Set color to organge & print hostname 27 | printf "${HOSTNAME_TEXT_COLOR}" 28 | printf "$(hostname)" 29 | 30 | #Reset Terminal color 31 | printf "${STOP}" 32 | printf "\n" 33 | -------------------------------------------------------------------------------- /roles/linux_common/templates/etc/update-motd.d/35-sysinfo.j2: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # get load averages 4 | IFS=" " read LOAD1 LOAD5 LOAD15 <<<$(cat /proc/loadavg | awk '{ print $1,$2,$3 }') 5 | # get free memory 6 | IFS=" " read USED FREE TOTAL <<<$(free -htm | grep "Mem" | awk {'print $3,$4,$2'}) 7 | # get processes 8 | PROCESS=`ps -eo user=|sort|uniq -c | awk '{ print $2 " " $1 }'` 9 | PROCESS_ALL=`echo "$PROCESS"| awk {'print $2'} | awk '{ SUM += $1} END { print SUM }'` 10 | PROCESS_ROOT=`echo "$PROCESS"| grep root | awk {'print $2'}` 11 | PROCESS_USER=`echo "$PROCESS"| grep -v root | awk {'print $2'} | awk '{ SUM += $1} END { print SUM }'` 12 | 13 | W="\e[0;39m" 14 | G="\e[1;32m" 15 | 16 | echo -e " 17 | ${W}system info: 18 | $W Distro......: $W`cat /etc/*release | grep "PRETTY_NAME" | cut -d "=" -f 2- | sed 's/"//g'` 19 | $W Kernel......: $W`uname -sr` 20 | $W Uptime......: $W`uptime -p` 21 | $W Load........: $G$LOAD1$W (1m), $G$LOAD5$W (5m), $G$LOAD15$W (15m) 22 | $W Processes...:$W $G$PROCESS_ROOT$W (root), $G$PROCESS_USER$W (user) | $G$PROCESS_ALL$W (total) 23 | $W CPU.........: $W`cat /proc/cpuinfo | grep "model name" | cut -d ' ' -f3- | awk {'print $0'} | head -1` 24 | $W Memory......: $G$USED$W used, $G$FREE$W free, $G$TOTAL$W in total$W" 25 | -------------------------------------------------------------------------------- /roles/linux_common/templates/etc/update-motd.d/40-services.j2: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # set column width 4 | COLUMNS=3 5 | # colors 6 | green="\e[1;32m" 7 | red="\e[1;31m" 8 | undim="\e[0m" 9 | 10 | # Load services from local file 11 | services=({{ motd_services | join(' ') }}) 12 | 13 | # sort services 14 | IFS=$'\n' services=($(sort <<<"${services[*]}")) 15 | unset IFS 16 | 17 | service_status=() 18 | # get status of all services 19 | for service in "${services[@]}"; do 20 | service_status+=($(systemctl is-active "$service")) 21 | done 22 | 23 | out="" 24 | for i in ${!services[@]}; do 25 | # color green if service is active, else red 26 | if [[ "${service_status[$i]}" == "active" ]]; then 27 | out+="${services[$i]}:,${green}${service_status[$i]}${undim}," 28 | else 29 | out+="${services[$i]}:,${red}${service_status[$i]}${undim}," 30 | fi 31 | # insert \n every $COLUMNS column 32 | if [ $((($i+1) % $COLUMNS)) -eq 0 ]; then 33 | out+="\n" 34 | fi 35 | done 36 | out+="\n" 37 | 38 | printf "\nservices:\n" 39 | printf "$out" | column -ts $',' | sed -e 's/^/ /' 40 | -------------------------------------------------------------------------------- /roles/linux_common/vars/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | # vars file for linux_common 3 | -------------------------------------------------------------------------------- /roles/swarm/README.md: -------------------------------------------------------------------------------- 1 | # Docker Swarm Ansible Role 2 | 3 | Deploy and maintain Docker Swarm servers easily. This role was inspired by [Jeff Geerling](https://github.com/geerlingguy), but expanded to support Docker Swarm. Please support his amazing work! 4 | 5 | ## Requirements 6 | 7 | For now, this project focuses on supporting **Ubuntu 22.04** only. Choose any host that you'd like. All this role needs is an SSH connection to a user that has `sudo` privileges. 8 | 9 | ## Role Variables 10 | 11 | You can find all variables organized and documented in `defaults/main.yml`. Feel free to override any variable of your choice. 12 | 13 | ```yml 14 | --- 15 | # Edition can be one of: 'ce' (Community Edition) or 'ee' (Enterprise Edition). 16 | docker_edition: 'ce' 17 | 18 | # Docker repo URL. 19 | docker_repo_url: https://download.docker.com/linux 20 | 21 | # Used only for Debian/Ubuntu. Switch 'stable' to 'nightly' if needed. 22 | docker_apt_release_channel: stable 23 | docker_apt_arch: "{{ 'arm64' if ansible_architecture == 'aarch64' else 'amd64' }}" 24 | docker_apt_repository: "deb [arch={{ docker_apt_arch }} signed-by=/etc/apt/trusted.gpg.d/docker.asc] {{ docker_repo_url }}/{{ ansible_distribution | lower }} {{ ansible_distribution_release }} {{ docker_apt_release_channel }}" 25 | docker_apt_ignore_key_error: true 26 | docker_apt_gpg_key: "{{ docker_repo_url }}/{{ ansible_distribution | lower }}/gpg" 27 | docker_apt_gpg_key_checksum: "sha256:1500c1f56fa9e26b9b8f42452a553675796ade0807cdce11975eb98170b3a570" 28 | 29 | # Docker user configuration. 30 | docker_user: 31 | username: deploy 32 | uid: 9999 33 | group: deploy 34 | secondary_groups: "docker" 35 | gid: 9999 36 | ## Uncomment to set authorized SSH keys for the docker user. 37 | # authorized_ssh_keys: 38 | # - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKNJGtd7a4DBHsQi7HGrC5xz0eAEFHZ3Ogh3FEFI2345 fake@key" 39 | # - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFRfXxUZ8q9vHRcQZ6tLb0KwGHu8xjQHfYopZKLmnopQ anotherfake@key" 40 | ``` 41 | 42 | ### Dependencies 43 | See [`requirements.yml`](./requirements.yml) for all collection dependencies. 44 | 45 | To install all dependencies, run: 46 | 47 | ```bash 48 | ansible-galaxy install -r requirements.yml 49 | ``` 50 | 51 | ## Example Playbook 52 | ```yml 53 | - hosts: servers 54 | roles: 55 | - role: serversideup.spin.docker_swarm 56 | ``` 57 | 58 | ## Adding a Swarm Manager 59 | In order to create a new swarm, you must have a group in your inventory called `swarm_managers`. This group should contain all of the hosts that you want to be managers. You can have as many managers as you want, but you must have at least one. -------------------------------------------------------------------------------- /roles/swarm/defaults/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | ############################################################## 3 | # Security 4 | ############################################################## 5 | automatically_open_http_and_https_ports: true 6 | 7 | ############################################################## 8 | # Docker 9 | ############################################################## 10 | 11 | # Edition can be one of: 'ce' (Community Edition) or 'ee' (Enterprise Edition). 12 | docker_edition: 'ce' 13 | 14 | # Docker repo URL. 15 | docker_repo_url: https://download.docker.com/linux 16 | 17 | # Used only for Debian/Ubuntu. Switch 'stable' to 'nightly' if needed. 18 | docker_apt_release_channel: stable 19 | docker_apt_arch: "{{ 'arm64' if ansible_architecture == 'aarch64' else 'amd64' }}" 20 | docker_apt_repository: "deb [arch={{ docker_apt_arch }} signed-by=/etc/apt/trusted.gpg.d/docker.asc] {{ docker_repo_url }}/{{ ansible_distribution | lower }} {{ ansible_distribution_release }} {{ docker_apt_release_channel }}" 21 | docker_apt_ignore_key_error: true 22 | docker_apt_gpg_key: "{{ docker_repo_url }}/{{ ansible_distribution | lower }}/gpg" 23 | docker_apt_gpg_key_checksum: "sha256:1500c1f56fa9e26b9b8f42452a553675796ade0807cdce11975eb98170b3a570" 24 | 25 | # Docker Swarm configuration. 26 | docker_swarm: 27 | # Use "default_ipv4.address" and fail to first available IP if not set. 28 | advertise_addr: "{{ ansible_default_ipv4.address | default(ansible_default_ipv6.address | default(ansible_all_ipv4_addresses[0] | default(ansible_all_ipv6_addresses[0]))) }}" 29 | 30 | ############################################################## 31 | # Users 32 | ############################################################## 33 | 34 | ### Use the template below to set users and their authorized keys 35 | ## Passwords are optional if you use passwordless sudo. If you do 36 | ## use passwords, you must be set with an encrypted hash. You can 37 | ## generate an encrypted hash with `spin mkpasswd`. Learn more: 38 | ## https://serversideup.net/open-source/spin/docs/command-reference/mkpasswd 39 | 40 | # users: 41 | # - username: alice 42 | # name: Alice Smith 43 | # state: present 44 | # groups: ['adm','sudo'] 45 | # password: "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1" 46 | # shell: "/bin/bash" 47 | # authorized_keys: 48 | # - public_key: "ssh-ed25519 AAAAC3NzaC1lmyfakeublickeyMVIzwQXBzxxD9b8Erd1FKVvu alice" 49 | 50 | # - username: bob 51 | # name: Bob Smith 52 | # state: present 53 | # password: "$6$mysecretsalt$qJbapG68nyRab3gxvKWPUcs2g3t0oMHSHMnSKecYNpSi3CuZm.GbBqXO8BE6EI6P1JUefhA0qvD7b5LSh./PU1" 54 | # groups: ['adm','sudo'] 55 | # shell: "/bin/bash" 56 | # authorized_keys: 57 | # - public_key: "ssh-ed25519 AAAAC3NzaC1anotherfakekeyIMVIzwQXBzxxD9b8Erd1FKVvu bob" -------------------------------------------------------------------------------- /roles/swarm/handlers/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Enable ufw 3 | community.general.ufw: 4 | state: enabled 5 | 6 | - name: Restart docker 7 | ansible.builtin.service: 8 | name: docker 9 | state: "restarted" -------------------------------------------------------------------------------- /roles/swarm/requirements.yml: -------------------------------------------------------------------------------- 1 | --- 2 | collections: 3 | - name: community.docker 4 | - name: community.general 5 | 6 | roles: 7 | - name: serversideup.spin.docker_user -------------------------------------------------------------------------------- /roles/swarm/tasks/configure-swarm.yml: -------------------------------------------------------------------------------- 1 | - name: Initialize Docker Swarm. 2 | community.docker.docker_swarm: 3 | state: present 4 | advertise_addr: "{{ docker_swarm.advertise_addr }}" 5 | when: "'swarm_managers' in group_names" 6 | 7 | - name: Open HTTP and HTTPS ports (if enabled) 8 | community.general.ufw: 9 | rule: allow 10 | port: "{{ item }}" 11 | proto: "tcp" 12 | comment: "Allow HTTP connections." 13 | loop: 14 | - "80" 15 | - "443" 16 | when: automatically_open_http_and_https_ports | bool 17 | notify: Enable ufw -------------------------------------------------------------------------------- /roles/swarm/tasks/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Install Docker (when OS is Debian based) 3 | ansible.builtin.include_tasks: setup-Debian.yml 4 | when: ansible_os_family == 'Debian' 5 | tags: install-docker 6 | 7 | - name: Configure Docker User. 8 | ansible.builtin.include_role: 9 | name: serversideup.spin.docker_user 10 | 11 | - name: Configure Docker Swarm Mode. 12 | ansible.builtin.include_tasks: configure-swarm.yml 13 | 14 | - name: Set CRON for Docker system prune. 15 | ansible.builtin.cron: 16 | name: "Prune unused Docker images, containers, and networks" 17 | minute: "0" 18 | hour: "4" 19 | job: "/usr/bin/docker system prune --all --force" 20 | -------------------------------------------------------------------------------- /roles/swarm/tasks/setup-Debian.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Ensure old versions of Docker are not installed. 3 | ansible.builtin.apt: 4 | name: 5 | - docker 6 | - docker-engine 7 | state: absent 8 | 9 | - name: Ensure 'docker' python package is installed. 10 | ansible.builtin.pip: 11 | name: docker 12 | state: latest 13 | 14 | - name: Ensure dependencies are installed. 15 | ansible.builtin.apt: 16 | name: 17 | - apt-transport-https 18 | - ca-certificates 19 | - curl 20 | - gnupg 21 | state: present 22 | 23 | - name: Add Docker apt key. 24 | ansible.builtin.get_url: 25 | url: "{{ docker_apt_gpg_key }}" 26 | dest: /etc/apt/trusted.gpg.d/docker.asc 27 | mode: '0644' 28 | force: false 29 | checksum: "{{ docker_apt_gpg_key_checksum | default(omit) }}" 30 | register: add_repository_key 31 | ignore_errors: "{{ docker_apt_ignore_key_error }}" 32 | 33 | - name: Add Docker repository. 34 | ansible.builtin.apt_repository: 35 | repo: "{{ docker_apt_repository }}" 36 | state: present 37 | update_cache: true 38 | 39 | - name: Install Docker packages. 40 | ansible.builtin.apt: 41 | name: 42 | - "docker-{{ docker_edition }}" 43 | - "docker-{{ docker_edition }}-cli" 44 | - "containerd.io" 45 | - "docker-buildx-plugin" 46 | - "docker-compose-plugin" 47 | state: present 48 | notify: Restart docker 49 | 50 | - name: Ensure Docker is started and enabled at boot. 51 | ansible.builtin.service: 52 | name: "{{ item }}" 53 | state: started 54 | enabled: true 55 | loop: 56 | - docker 57 | - containerd 58 | -------------------------------------------------------------------------------- /roles/update_server/README.md: -------------------------------------------------------------------------------- 1 | # Server Update Ansible Role 2 | 3 | A simple but robust role to safely update Ubuntu servers, handling package updates and automatic reboots when required. This role includes connection checking and proper wait times to ensure system stability. 4 | 5 | ## Requirements 6 | 7 | - Target system must be Ubuntu/Debian-based (uses `apt` package manager) 8 | - SSH access with sudo privileges 9 | - Ansible 2.9 or higher 10 | 11 | ## Role Features 12 | 13 | - Updates package cache 14 | - Performs full system upgrade 15 | - Removes unnecessary packages (autoremove) 16 | - Cleans package cache (autoclean) 17 | - Automatically handles required reboots 18 | - Includes connection checking before and after updates 19 | - Configurable timeout values 20 | 21 | ## Role Behavior 22 | 23 | 1. Verifies SSH connection is available (5-minute timeout) 24 | 2. Updates and upgrades all system packages 25 | 3. Checks if a system reboot is required 26 | 4. Performs automatic reboot if necessary 27 | 5. Waits for system to come back online 28 | 6. Verifies SSH connection is re-established 29 | 30 | ## Configuration 31 | 32 | The role uses these default timeout values: 33 | ```yaml 34 | # Initial connection timeout (in seconds) 35 | connection_timeout: 300 36 | 37 | # Package manager lock timeout (in seconds) 38 | lock_timeout: 600 39 | 40 | # Reboot timeout (in seconds) 41 | reboot_timeout: 600 42 | ``` 43 | 44 | ## Example Playbook 45 | 46 | Basic usage: 47 | ```yaml 48 | - hosts: servers 49 | roles: 50 | - role: update_server 51 | ``` 52 | 53 | With custom timeouts: 54 | ```yaml 55 | - hosts: servers 56 | roles: 57 | - role: update_server 58 | vars: 59 | connection_timeout: 600 # 10 minutes 60 | lock_timeout: 1200 # 20 minutes 61 | reboot_timeout: 900 # 15 minutes 62 | ``` 63 | 64 | ## Important Notes 65 | 66 | - The update process may take several minutes depending on: 67 | - Server performance 68 | - Network connection speed 69 | - Number of packages to update 70 | - Whether a reboot is required 71 | - The role includes appropriate wait times and connection checks to prevent SSH disconnection issues 72 | - If the server requires a reboot, the role will handle it automatically 73 | - The role is idempotent and can be run multiple times safely 74 | 75 | ## Dependencies 76 | 77 | This role has no external dependencies beyond core Ansible modules. -------------------------------------------------------------------------------- /roles/update_server/tasks/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - name: Ensure SSH connection is established (wait up to 5 minutes) 3 | ansible.builtin.wait_for_connection: 4 | timeout: 300 5 | 6 | - name: Update and upgrade all packages (this might take a while depending on your host and server's performance) 7 | ansible.builtin.apt: 8 | update_cache: yes 9 | upgrade: yes 10 | autoremove: yes 11 | autoclean: yes 12 | lock_timeout: 600 13 | become: true 14 | 15 | - name: Check if reboot is required 16 | ansible.builtin.stat: 17 | path: /var/run/reboot-required 18 | register: reboot_required 19 | become: true 20 | 21 | - name: Reboot server if required 22 | ansible.builtin.reboot: 23 | reboot_timeout: 600 24 | become: true 25 | when: reboot_required.stat.exists 26 | register: reboot_result 27 | 28 | - name: Wait for SSH connection after reboot (wait up to 5 minutes) 29 | ansible.builtin.wait_for_connection: 30 | timeout: 300 31 | when: reboot_result.changed --------------------------------------------------------------------------------