start
Ansible - controle du code / controle (push) Failing after 5m47s
Ansible - controle du code / promouvoir (push) Skipped

This commit is contained in:
hcornet committed 2026-09-15 17:09:39 +02:00
1 parent 4b8bb1427a
commit 975d3e9d1d
84 files changed
+2507 -351

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
profile: production
exclude_paths:
- .gitea/
+4
View File
@@ -0,0 +1,4 @@
* text=auto eol=lf
*.sh text eol=lf
*.yml text eol=lf
*.j2 text eol=lf
+73
View File
@@ -0,0 +1,73 @@
name: Ansible - controle du code
on:
pull_request:
branches: [main]
push:
branches: [main]
jobs:
controle:
runs-on: ubuntu-latest
steps:
- name: Récupérer le dépôt
uses: actions/checkout@v4
- name: Installer les outils
run: |
set -euo pipefail
if ! command -v pip3 >/dev/null; then
apt-get update -qq
apt-get install -y -qq python3-pip
fi
pip3 install --quiet --break-system-packages ansible-core ansible-lint yamllint
ansible-galaxy collection install -r collections/requirements.yml -p collections
ansible --version | head -n 1
- name: Contrôler la mise en forme YAML
run: yamllint .
- name: Vérifier la syntaxe du playbook
run: |
set -euo pipefail
# vault.yml est chiffré : un fichier de substitution suffit au syntax-check.
[ -f group_vars/all/vault.yml ] || cp group_vars/all/vault.yml.example group_vars/all/vault.yml
ansible-playbook site.yml --syntax-check
ansible-playbook site.yml --list-tasks > /dev/null
- name: Passer ansible-lint
run: ansible-lint
- name: Vérifier que chaque compte SSH a au moins une clé
run: |
set -euo pipefail
manquants=0
for d in files/keys/*/; do
[ -d "$d" ] || continue
n=$(find "$d" -name '*.pub' | wc -l)
echo "$(basename "$d") : $n clé(s)"
[ "$n" -gt 0 ] || manquants=1
done
[ "$manquants" -eq 0 ] || { echo "Un répertoire de files/keys/ est vide"; exit 1; }
promouvoir:
# Semaphore suit la branche « valide » : elle n'avance que depuis « main », après contrôle réussi.
needs: controle
if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push'
runs-on: ubuntu-latest
steps:
- name: Récupérer le dépôt
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.GITEA_TOKEN_PROMOTION }}
- name: Pousser main vers valide
run: |
set -euo pipefail
git config user.name "gitea-actions"
git config user.email "[email protected]"
git push origin HEAD:refs/heads/valide
echo "Branche valide -> $(git rev-parse --short HEAD)"
-36
View File
@@ -1,36 +0,0 @@
name: Run ansible
on:
push:
schedule:
- cron: "0 */12 * * *"
jobs:
run-ansible-playbook:
runs-on: ubuntu-latest
steps:
- name: Check out repository code
uses: actions/checkout@v4
- name: Install ansible
run: |
apt update && apt install ansible -y
- name: Run playbook
uses: dawidd6/action-ansible-playbook@v2
with:
playbook: playbooks/main.yml
requirements: requirements.yml
options: |
--inventory inventory
- name: Send failure notification
uses: dawidd6/action-send-mail@v3
if: always() && failure()
with:
server_address: smtp.gmail.com
server_port: 465
secure: true
username: myuser
password: ${{ secrets.MAIL_PASSWORD }}
subject: ansible runbook failed
to: [email protected]
from: RFD Notify
body: |
${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}
+5 -14
View File
@@ -1,14 +1,5 @@
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
*.retry
.vault_pass
.cache/
# group_vars/all/vault.yml n'est PAS ignoré : chiffré par ansible-vault,
# il doit être versionné pour que Semaphore y ait accès.
+20
View File
@@ -0,0 +1,20 @@
---
extends: default
ignore: |
.gitea/
rules:
line-length:
max: 160
document-start: disable
comments-indentation: disable
comments:
min-spaces-from-content: 1
braces:
max-spaces-inside: 1
octal-values:
forbid-implicit-octal: true
forbid-explicit-octal: true
truthy:
allowed-values: ["true", "false"]
+66
View File
@@ -0,0 +1,66 @@
# CI/CD — dépôt `ansible-hardening-linux`
Même principe qu'`ansible-centreon` : Gitea **contrôle** le code, Semaphore **l'exécute**.
Une différence : Semaphore ne suit pas `main` mais la branche **`valide`**, qui n'avance
que depuis `main` et seulement après un contrôle réussi. Un commit qui casse le lint
n'atteint donc jamais Semaphore.
```
push / PR sur main ──► controle : yamllint, syntax-check, ansible-lint, clés présentes
│ succès (push sur main uniquement)
▼
promouvoir : main ──► valide
│
▼
Semaphore (dépôt sur branche « valide ») exécute site.yml
```
## Contrôle du code — Gitea Actions
`.gitea/workflows/ansible-lint.yml`, job `controle`, sur chaque pull request et chaque
push vers `main` :
| Étape | Ce qu'elle attrape |
|---|---|
| `yamllint .` | indentation, lignes trop longues, valeurs booléennes douteuses |
| `ansible-playbook site.yml --syntax-check` + `--list-tasks` | playbook ou rôle cassé, tâche mal formée, variable manquante dans les rôles |
| `ansible-lint` | mauvaises pratiques, modules dépréciés, tâches sans `changed_when` — profil `production` |
| clés présentes | un répertoire `files/keys/<compte>/` sans fichier `.pub` verrouillerait ce compte |
`vault.yml` étant chiffré, le syntax-check utilise `vault.yml.example` à sa place si le
mot de passe n'est pas disponible dans la CI (il ne l'est pas, volontairement).
## Promotion — job `promouvoir`
Sur un push validé sur `main`, le job pousse le même commit sur `valide`. Il lui faut :
- un secret de dépôt **`GITEA_TOKEN_PROMOTION`** : jeton d'un compte (de préférence un
compte technique) autorisé à écrire sur `valide` ;
- la branche `valide` **protégée** dans Gitea, avec ce seul compte en liste blanche de
push, pour qu'aucun humain ne puisse y pousser directement.
## Exécution — Semaphore
À créer une fois dans le projet Semaphore :
- **Dépôt** : l'URL Gitea de `ansible-hardening-linux`, branche **`valide`**.
- **Clé SSH** : la clé privée du compte de connexion (`ansible` avec sudo, ou `root`
comme sur les VM Terraform). Sa clé publique doit figurer dans
`files/keys/<compte>/` — c'est ce que vérifie le rôle `ssh` avant de durcir.
- **Mot de passe du vault** : entrée dédiée du magasin de clés, pointée par le modèle
de tâche, ou `ANSIBLE_VAULT_PASSWORD_FILE` dans l'environnement du modèle.
- **Inventaire** : `inventory/hosts.yml` du dépôt (versionné), ou un inventaire
Semaphore si les hôtes changent souvent.
- **Modèle `Simulation`** : `site.yml` avec `--check --diff` — à utiliser pour tout
premier passage sur un hôte.
- **Modèle `Configuration`** : `site.yml`.
- **Modèle `SSH seul`** : `site.yml --tags ssh`, pratique pour la rotation des clés.
Semaphore installe les collections de `collections/requirements.yml` avant chaque exécution.
## Secrets
Rien de secret ne transite par Gitea : les communautés SNMP et les mots de passe SNMPv3
sont dans `group_vars/all/vault.yml`, chiffré, et seul Semaphore détient le mot de passe
du vault. Les clés publiques SSH et les certificats racine sont versionnés en clair :
ce sont des éléments publics.
-235
View File
@@ -1,235 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
Template-Ansible
Copyright (C) 2024 Tips-Of-Mine
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
+105 -55
View File
@@ -1,75 +1,125 @@
# ${REPO_NAME}
# ansible-hardening-linux
${REPO_DESCRIPTION}
Configuration et durcissement de serveurs Linux — Debian 12/13, Ubuntu 22.04/24.04,
RHEL / Rocky / AlmaLinux 8 et 9 — par Ansible. Reprise du dépôt de scripts
`prerequis-install-deb` (Debian uniquement, copie de fichiers à la main) sous
forme de rôles idempotents, multi-distributions, avec CI/CD Gitea.
# A propos de
Objectif : à la fin d'un passage, tout serveur est configuré, à jour, supervisé,
et **n'est joignable à distance qu'en SSH par clé publique** ; l'accès local
(console, `su -`) continue de fonctionner comme avant.
# Prérequis
## Correspondance avec les scripts d'origine
Vous avez besoin d'une installation Ansible fonctionnelle sur votre machine.
| Script d'origine | Rôle | Ce qui change |
|---|---|---|
| `01-ssh` (sshd_config, ssh_config, banner, authorized_keys, 00-basic) | `ssh` | Drop-in `sshd_config.d/00-durcissement.conf` au lieu d'écraser tout le fichier ; clé publique obligatoire (`AuthenticationMethods publickey`) ; `AllowUsers` calculé depuis la liste des comptes ; clés centralisées dans `/etc/ssh/authorized_keys/<user>` (le lien symbolique de l'ancien script est remplacé par des fichiers appartenant à root) ; bannière dans `/etc/issue.net` et `/etc/issue` ; MOTD `00-basic` conservé, rendu portable, et équivalent `profile.d` sous Red Hat ; vérification d'une **nouvelle** connexion SSH avant de rendre la main |
| `02-apt` (proxy + full-upgrade) | `proxy`, `updates` | Proxy APT **et** DNF, plus `profile.d` ; mises à jour de sécurité automatiques (`unattended-upgrades` / `dnf-automatic`) ; signalement du besoin de redémarrage |
| `04-agent-glpi` | `glpi_agent` (+ `common` pour le certificat) | Installateur perl officiel, version pilotée par variable, configuration dans `conf.d/10-ansible.cfg` ; le certificat racine va dans le magasin système (`update-ca-certificates` / `update-ca-trust`) et sert à tout le monde, pas seulement à l'agent |
| `06-snmp` | `snmp` | Communautés v2c par source de supervision, lues depuis le vault ; SNMPv3 disponible ; vue en lecture seule |
| `07-DNS` | `dns` | Respecte le gestionnaire réel : `systemd-resolved` (drop-in), NetworkManager (`dns=none` puis `resolv.conf`), ou `resolv.conf` direct |
| `08-NRPE` | `nrpe` | Installation **et** configuration : `allowed_hosts`, `dont_blame_nrpe=0`, commandes de base |
| `03-cortex`, `05-manageengine` | — | Ignorés à la demande |
| *(absent)* | `firewall` | nftables (Debian/Ubuntu) ou firewalld (Red Hat), politique `drop` : SSH depuis les réseaux d'administration, ICMP, SNMP/NRPE depuis la supervision |
| *(absent)* | `fail2ban` | Bannissement des sources en échec sur SSH, backend `systemd` |
| *(absent)* | `os_hardening` | sysctl, core dumps, `login.defs`, auditd, services et paquets inutiles |
| *(absent)* | `common` | Contrôle de la distribution, paquets de base, fuseau, certificats racine |
~~~bash
./install-ansible.sh
~~~
## Ce qui garantit que l'accès local reste possible
## Edition du fichier Hosts
~~~bash
sudo nano /etc/ansible/hosts
~~~
- Aucun mot de passe n'est verrouillé, aucun compte n'est désactivé, PAM n'est pas modifié.
- `PermitRootLogin prohibit-password` : root n'est joignable à distance que par clé,
mais son mot de passe reste valable sur la console (Proxmox, KVM, iLO…) et pour `su -`.
- Le pare-feu ne filtre que le réseau ; la console n'est pas concernée.
- fail2ban ne bannit que des adresses IP distantes ; les réseaux d'administration sont
dans `ignoreip`.
- Deux garde-fous contre l'auto-verrouillage : le rôle `ssh` refuse une configuration
où le compte utilisé par Ansible n'aurait pas de clé ou ne serait pas dans `AllowUsers`,
et le rôle `firewall` refuse une liste `firewall_ssh_sources` qui exclurait l'adresse
depuis laquelle Ansible est connecté. Après chaque redémarrage de sshd et après
chaque application du pare-feu, une **nouvelle** session SSH est ouverte depuis le
contrôleur ; si elle échoue, le playbook s'arrête sans fermer la session courante.
## Creation clé SSH
~~~bash
ssh-keygen -t ed25519 -C "ansible"
~~~
## Arborescence
## Permissions clé SSH
~~~bash
chmod 600 ~/.ssh/ansible
~~~
Même organisation qu'`ansible-centreon` : playbook et `group_vars` à la racine,
inventaire et vault versionnés, collections déclarées dans `collections/`.
## Ping Command Ansible
~~~bash
ansible all -m ping
~~~
```
.
├── ansible.cfg
├── site.yml # point d'entrée
├── collections/requirements.yml # ansible.posix, community.general (installées par Semaphore)
├── inventory/hosts.yml # inventaire versionné
├── group_vars/all/
│ ├── main.yml # réseaux, DNS, proxy, comptes, supervision, activation des rôles
│ └── vault.yml.example # à copier vers vault.yml, chiffrer, puis versionner
├── files/
│ ├── keys/<utilisateur>/*.pub # clés publiques SSH (versionnées)
│ └── ca/*.crt # certificats racine internes (versionnés)
├── roles/ # common, proxy, dns, updates, ssh, firewall, fail2ban,
│ # os_hardening, snmp, nrpe, glpi_agent
├── .gitea/workflows/ansible-lint.yml
└── CICD.md # chaîne Gitea (contrôle) -> Semaphore (exécution)
```
## Copier clé SSH
~~~bash
ssh-copy-id -i ~/.ssh/ansible.pub 10.0.4.150
~~~
## Mise en route
## Ping Command Ansible avec nouvelle clé SSH
~~~bash
ansible all -m ping --key-file ~/.ssh/ansible
~~~
1. **Inventaire** : renseigner `inventory/hosts.yml`. Deux modes de connexion :
- compte de service `ansible` + sudo (`become` est activé dans `ansible.cfg`) ;
- root par clé, comme sur les VM Terraform : `ansible_user: root`, `become` est alors sans effet.
2. **Clés publiques** : un répertoire par compte dans `files/keys/`, un ou plusieurs
fichiers `*.pub` dedans. Le compte utilisé par Ansible **doit** y avoir une clé.
3. **Certificat racine** (facultatif) : `files/ca/root-ca.crt` au format PEM.
4. **Secrets** : `cp group_vars/all/vault.yml.example group_vars/all/vault.yml`,
renseigner, puis `ansible-vault encrypt group_vars/all/vault.yml`.
5. **Variables** : relire `group_vars/all/main.yml` — en particulier
`firewall_ssh_sources` (réseaux d'administration), `supervision_sources`,
`dns_nameservers`, `proxy_url`, `ssh_users`, `glpi_agent_server`.
6. **Simulation** : `ansible-playbook site.yml --check --diff --ask-vault-pass`
7. **Application** : `ansible-playbook site.yml --ask-vault-pass`
# Démarrage
Un seul rôle : `--tags ssh`, `--tags firewall`, etc. Un rôle peut aussi être
désactivé par variable (`enable_<rôle>: false`) au niveau global, d'un groupe ou d'un hôte.
~~~bash
git clone https://gitea.tips-of-mine.com${REPO_LINK}.git
cd ${REPO_NAME}
~~~
## Ordre d'exécution et raison
## Personnalisation
`common` → `proxy` → `dns` → `updates` → `ssh` → `firewall` → `fail2ban` →
`os_hardening` → `snmp` → `nrpe` → `glpi_agent`.
Le fichier .env pour les variable d'environnement
~~~bash
nano .env
~~~
Le proxy et le DNS viennent d'abord (sans eux, aucun paquet ne se télécharge) ; le SSH
est durci avant le pare-feu (la règle SSH doit exister avant que la politique passe à
`drop`) ; la supervision et l'agent GLPI viennent en dernier, une fois le système stable.
Modification des labels pour traefik
~~~bash
nano docker-compose.yml
~~~
## Points d'attention par distribution
## Lancement
- **Ubuntu 22.10+** : sshd est activé par socket (`ssh.socket`). Le rôle bascule sur
`ssh.service` pour que `Port` soit pris en compte depuis `sshd_config`.
- **Red Hat / Rocky / Alma** : les algorithmes SSH ne sont pas définis dans `sshd_config`
(ils viennent de `crypto-policies`) ; fail2ban, NRPE et les greffons Nagios viennent
d'EPEL, installé par `common`. SELinux : le port SSH est déclaré si différent de 22.
- **Red Hat 8 (OpenSSH 8.0)** : pas de directive `Include` ; le durcissement est inséré
en tête de `sshd_config` entre des marqueurs, et les directives contradictoires du
fichier d'origine sont commentées.
- **VM issues de `terraform-proxmox-serveur-debian-12`** : le jeu nftables et le drop-in
sshd sont compatibles avec ceux posés par cloud-init (même structure, même
répertoire `/etc/nftables.d/`). Le drop-in Ansible `00-durcissement.conf` passe avant
`99-durcissement.conf` de cloud-init : c'est Ansible qui a le dernier mot.
~~~bash
docker compose up -d
~~~
## CI/CD
~~~bash
docker compose logs -f
~~~
Voir `CICD.md` : Gitea contrôle le code, Semaphore l'exécute depuis la branche `valide`.
# Buy me a coffe
<a href='https://ko-fi.com/R5R2KNI3N' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://storage.ko-fi.com/cdn/kofi4.png?v=3' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>
## Vérifications après un premier passage
```bash
# Depuis le contrôleur : nouvelle session, clé uniquement
ssh -o BatchMode=yes -o ControlPath=none ansible@<hôte> 'sudo sshd -T | grep -Ei "^(permitrootlogin|passwordauthentication|authenticationmethods|allowusers)"'
# Pare-feu : seuls SSH, ICMP et les ports de supervision sont ouverts
ssh ansible@<hôte> 'sudo nft list chain inet filter input' # Debian/Ubuntu
ssh ansible@<hôte> 'sudo firewall-cmd --list-all' # Red Hat
# fail2ban actif sur sshd
ssh ansible@<hôte> 'sudo fail2ban-client status sshd'
```
+23
View File
@@ -0,0 +1,23 @@
[defaults]
inventory = inventory/hosts.yml
roles_path = roles
collections_path = collections:~/.ansible/collections
interpreter_python = /usr/bin/python3
host_key_checking = True
stdout_callback = ansible.builtin.default
result_format = yaml
callbacks_enabled = ansible.posix.profile_tasks
display_skipped_hosts = False
retry_files_enabled = False
forks = 5
# Contrairement à ansible-centreon (root sans sudo), les cibles sont hétérogènes :
# become est actif mais sans effet quand la connexion se fait déjà en root.
[privilege_escalation]
become = True
become_method = sudo
become_ask_pass = False
[ssh_connection]
pipelining = True
ssh_args = -o ControlMaster=auto -o ControlPersist=300s -o StrictHostKeyChecking=accept-new
+9
View File
@@ -0,0 +1,9 @@
---
# Semaphore lit ce fichier avant chaque exécution et installe ce qui manque.
# ansible.posix : profile_tasks, sysctl, firewalld, authorized_key.
# community.general : timezone, ini_file, seport.
collections:
- name: ansible.posix
version: ">=1.5.0"
- name: community.general
version: ">=8.0.0"
+13
View File
@@ -0,0 +1,13 @@
_______ _
|__ __| (_)
| | __ _ _ __ _ ___
| |/ _` | '_ \| / __|
| | (_| | |_) | \__ \
|_|\__,_| .__/|_|___/
_____ | |_ _ __ __ _
/ ____| |_(_) | | | \/ | | |
| (___ __ _ _ _ __ | |_ __ | \ / | __ _ ___| | ___ _ _
\___ \ / _` | | '_ \| __||__|| |\/| |/ _` |/ __| |/ _ \| | | |
____) | (_| | | | | | |_ | | | | (_| | (__| | (_) | |_| |
|_____/ \__,_|_|_| |_|\__| |_| |_|\__,_|\___|_|\___/ \__,_|
+10
View File
@@ -0,0 +1,10 @@
# Autorités de certification internes
Déposer ici les certificats racine internes au format PEM, avec l'extension
`.crt` (ex. `root-ca.crt`). Le rôle `common` les installe dans le magasin de
confiance du système (Debian : `update-ca-certificates`, Red Hat :
`update-ca-trust`), ce qui couvre à la fois l'agent GLPI et tout autre client
TLS (curl, wget, Python…).
Les certificats racine (partie publique) sont versionnés : Semaphore clone le dépôt
et doit les trouver.
+16
View File
@@ -0,0 +1,16 @@
# Clés publiques SSH
Un sous-répertoire par utilisateur, contenant une ou plusieurs clés au format
OpenSSH (`*.pub`) :
files/keys/root/hcornet.pub
files/keys/root/ansible.pub
files/keys/ansible/ansible.pub
files/keys/hcornet/hcornet.pub
Le rôle `ssh` concatène les fichiers `*.pub` du répertoire portant le nom de
l'utilisateur et remplace intégralement le fichier de clés autorisées : une clé
retirée d'ici est retirée du serveur au passage suivant.
Les clés publiques sont versionnées : Semaphore clone le dépôt et doit les trouver.
Une clé publique n'est pas un secret ; ne jamais déposer de clé privée ici.
+74
View File
@@ -0,0 +1,74 @@
---
# Variables communes à tous les serveurs.
# En-tête des fichiers déposés (templates et contenus inline).
ansible_managed: "Géré par Ansible (ansible-hardening-linux) — ne pas modifier à la main"
# Les valeurs par défaut de chaque rôle sont dans roles/<rôle>/defaults/main.yml ;
# ce fichier ne redéfinit que ce qui dépend de l'infrastructure.
# ---------------------------------------------------------------- réseau ----
# Réseaux d'administration : seuls ces réseaux peuvent joindre SSH.
# Liste vide = SSH ouvert à tous (déconseillé, mais évite tout verrouillage
# tant que les réseaux ne sont pas connus).
firewall_ssh_sources:
- 10.0.0.0/8
# Serveurs de supervision : autorisés sur SNMP (161/udp) et NRPE (5666/tcp).
supervision_sources:
- 10.78.56.16
- 10.78.56.45
- 10.78.56.100
# ------------------------------------------------------------------- DNS ----
dns_nameservers:
- 10.78.56.8
- 10.78.56.9
dns_search_domains:
- fr.dgs.group
# ----------------------------------------------------------------- proxy ----
# Laisser vide pour ne configurer aucun proxy.
proxy_url: ""
# proxy_url: "http://serv-proxy.fr.dgs.group:3128"
proxy_no_proxy:
- localhost
- 127.0.0.1
- .fr.dgs.group
# ------------------------------------------------------------------- SSH ----
# Les clés publiques sont lues dans files/keys/<utilisateur>/*.pub.
# Chaque utilisateur listé ici est créé s'il n'existe pas (sauf root).
ssh_users:
- name: root
- name: ansible
groups: [sudo_or_wheel] # remplacé par « sudo » ou « wheel » selon l'OS
sudo_nopasswd: true
- name: hcornet
groups: [sudo_or_wheel]
ssh_banner_organisation: "Tapis-Saint-Maclou"
# Logo ASCII repris de 01-ssh/banner, dans un fichier pour éviter tout souci d'indentation YAML.
ssh_banner_logo: "{{ lookup('ansible.builtin.file', playbook_dir ~ '/files/banner-logo.txt') }}"
# --------------------------------------------------------------- services ----
snmp_communities:
- name: "{{ vault_snmp_community_supervision }}"
sources: "{{ supervision_sources }}"
nrpe_allowed_hosts: "{{ supervision_sources }}"
glpi_agent_server: "https://glpi.fr.dgs.group/marketplace/glpiinventory/"
glpi_agent_tag: "ServeurProd"
# ------------------------------------------------------------- activation ----
# Chaque rôle peut être désactivé globalement, par groupe ou par hôte.
enable_proxy: "{{ proxy_url | length > 0 }}"
enable_dns: true
enable_updates: true
enable_ssh: true
enable_firewall: true
enable_fail2ban: true
enable_os_hardening: true
enable_snmp: true
enable_nrpe: true
enable_glpi_agent: true
+8
View File
@@ -0,0 +1,8 @@
---
# Une fois chiffré, ce fichier a vocation à être versionné — c'est tout l'intérêt d'ansible-vault.
#
# cp group_vars/all/vault.yml.example group_vars/all/vault.yml
# ansible-vault encrypt group_vars/all/vault.yml
#
# Référencé par les variables « vault_* » de main.yml.
vault_snmp_community_supervision: "changer-moi"
-11
View File
@@ -1,11 +0,0 @@
#!/bin/sh
# Pour docker et le plugin compose pour docker sur un Debian
# Add Docker's official GPG key:
apt-get update
apt-get install software-properties-common
add-apt-repository --yes --update ppa:ansible/ansible
apt install ansible
+22
View File
@@ -0,0 +1,22 @@
---
# Inventaire versionné (même principe qu'ansible-centreon) : Semaphore le lit depuis le dépôt.
#
# Deux modes de connexion possibles :
# - compte de service « ansible » + sudo (become=True dans ansible.cfg) ;
# - compte root par clé (comme sur les VM Terraform) : become est alors sans effet.
all:
vars:
ansible_user: ansible
children:
debian:
hosts:
srv-deb-01:
ansible_host: 10.0.5.20
ubuntu:
hosts:
srv-ubu-01:
ansible_host: 10.0.5.21
redhat:
hosts:
srv-rocky-01:
ansible_host: 10.0.5.22
+40
View File
@@ -0,0 +1,40 @@
---
# Rôle common — prérequis partagés par tous les autres rôles.
# Distributions acceptées (version majeure minimale).
common_supported:
Debian: 12
Ubuntu: 22
RedHat: 8
Rocky: 8
AlmaLinux: 8
OracleLinux: 8
common_timezone: "Europe/Paris"
# Paquets de base, communs aux deux familles.
common_packages:
- ca-certificates
- curl
- wget
- vim
- htop
- less
- rsync
- tar
- unzip
- sudo
# Paquets propres à chaque famille.
common_packages_debian:
- apt-transport-https
- gnupg2
- lsb-release
- python3-apt
common_packages_redhat:
- epel-release
- python3-libselinux
- dnf-plugins-core
# Certificats racine internes (files/ca/*.crt) à installer dans le magasin système.
common_ca_dir: "{{ playbook_dir }}/files/ca"
+5
View File
@@ -0,0 +1,5 @@
---
- name: Mettre à jour le magasin de certificats
ansible.builtin.command:
cmd: "{{ common_ca_update_cmd[ansible_facts['os_family']] }}"
changed_when: true
+52
View File
@@ -0,0 +1,52 @@
---
- name: Vérifier que la distribution est prise en charge
ansible.builtin.assert:
that:
- ansible_facts['distribution'] in common_supported
- ansible_facts['distribution_major_version'] | int >= common_supported[ansible_facts['distribution']]
- ansible_facts['os_family'] in ['Debian', 'RedHat']
fail_msg: >-
{{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}
n'est pas pris en charge (voir common_supported).
- name: Exposer le groupe sudo de la famille d'OS
ansible.builtin.set_fact:
common_sudo_group_effective: "{{ common_sudo_group[ansible_facts['os_family']] }}"
- name: Rafraîchir le cache APT
ansible.builtin.apt:
update_cache: true
cache_valid_time: 3600
when: ansible_facts['os_family'] == 'Debian'
- name: Installer les paquets de base
ansible.builtin.package:
name: "{{ common_packages + (common_packages_debian if ansible_facts['os_family'] == 'Debian' else common_packages_redhat) }}"
state: present
- name: Régler le fuseau horaire
community.general.timezone:
name: "{{ common_timezone }}"
- name: Lister les certificats racine internes à installer
ansible.builtin.find:
paths: "{{ common_ca_dir }}"
patterns: "*.crt"
delegate_to: localhost
become: false
register: common_ca_files
- name: Installer les certificats racine internes
ansible.builtin.copy:
src: "{{ item.path }}"
dest: "{{ common_ca_path[ansible_facts['os_family']] }}/{{ item.path | basename }}"
owner: root
group: root
mode: "0644"
loop: "{{ common_ca_files.files }}"
loop_control:
label: "{{ item.path | basename }}"
notify: Mettre à jour le magasin de certificats
- name: Appliquer immédiatement le magasin de certificats
ansible.builtin.meta: flush_handlers
+11
View File
@@ -0,0 +1,11 @@
---
# Correspondances propres à chaque famille d'OS.
common_ca_path:
Debian: /usr/local/share/ca-certificates
RedHat: /etc/pki/ca-trust/source/anchors
common_ca_update_cmd:
Debian: update-ca-certificates
RedHat: update-ca-trust extract
common_sudo_group:
Debian: sudo
RedHat: wheel
+13
View File
@@ -0,0 +1,13 @@
---
# Rôle dns — reprend 07-DNS/resolv.conf, en respectant le gestionnaire de
# résolution réellement en place (systemd-resolved, NetworkManager, ou aucun).
dns_nameservers: []
dns_search_domains: []
dns_options:
- timeout:2
- attempts:2
# Quand aucun gestionnaire n'est actif, /etc/resolv.conf est écrit directement.
# Un client DHCP peut le réécrire : dns_lock_resolv_conf pose l'attribut
# immuable (chattr +i) pour l'en empêcher.
dns_lock_resolv_conf: false
+10
View File
@@ -0,0 +1,10 @@
---
- name: Redémarrer systemd-resolved
ansible.builtin.systemd:
name: systemd-resolved
state: restarted
- name: Recharger NetworkManager
ansible.builtin.systemd:
name: NetworkManager
state: reloaded
+18
View File
@@ -0,0 +1,18 @@
---
- name: Vérifier qu'au moins un serveur DNS est défini
ansible.builtin.assert:
that: dns_nameservers | length > 0
fail_msg: "dns_nameservers est vide"
- name: Recenser les services de résolution présents
ansible.builtin.service_facts:
- name: Déterminer le gestionnaire de résolution en place
ansible.builtin.set_fact:
dns_manager: >-
{{ 'resolved' if (ansible_facts['services']['systemd-resolved.service'] | default({})).state | default('') == 'running'
else 'networkmanager' if (ansible_facts['services']['NetworkManager.service'] | default({})).state | default('') == 'running'
else 'static' }}
- name: Configurer la résolution
ansible.builtin.include_tasks: "{{ dns_manager }}.yml"
+16
View File
@@ -0,0 +1,16 @@
---
- name: Empêcher NetworkManager de gérer /etc/resolv.conf
ansible.builtin.copy:
dest: /etc/NetworkManager/conf.d/90-dns-none.conf
content: |
# {{ ansible_managed }}
[main]
dns=none
rc-manager=unmanaged
owner: root
group: root
mode: "0644"
notify: Recharger NetworkManager
- name: Écrire /etc/resolv.conf
ansible.builtin.include_tasks: static.yml
+24
View File
@@ -0,0 +1,24 @@
---
- name: Créer le répertoire de surcharge de systemd-resolved
ansible.builtin.file:
path: /etc/systemd/resolved.conf.d
state: directory
owner: root
group: root
mode: "0755"
- name: Déposer la configuration DNS de systemd-resolved
ansible.builtin.template:
src: resolved.conf.j2
dest: /etc/systemd/resolved.conf.d/10-dns.conf
owner: root
group: root
mode: "0644"
notify: Redémarrer systemd-resolved
- name: Pointer /etc/resolv.conf vers le résolveur local
ansible.builtin.file:
src: /run/systemd/resolve/stub-resolv.conf
dest: /etc/resolv.conf
state: link
force: true
+35
View File
@@ -0,0 +1,35 @@
---
- name: Examiner /etc/resolv.conf
ansible.builtin.stat:
path: /etc/resolv.conf
follow: false
register: dns_resolv_stat
- name: Supprimer un éventuel lien symbolique /etc/resolv.conf
ansible.builtin.file:
path: /etc/resolv.conf
state: absent
when: dns_resolv_stat.stat.islnk | default(false)
- name: Retirer l'attribut immuable avant écriture
ansible.builtin.file:
path: /etc/resolv.conf
attributes: -i
when:
- dns_resolv_stat.stat.exists
- not dns_resolv_stat.stat.islnk | default(false)
- "'i' in (dns_resolv_stat.stat.attributes | default([]))"
- name: Écrire /etc/resolv.conf
ansible.builtin.template:
src: resolv.conf.j2
dest: /etc/resolv.conf
owner: root
group: root
mode: "0644"
- name: Poser l'attribut immuable sur /etc/resolv.conf
ansible.builtin.file:
path: /etc/resolv.conf
attributes: +i
when: dns_lock_resolv_conf | bool
+10
View File
@@ -0,0 +1,10 @@
# {{ ansible_managed }}
{% for ns in dns_nameservers %}
nameserver {{ ns }}
{% endfor %}
{% if dns_search_domains | length > 0 %}
search {{ dns_search_domains | join(' ') }}
{% endif %}
{% if dns_options | length > 0 %}
options {{ dns_options | join(' ') }}
{% endif %}
+6
View File
@@ -0,0 +1,6 @@
# {{ ansible_managed }}
[Resolve]
DNS={{ dns_nameservers | join(' ') }}
{% if dns_search_domains | length > 0 %}
Domains={{ dns_search_domains | join(' ') }}
{% endif %}
+7
View File
@@ -0,0 +1,7 @@
---
# Rôle fail2ban — bannissement des sources en échec d'authentification SSH.
fail2ban_bantime: 1h
fail2ban_findtime: 10m
fail2ban_maxretry: 5
# Adresses jamais bannies : boucle locale + réseaux d'administration.
fail2ban_ignoreip: "{{ ['127.0.0.1/8', '::1'] + (firewall_ssh_sources | default([])) }}"
+5
View File
@@ -0,0 +1,5 @@
---
- name: Redémarrer fail2ban
ansible.builtin.systemd:
name: fail2ban
state: restarted
+20
View File
@@ -0,0 +1,20 @@
---
- name: Installer fail2ban
ansible.builtin.package:
name: "{{ fail2ban_packages[ansible_facts['os_family']] }}"
state: present
- name: Déposer la configuration locale
ansible.builtin.template:
src: jail.local.j2
dest: /etc/fail2ban/jail.local
owner: root
group: root
mode: "0644"
notify: Redémarrer fail2ban
- name: Activer et démarrer fail2ban
ansible.builtin.systemd:
name: fail2ban
enabled: true
state: started
+16
View File
@@ -0,0 +1,16 @@
# {{ ansible_managed }}
[DEFAULT]
# Le journal systemd est lu directement : aucun chemin de log à maintenir
# selon la distribution.
backend = systemd
banaction = {{ fail2ban_banaction[ansible_facts['os_family']] }}
banaction_allports = {{ fail2ban_banaction[ansible_facts['os_family']] }}
bantime = {{ fail2ban_bantime }}
findtime = {{ fail2ban_findtime }}
maxretry = {{ fail2ban_maxretry }}
ignoreip = {{ fail2ban_ignoreip | join(' ') }}
[sshd]
enabled = true
port = {{ ssh_port | default(22) }}
mode = aggressive
+8
View File
@@ -0,0 +1,8 @@
---
fail2ban_packages:
Debian: [fail2ban, python3-systemd]
RedHat: [fail2ban, fail2ban-firewalld]
# Action de bannissement cohérente avec le pare-feu de la famille.
fail2ban_banaction:
Debian: nftables-multiport
RedHat: firewallcmd-rich-rules
+34
View File
@@ -0,0 +1,34 @@
---
# Rôle firewall — nouveau par rapport aux scripts d'origine (qui ne posaient
# aucun pare-feu). Politique : tout est fermé en entrée sauf SSH, ICMP et les
# ports de supervision, chacun limité aux réseaux qui en ont besoin.
#
# auto : nftables sous Debian/Ubuntu, firewalld sous Red Hat (chacun est le
# pare-feu natif de sa famille). Peut être forcé à « nftables » ou « firewalld ».
firewall_backend: auto
# Réseaux autorisés à joindre SSH. Vide = tout le monde.
firewall_ssh_sources: []
# Règles standard, activées avec le rôle correspondant.
firewall_rules:
- name: snmp
port: 161
proto: udp
sources: "{{ supervision_sources | default([]) }}"
enabled: "{{ enable_snmp | default(false) }}"
- name: nrpe
port: 5666
proto: tcp
sources: "{{ supervision_sources | default([]) }}"
enabled: "{{ enable_nrpe | default(false) }}"
# Règles supplémentaires propres à un hôte ou un groupe (même format).
# Exemple : { name: https, port: 443, proto: tcp, sources: [], enabled: true }
firewall_extra_rules: []
# Avant d'appliquer, vérifier que l'adresse depuis laquelle Ansible est
# connecté figure bien dans firewall_ssh_sources (sinon : verrouillage).
firewall_check_controller_source: true
# Après application, ouvrir une nouvelle session SSH depuis le contrôleur.
firewall_verify_ssh: true
+5
View File
@@ -0,0 +1,5 @@
---
- name: Recharger nftables
ansible.builtin.systemd:
name: nftables
state: reloaded
+79
View File
@@ -0,0 +1,79 @@
---
- name: Installer firewalld
ansible.builtin.package:
name:
- firewalld
- python3-firewall
state: present
- name: Recenser les services
ansible.builtin.service_facts:
- name: Arrêter et désactiver nftables (pilotage par firewalld)
ansible.builtin.systemd:
name: nftables
enabled: false
state: stopped
when: "'nftables.service' in ansible_facts['services']"
- name: Activer et démarrer firewalld
ansible.builtin.systemd:
name: firewalld
enabled: true
state: started
- name: Retirer les services ouverts par défaut dans la zone public
ansible.posix.firewalld:
zone: public
service: "{{ item }}"
state: disabled
permanent: true
immediate: true
loop:
- cockpit
- dhcpv6-client
- ssh
- name: Autoriser SSH depuis tout le monde (aucune source définie)
ansible.posix.firewalld:
zone: public
port: "{{ ssh_port | default(22) }}/tcp"
state: enabled
permanent: true
immediate: true
when: firewall_ssh_sources | length == 0
- name: Autoriser SSH depuis les réseaux d'administration
ansible.posix.firewalld:
zone: public
rich_rule: >-
rule family="{{ 'ipv6' if ':' in item else 'ipv4' }}" source address="{{ item }}"
port port="{{ ssh_port | default(22) }}" protocol="tcp" accept
state: enabled
permanent: true
immediate: true
loop: "{{ firewall_ssh_sources }}"
- name: Autoriser les services depuis leurs sources
ansible.posix.firewalld:
zone: public
rich_rule: >-
rule family="{{ 'ipv6' if ':' in item.1 else 'ipv4' }}" source address="{{ item.1 }}"
port port="{{ item.0.port }}" protocol="{{ item.0.proto }}" accept
state: enabled
permanent: true
immediate: true
loop: "{{ firewall_rules_effective | subelements('sources', skip_missing=True) }}"
loop_control:
label: "{{ item.0.name }} <- {{ item.1 }}"
- name: Autoriser les services ouverts à tous (sans source)
ansible.posix.firewalld:
zone: public
port: "{{ item.port }}/{{ item.proto }}"
state: enabled
permanent: true
immediate: true
loop: "{{ firewall_rules_effective | rejectattr('sources') | list }}"
loop_control:
label: "{{ item.name }}"
+60
View File
@@ -0,0 +1,60 @@
---
- name: Déterminer le pare-feu à utiliser
ansible.builtin.set_fact:
firewall_backend_effective: >-
{{ firewall_backend if firewall_backend != 'auto' else firewall_backend_by_family[ansible_facts['os_family']] }}
firewall_rules_effective: >-
{{ (firewall_rules + firewall_extra_rules) | selectattr('enabled', 'defined') | selectattr('enabled') | list }}
- name: Relever l'adresse source de la session Ansible
ansible.builtin.shell:
cmd: 'echo "${SSH_CONNECTION%% *}"'
become: false
register: firewall_controller_ip
changed_when: false
when:
- firewall_check_controller_source | bool
- firewall_ssh_sources | length > 0
- name: Refuser une liste firewall_ssh_sources qui exclurait le contrôleur
ansible.builtin.command:
argv:
- python3
- -c
- |
import ipaddress, sys
ip = ipaddress.ip_address(sys.argv[1])
ok = any(ip in ipaddress.ip_network(n, strict=False) for n in ' '.join(sys.argv[2:]).split())
sys.exit(0 if ok else 1)
- "{{ firewall_controller_ip.stdout }}"
- "{{ firewall_ssh_sources | join(' ') }}"
changed_when: false
failed_when: false
register: firewall_controller_check
when:
- firewall_check_controller_source | bool
- firewall_ssh_sources | length > 0
- firewall_controller_ip.stdout | length > 0
- name: Arrêter si le contrôleur serait bloqué
ansible.builtin.fail:
msg: >-
Ansible est connecté depuis {{ firewall_controller_ip.stdout }}, absent de
firewall_ssh_sources ({{ firewall_ssh_sources | join(', ') }}) : appliquer
ce pare-feu couperait l'accès. Compléter la liste ou passer
firewall_check_controller_source=false en connaissance de cause.
when:
- firewall_controller_check is not skipped
- firewall_controller_check.rc != 0
- name: Configurer le pare-feu
ansible.builtin.include_tasks: "{{ firewall_backend_effective }}.yml"
- name: Appliquer les règles maintenant
ansible.builtin.meta: flush_handlers
- name: Vérifier qu'une nouvelle connexion SSH aboutit
ansible.builtin.include_role:
name: ssh
tasks_from: verify
when: firewall_verify_ssh | bool
+54
View File
@@ -0,0 +1,54 @@
---
- name: Installer nftables
ansible.builtin.package:
name: nftables
state: present
- name: Recenser les services
ansible.builtin.service_facts:
- name: Arrêter et désactiver les pare-feux concurrents
ansible.builtin.systemd:
name: "{{ item }}"
enabled: false
state: stopped
loop:
- ufw
- firewalld
- iptables
- netfilter-persistent
when: (item ~ '.service') in ansible_facts['services']
- name: Créer le répertoire des fragments de règles
ansible.builtin.file:
path: /etc/nftables.d
state: directory
owner: root
group: root
mode: "0750"
- name: Déposer un fragment vide pour que l'include soit toujours valide
ansible.builtin.copy:
dest: /etc/nftables.d/00-placeholder.nft
content: |
# Fragments de règles applicatives (un fichier par service). Ne rien mettre ici.
owner: root
group: root
mode: "0640"
force: false
- name: Déposer le jeu de règles principal
ansible.builtin.template:
src: nftables.conf.j2
dest: /etc/nftables.conf
owner: root
group: root
mode: "0640"
validate: nft -c -f %s
notify: Recharger nftables
- name: Activer et démarrer nftables
ansible.builtin.systemd:
name: nftables
enabled: true
state: started
+72
View File
@@ -0,0 +1,72 @@
#!/usr/sbin/nft -f
# {{ ansible_managed }}
# Compatible avec le jeu posé par cloud-init sur les VM Terraform :
# les règles applicatives vont dans /etc/nftables.d/*.nft.
flush ruleset
table inet filter {
{% if firewall_ssh_sources | length > 0 %}
set reseaux_admin_v4 {
type ipv4_addr
flags interval
{% set v4 = firewall_ssh_sources | reject('search', ':') | list %}
{% if v4 | length > 0 %}
elements = { {{ v4 | join(', ') }} }
{% endif %}
}
set reseaux_admin_v6 {
type ipv6_addr
flags interval
{% set v6 = firewall_ssh_sources | select('search', ':') | list %}
{% if v6 | length > 0 %}
elements = { {{ v6 | join(', ') }} }
{% endif %}
}
{% endif %}
chain input {
type filter hook input priority filter; policy drop;
iif "lo" accept
ct state established,related accept
ct state invalid drop
ip protocol icmp icmp type { echo-request, destination-unreachable, time-exceeded, parameter-problem } accept
ip6 nexthdr ipv6-icmp accept
{% if firewall_ssh_sources | length > 0 %}
tcp dport {{ ssh_port | default(22) }} ip saddr @reseaux_admin_v4 ct state new accept
tcp dport {{ ssh_port | default(22) }} ip6 saddr @reseaux_admin_v6 ct state new accept
{% else %}
tcp dport {{ ssh_port | default(22) }} ct state new accept
{% endif %}
{% for rule in firewall_rules_effective %}
{% set r4 = rule.sources | reject('search', ':') | list %}
{% set r6 = rule.sources | select('search', ':') | list %}
# {{ rule.name }}
{% if rule.sources | length == 0 %}
{{ rule.proto }} dport {{ rule.port }} accept
{% else %}
{% if r4 | length > 0 %}
ip saddr { {{ r4 | join(', ') }} } {{ rule.proto }} dport {{ rule.port }} accept
{% endif %}
{% if r6 | length > 0 %}
ip6 saddr { {{ r6 | join(', ') }} } {{ rule.proto }} dport {{ rule.port }} accept
{% endif %}
{% endif %}
{% endfor %}
include "/etc/nftables.d/*.nft"
counter comment "paquets rejetes en entree"
}
chain forward {
type filter hook forward priority filter; policy drop;
}
chain output {
type filter hook output priority filter; policy accept;
}
}
+4
View File
@@ -0,0 +1,4 @@
---
firewall_backend_by_family:
Debian: nftables
RedHat: firewalld
+15
View File
@@ -0,0 +1,15 @@
---
# Rôle glpi_agent — reprend 04-agent-glpi (installateur perl officiel).
# Le certificat racine n'est plus passé à l'agent : il est installé dans le
# magasin système par le rôle common, ce qui couvre l'agent et tout le reste.
glpi_agent_version: "1.19"
glpi_agent_installer_url: >-
https://github.com/glpi-project/glpi-agent/releases/download/{{ glpi_agent_version
}}/glpi-agent-{{ glpi_agent_version }}-linux-installer.pl
glpi_agent_server: ""
glpi_agent_tag: ""
# Profil d'installation de l'installateur : typical | network | all.
glpi_agent_install_type: all
# Tâches activées côté agent : inventory, netdiscovery, netinventory, deploy, collect, esx…
glpi_agent_tasks: "inventory,deploy,collect"
glpi_agent_no_ssl_check: false
+5
View File
@@ -0,0 +1,5 @@
---
- name: Redémarrer glpi-agent
ansible.builtin.systemd:
name: glpi-agent
state: restarted
+59
View File
@@ -0,0 +1,59 @@
---
- name: Vérifier que le serveur GLPI est renseigné
ansible.builtin.assert:
that: glpi_agent_server is match('^https?://')
fail_msg: "glpi_agent_server doit être l'URL du serveur GLPI (plugin inventaire)"
- name: Installer perl (prérequis de l'installateur)
ansible.builtin.package:
name: perl
state: present
- name: Lire la version installée de l'agent
ansible.builtin.command:
cmd: glpi-agent --version
register: glpi_agent_installed
changed_when: false
failed_when: false
- name: Installer ou mettre à jour l'agent
when: ('(' ~ glpi_agent_version ~ ')') not in (glpi_agent_installed.stdout | default(''))
environment: "{{ {'http_proxy': proxy_url, 'https_proxy': proxy_url} if (proxy_url | default('')) | length > 0 else {} }}"
block:
- name: Télécharger l'installateur
ansible.builtin.get_url:
url: "{{ glpi_agent_installer_url }}"
dest: "/tmp/glpi-agent-{{ glpi_agent_version }}-linux-installer.pl"
mode: "0600"
owner: root
group: root
- name: Exécuter l'installateur
ansible.builtin.command:
argv:
- perl
- "/tmp/glpi-agent-{{ glpi_agent_version }}-linux-installer.pl"
- --install
- --type={{ glpi_agent_install_type }}
- --no-question
changed_when: true
- name: Supprimer l'installateur
ansible.builtin.file:
path: "/tmp/glpi-agent-{{ glpi_agent_version }}-linux-installer.pl"
state: absent
- name: Configurer l'agent
ansible.builtin.template:
src: 10-ansible.cfg.j2
dest: /etc/glpi-agent/conf.d/10-ansible.cfg
owner: root
group: root
mode: "0640"
notify: Redémarrer glpi-agent
- name: Activer et démarrer l'agent
ansible.builtin.systemd:
name: glpi-agent
enabled: true
state: started
@@ -0,0 +1,10 @@
# {{ ansible_managed }}
server = {{ glpi_agent_server }}
{% if glpi_agent_tag | length > 0 %}
tag = {{ glpi_agent_tag }}
{% endif %}
tasks = {{ glpi_agent_tasks }}
no-ssl-check = {{ '1' if glpi_agent_no_ssl_check else '0' }}
{% if proxy_url | default('') | length > 0 %}
proxy = {{ proxy_url }}
{% endif %}
+13
View File
@@ -0,0 +1,13 @@
---
# Rôle nrpe — reprend 08-NRPE (installation) et ajoute la configuration :
# hôtes autorisés et commandes de base.
nrpe_allowed_hosts: []
nrpe_port: 5666
# Vérifications standard exposées au serveur de supervision.
nrpe_commands:
check_users: "check_users -w 5 -c 10"
check_load: "check_load -r -w .15,.10,.05 -c .30,.25,.20"
check_disk_root: "check_disk -w 20% -c 10% -p /"
check_zombie_procs: "check_procs -w 5 -c 10 -s Z"
check_total_procs: "check_procs -w 250 -c 400"
check_swap: "check_swap -w 20% -c 10%"
+5
View File
@@ -0,0 +1,5 @@
---
- name: Redémarrer nrpe
ansible.builtin.systemd:
name: "{{ nrpe_service[ansible_facts['os_family']] }}"
state: restarted
+54
View File
@@ -0,0 +1,54 @@
---
- name: Installer NRPE et les greffons
ansible.builtin.package:
name: "{{ nrpe_packages[ansible_facts['os_family']] }}"
state: present
- name: Vérifier qu'au moins un hôte de supervision est défini
ansible.builtin.assert:
that: nrpe_allowed_hosts | length > 0
fail_msg: "nrpe_allowed_hosts est vide"
- name: Fixer les hôtes autorisés dans nrpe.cfg
ansible.builtin.lineinfile:
path: /etc/nagios/nrpe.cfg
regexp: '^\s*#?\s*allowed_hosts\s*='
line: "allowed_hosts={{ (['127.0.0.1', '::1'] + nrpe_allowed_hosts) | join(',') }}"
notify: Redémarrer nrpe
- name: Interdire les arguments passés par le superviseur
ansible.builtin.lineinfile:
path: /etc/nagios/nrpe.cfg
regexp: '^\s*#?\s*dont_blame_nrpe\s*='
line: "dont_blame_nrpe=0"
notify: Redémarrer nrpe
- name: Fixer le port d'écoute
ansible.builtin.lineinfile:
path: /etc/nagios/nrpe.cfg
regexp: '^\s*#?\s*server_port\s*='
line: "server_port={{ nrpe_port }}"
notify: Redémarrer nrpe
- name: Créer le répertoire des commandes
ansible.builtin.file:
path: "{{ nrpe_include_dir[ansible_facts['os_family']] }}"
state: directory
owner: root
group: root
mode: "0755"
- name: Déposer les commandes de supervision
ansible.builtin.template:
src: commandes.cfg.j2
dest: "{{ nrpe_include_dir[ansible_facts['os_family']] }}/10-ansible.cfg"
owner: root
group: root
mode: "0644"
notify: Redémarrer nrpe
- name: Activer et démarrer NRPE
ansible.builtin.systemd:
name: "{{ nrpe_service[ansible_facts['os_family']] }}"
enabled: true
state: started
+4
View File
@@ -0,0 +1,4 @@
# {{ ansible_managed }}
{% for name, cmd in nrpe_commands.items() %}
command[{{ name }}]={{ nrpe_plugins_dir[ansible_facts['os_family']] }}/{{ cmd }}
{% endfor %}
+13
View File
@@ -0,0 +1,13 @@
---
nrpe_packages:
Debian: [nagios-nrpe-server, monitoring-plugins-basic, monitoring-plugins-standard]
RedHat: [nrpe, nagios-plugins-all]
nrpe_service:
Debian: nagios-nrpe-server
RedHat: nrpe
nrpe_include_dir:
Debian: /etc/nagios/nrpe.d
RedHat: /etc/nrpe.d
nrpe_plugins_dir:
Debian: /usr/lib/nagios/plugins
RedHat: /usr/lib64/nagios/plugins
+70
View File
@@ -0,0 +1,70 @@
---
# Rôle os_hardening — durcissement du système, sans jamais toucher à
# l'authentification locale (PAM, mots de passe, console) : un administrateur
# devant la machine doit toujours pouvoir se connecter.
# Paramètres noyau (repris du cloud-init Terraform et complétés).
os_hardening_sysctl:
net.ipv4.conf.all.accept_redirects: 0
net.ipv4.conf.default.accept_redirects: 0
net.ipv4.conf.all.secure_redirects: 0
net.ipv4.conf.default.secure_redirects: 0
net.ipv4.conf.all.send_redirects: 0
net.ipv4.conf.default.send_redirects: 0
net.ipv4.conf.all.accept_source_route: 0
net.ipv4.conf.default.accept_source_route: 0
net.ipv4.conf.all.log_martians: 1
net.ipv4.conf.default.log_martians: 1
net.ipv4.conf.all.rp_filter: 1
net.ipv4.conf.default.rp_filter: 1
net.ipv4.icmp_echo_ignore_broadcasts: 1
net.ipv4.icmp_ignore_bogus_error_responses: 1
net.ipv4.tcp_syncookies: 1
net.ipv6.conf.all.accept_redirects: 0
net.ipv6.conf.default.accept_redirects: 0
net.ipv6.conf.all.accept_source_route: 0
net.ipv6.conf.all.accept_ra: 0
net.ipv6.conf.default.accept_ra: 0
kernel.dmesg_restrict: 1
kernel.kptr_restrict: 2
kernel.sysrq: 0
kernel.yama.ptrace_scope: 1
kernel.randomize_va_space: 2
fs.protected_hardlinks: 1
fs.protected_symlinks: 1
fs.protected_fifos: 2
fs.protected_regular: 2
fs.suid_dumpable: 0
# Interdire les core dumps.
os_hardening_disable_core_dumps: true
# Politique des NOUVEAUX comptes (login.defs) — n'affecte pas les comptes existants.
os_hardening_login_defs:
PASS_MAX_DAYS: "365"
PASS_MIN_DAYS: "1"
PASS_WARN_AGE: "14"
UMASK: "027"
# Journalisation des appels système sensibles.
os_hardening_auditd: true
# Services inutiles sur un serveur, désactivés s'ils sont présents.
os_hardening_disable_services:
- avahi-daemon
- cups
- bluetooth
# Paquets à retirer (protocoles en clair).
os_hardening_remove_packages:
- telnet
- rsh-client
- rsh-redone-client
- talk
- nis
- ypbind
# Restreindre « su » aux membres du groupe sudo/wheel (pam_wheel).
# false par défaut : les comptes sans sudo doivent pouvoir faire « su - »
# (cas des VM Terraform où sudo est purgé).
os_hardening_restrict_su: false
+114
View File
@@ -0,0 +1,114 @@
---
- name: Appliquer les paramètres noyau
ansible.posix.sysctl:
name: "{{ item.key }}"
value: "{{ item.value }}"
sysctl_file: /etc/sysctl.d/99-durcissement.conf
sysctl_set: true
reload: true
state: present
loop: "{{ os_hardening_sysctl | dict2items }}"
loop_control:
label: "{{ item.key }}"
# Certaines clés n'existent pas partout (yama, IPv6 désactivé) : ne pas bloquer.
failed_when: false
- name: Interdire les core dumps (limits)
ansible.builtin.copy:
dest: /etc/security/limits.d/99-durcissement.conf
content: |
# {{ ansible_managed }}
* hard core 0
* soft core 0
owner: root
group: root
mode: "0644"
when: os_hardening_disable_core_dumps | bool
- name: Créer le répertoire coredump.conf.d
ansible.builtin.file:
path: /etc/systemd/coredump.conf.d
state: directory
owner: root
group: root
mode: "0755"
when: os_hardening_disable_core_dumps | bool
- name: Interdire les core dumps (systemd-coredump)
ansible.builtin.copy:
dest: /etc/systemd/coredump.conf.d/99-durcissement.conf
content: |
# {{ ansible_managed }}
[Coredump]
Storage=none
ProcessSizeMax=0
owner: root
group: root
mode: "0644"
when: os_hardening_disable_core_dumps | bool
- name: Politique des nouveaux comptes (login.defs)
ansible.builtin.lineinfile:
path: /etc/login.defs
regexp: '^\s*#?\s*{{ item.key }}\s'
line: "{{ item.key }}\t{{ item.value }}"
loop: "{{ os_hardening_login_defs | dict2items }}"
loop_control:
label: "{{ item.key }}"
- name: Installer et activer auditd
ansible.builtin.package:
name: "{{ 'auditd' if ansible_facts['os_family'] == 'Debian' else 'audit' }}"
state: present
when: os_hardening_auditd | bool
- name: Démarrer auditd
ansible.builtin.systemd:
name: auditd
enabled: true
state: started
when: os_hardening_auditd | bool
- name: Recenser les services
ansible.builtin.service_facts:
- name: Désactiver les services inutiles présents
ansible.builtin.systemd:
name: "{{ item }}"
enabled: false
state: stopped
masked: true
loop: "{{ os_hardening_disable_services }}"
when: (item ~ '.service') in ansible_facts['services']
- name: Retirer les paquets aux protocoles en clair
ansible.builtin.package:
name: "{{ os_hardening_remove_packages }}"
state: absent
- name: Restreindre « su » au groupe sudo/wheel
ansible.builtin.lineinfile:
path: /etc/pam.d/su
regexp: '^\s*#?\s*auth\s+required\s+pam_wheel\.so'
line: "auth required pam_wheel.so use_uid group={{ common_sudo_group_effective }}"
insertafter: '^auth\s+sufficient\s+pam_rootok\.so'
when: os_hardening_restrict_su | bool
- name: Protéger les fichiers sensibles
ansible.builtin.file:
path: "{{ item.path }}"
owner: root
group: root
mode: "{{ item.mode }}"
loop:
- { path: /etc/crontab, mode: "0600" }
- { path: /etc/cron.d, mode: "0700" }
- { path: /etc/cron.daily, mode: "0700" }
- { path: /etc/cron.hourly, mode: "0700" }
- { path: /etc/cron.weekly, mode: "0700" }
- { path: /etc/cron.monthly, mode: "0700" }
- { path: /etc/ssh/sshd_config, mode: "0600" }
loop_control:
label: "{{ item.path }}"
failed_when: false
+10
View File
@@ -0,0 +1,10 @@
---
# Rôle proxy — reprend 02-apt/02proxy et les exports du README d'origine.
proxy_url: ""
proxy_no_proxy:
- localhost
- 127.0.0.1
# Le gestionnaire de paquets passe toujours par le proxy.
# L'environnement (profile.d) est optionnel : utile pour wget/curl/pip.
proxy_configure_environment: true
+41
View File
@@ -0,0 +1,41 @@
---
- name: Vérifier que l'URL du proxy est renseignée
ansible.builtin.assert:
that: proxy_url is match('^https?://')
fail_msg: "proxy_url doit être une URL http(s)://hôte:port"
- name: Configurer le proxy APT
ansible.builtin.template:
src: 02proxy.j2
dest: /etc/apt/apt.conf.d/02proxy
owner: root
group: root
mode: "0644"
when: ansible_facts['os_family'] == 'Debian'
- name: Configurer le proxy DNF
community.general.ini_file:
path: /etc/dnf/dnf.conf
section: main
option: proxy
value: "{{ proxy_url }}"
no_extra_spaces: true
owner: root
group: root
mode: "0644"
when: ansible_facts['os_family'] == 'RedHat'
- name: Exposer le proxy dans l'environnement des sessions
ansible.builtin.template:
src: proxy.sh.j2
dest: /etc/profile.d/proxy.sh
owner: root
group: root
mode: "0644"
when: proxy_configure_environment | bool
- name: Retirer le proxy de l'environnement des sessions
ansible.builtin.file:
path: /etc/profile.d/proxy.sh
state: absent
when: not proxy_configure_environment | bool
+4
View File
@@ -0,0 +1,4 @@
// {{ ansible_managed }}
Acquire::http::proxy "{{ proxy_url }}";
Acquire::https::proxy "{{ proxy_url }}";
Acquire::ftp::proxy "{{ proxy_url }}";
+6
View File
@@ -0,0 +1,6 @@
# {{ ansible_managed }}
export http_proxy="{{ proxy_url }}"
export https_proxy="{{ proxy_url }}"
export ftp_proxy="{{ proxy_url }}"
export no_proxy="{{ proxy_no_proxy | join(',') }}"
export HTTP_PROXY="$http_proxy" HTTPS_PROXY="$https_proxy" FTP_PROXY="$ftp_proxy" NO_PROXY="$no_proxy"
+18
View File
@@ -0,0 +1,18 @@
---
# Rôle snmp — reprend 06-snmp (communautés v2c par source de supervision)
# et ajoute SNMPv3 en option.
snmp_listen: "udp:161,udp6:[::1]:161"
snmp_sys_location: "Datacenter"
snmp_sys_contact: "[email protected]"
# Communautés v2c en lecture seule : name (depuis le vault), sources (liste ;
# vide = toutes). Reprise de l'ancien snmpd.conf.
snmp_communities: []
# Utilisateurs SNMPv3 (lecture seule) : name, auth_pass, priv_pass, et en
# option auth (SHA) / priv (AES). Créés une fois dans la base persistante.
snmp_v3_users: []
# Lignes « extend » (ex. docker-stats). Le script doit être déployé à part.
snmp_extends: []
# - { name: docker, command: /etc/snmp/docker-stats.py }
+5
View File
@@ -0,0 +1,5 @@
---
- name: Redémarrer snmpd
ansible.builtin.systemd:
name: snmpd
state: restarted
+30
View File
@@ -0,0 +1,30 @@
---
- name: Installer snmpd
ansible.builtin.package:
name: "{{ snmp_packages[ansible_facts['os_family']] }}"
state: present
- name: Vérifier qu'au moins un accès est défini
ansible.builtin.assert:
that: (snmp_communities | length) + (snmp_v3_users | length) > 0
fail_msg: "snmp_communities et snmp_v3_users sont vides : aucun superviseur ne pourrait interroger l'agent"
- name: Déposer snmpd.conf
ansible.builtin.template:
src: snmpd.conf.j2
dest: /etc/snmp/snmpd.conf
owner: root
group: root
mode: "0600"
no_log: true
notify: Redémarrer snmpd
- name: Créer les utilisateurs SNMPv3
ansible.builtin.include_tasks: v3.yml
when: snmp_v3_users | length > 0
- name: Activer et démarrer snmpd
ansible.builtin.systemd:
name: snmpd
enabled: true
state: started
+40
View File
@@ -0,0 +1,40 @@
---
# createUser n'est lu qu'au démarrage : le service est arrêté, la ligne est
# ajoutée à la base persistante, puis snmpd la convertit en clés au redémarrage.
- name: Vérifier quels utilisateurs SNMPv3 existent déjà
ansible.builtin.shell:
cmd: >-
set -o pipefail;
hex=$(printf '%s' '{{ item.name }}' | od -An -tx1 | tr -d ' \n');
grep -c -e "createUser {{ item.name }} " -e "usmUser .*0x${hex} " {{ snmp_persistent_conf[ansible_facts['os_family']] }}
executable: /bin/bash
loop: "{{ snmp_v3_users }}"
loop_control:
label: "{{ item.name }}"
register: snmp_v3_existing
changed_when: false
failed_when: false
no_log: true
- name: Arrêter snmpd avant la création des utilisateurs
ansible.builtin.systemd:
name: snmpd
state: stopped
when: snmp_v3_existing.results | selectattr('rc', 'ne', 0) | list | length > 0
- name: Déclarer les utilisateurs SNMPv3 manquants
ansible.builtin.lineinfile:
path: "{{ snmp_persistent_conf[ansible_facts['os_family']] }}"
line: >-
createUser {{ item.item.name }} {{ item.item.auth | default('SHA') }} "{{ item.item.auth_pass }}"
{{ item.item.priv | default('AES') }} "{{ item.item.priv_pass }}"
create: true
owner: root
group: root
mode: "0600"
loop: "{{ snmp_v3_existing.results }}"
loop_control:
label: "{{ item.item.name }}"
when: item.rc != 0
no_log: true
notify: Redémarrer snmpd
+26
View File
@@ -0,0 +1,26 @@
# {{ ansible_managed }}
agentaddress {{ snmp_listen }}
sysLocation {{ snmp_sys_location }}
sysContact {{ snmp_sys_contact }}
sysServices 72
# Lecture seule, arbre complet.
view systemonly included .1
{% for c in snmp_communities %}
{% if c.sources | default([]) | length == 0 %}
rocommunity {{ c.name }} default -V systemonly
{% else %}
{% for src in c.sources %}
rocommunity{{ '6' if ':' in src else '' }} {{ c.name }} {{ src }} -V systemonly
{% endfor %}
{% endif %}
{% endfor %}
{% for u in snmp_v3_users %}
rouser {{ u.name }} priv -V systemonly
{% endfor %}
{% for e in snmp_extends %}
extend {{ e.name }} {{ e.command }}
{% endfor %}
+7
View File
@@ -0,0 +1,7 @@
---
snmp_packages:
Debian: [snmpd, snmp]
RedHat: [net-snmp, net-snmp-utils]
snmp_persistent_conf:
Debian: /var/lib/snmp/snmpd.conf
RedHat: /var/lib/net-snmp/snmpd.conf
+84
View File
@@ -0,0 +1,84 @@
---
# Rôle ssh — reprend 01-ssh (sshd_config, ssh_config, banner, motd, clés
# autorisées) et le durcissement du projet terraform-proxmox-serveur-debian-12.
#
# Principe : les accès distants sont exclusivement en SSH par clé publique ;
# le mot de passe des comptes reste utilisable en local (console, su),
# le rôle ne le verrouille jamais.
ssh_port: 22
# yes | prohibit-password | no
# prohibit-password : root par clé uniquement (nécessaire si Ansible se
# connecte en root) ; le mot de passe root reste utilisable sur la console.
ssh_permit_root_login: prohibit-password
# Comptes autorisés en SSH. Chaque entrée : name (obligatoire), groups (liste,
# « sudo_or_wheel » est traduit selon l'OS), sudo_nopasswd (bool), shell,
# password_hash (optionnel, pour un mot de passe local — jamais en clair).
# Les clés publiques sont lues dans files/keys/<name>/*.pub.
ssh_users:
- name: root
ssh_keys_dir: "{{ playbook_dir }}/files/keys"
# Clés centralisées dans /etc/ssh/authorized_keys/<utilisateur>, appartenant à
# root : un utilisateur ne peut pas ajouter de clé lui-même (reprise de
# l'ancien script, qui posait un lien symbolique vers /root/.ssh).
# false : clés classiques dans ~/.ssh/authorized_keys.
ssh_central_authorized_keys: true
# Groupes supplémentaires autorisés en SSH (en plus des ssh_users).
ssh_allow_groups: []
# Durcissement du démon.
ssh_max_auth_tries: 3
ssh_max_sessions: 4
ssh_max_startups: "10:30:60"
ssh_login_grace_time: 30
ssh_client_alive_interval: 300
ssh_client_alive_count_max: 2
ssh_x11_forwarding: false
ssh_agent_forwarding: false
ssh_tcp_forwarding: false
ssh_log_level: VERBOSE
# Algorithmes (Debian/Ubuntu uniquement : sous Red Hat ils sont imposés par
# crypto-policies, ne pas les redéfinir dans sshd_config).
ssh_kex_algorithms:
- [email protected]
- curve25519-sha256
- [email protected]
- diffie-hellman-group16-sha512
- diffie-hellman-group18-sha512
ssh_ciphers:
- [email protected]
- [email protected]
- [email protected]
- aes256-ctr
ssh_macs:
- [email protected]
- [email protected]
- [email protected]
ssh_host_key_algorithms:
- ssh-ed25519
- [email protected]
- rsa-sha2-512
- rsa-sha2-256
ssh_pubkey_accepted_algorithms: "{{ ssh_host_key_algorithms }}"
# Bannière d'avertissement (avant authentification) et MOTD (après).
ssh_banner: true
ssh_banner_organisation: "l'organisation"
# Logo ASCII affiché en tête de bannière (chaîne multiligne, vide = pas de logo).
ssh_banner_logo: ""
ssh_motd: true
# Sous Ubuntu : désactiver les MOTD publicitaires (motd-news, help-text).
ssh_motd_disable_ubuntu_extras: true
# Durcissement du client ssh (ssh_config) : pas d'agent forwarding ni de X11
# par défaut, known_hosts hachés.
ssh_client_hardening: true
# Après redémarrage du démon, ouvrir une NOUVELLE connexion depuis le
# contrôleur pour vérifier qu'on ne s'est pas enfermé dehors.
ssh_verify_new_connection: true
+67
View File
@@ -0,0 +1,67 @@
#!/bin/bash
# Géré par Ansible (rôle ssh) — repris de 01-ssh/00-basic.
# get load averages
IFS=" " read LOAD1 LOAD5 LOAD15 <<<$(awk '{ print $1,$2,$3 }' /proc/loadavg)
# get free memory
IFS=" " read USED AVAIL TOTAL <<<$(free -htm | awk '/Mem/ { print $3,$7,$2 }')
# get processes
PROCESS=$(ps -eo user=|sort|uniq -c | awk '{ print $2 " " $1 }')
PROCESS_ALL=$(echo "$PROCESS"| awk {'print $2'} | awk '{ SUM += $1} END { print SUM }')
PROCESS_ROOT=$(echo "$PROCESS" | awk '/root/ { print $2}')
PROCESS_USER=$(echo "$PROCESS" | awk '!/root/ { SUM += $2} END { print SUM }')
# get processors
PROCESSOR_NAME=$(awk -F": " '/model name/ { print $2 }' /proc/cpuinfo | head -1)
PROCESSOR_COUNT=$(grep -ioPc 'processor\t:' /proc/cpuinfo)
# colors
W="\e[0;39m"
G="\e[1;32m"
R="\e[1;31m"
dim="\e[2m"
undim="\e[0m"
echo -e "${W}System info:
$W Hostname$dim····$undim: $W${HOSTNAME}
$W Distro$dim······$undim: $W$(. /etc/os-release; echo "$PRETTY_NAME")
$W Kernel$dim······$undim: $W$(uname -sr)
$W Uptime$dim······$undim: $W$(uptime -p)
$W Load$dim········$undim: $G$LOAD1$W (1m), $G$LOAD5$W (5m), $G$LOAD15$W (15m)
$W Processes$dim···$undim: $G$PROCESS_ROOT$W (root), $G$PROCESS_USER$W (user), $G$PROCESS_ALL$W (total)
$W CPU$dim·········$undim: $W$PROCESSOR_NAME ($G$PROCESSOR_COUNT$W vCPU)
$W Memory$dim······$undim: $G$USED$W used, $G$AVAIL$W avail, $G$TOTAL$W total"
# config
max_usage=90
bar_width=50
# disk usage: ignore zfs, squashfs & tmpfs
printf "\nDisk usage:\n"
while read line; do
# get disk usage
usage=$(echo "$line" | awk '{print $2}' | sed 's/%//')
used_width=$((($usage*$bar_width)/100))
# color is green if usage < max_usage, else red
if [ "${usage}" -ge "${max_usage}" ]; then
color=$R
else
color=$G
fi
# print green/red bar until used_width
bar="[${color}"
for ((i=0; i<$used_width; i++)); do
bar+="="
done
# print dimmmed bar until end
bar+="${W}${dim}"
for ((i=$used_width; i<$bar_width; i++)); do
bar+="·"
done
bar+="${undim}]"
# print usage line & bar
echo "${line}" | awk '{ printf("%-31s%+3s used out of %+4s\n", $1, $2, $3); }' | sed -e 's/^/ /'
echo -e "${bar}" | sed -e 's/^/ /'
done < <(df -H -x zfs -x squashfs -x tmpfs -x devtmpfs -x overlay -x nfs -x nfs4 -x cifs --output=target,pcent,size | tail -n+2)
printf "\n"
+5
View File
@@ -0,0 +1,5 @@
---
- name: Redémarrer sshd
ansible.builtin.systemd:
name: "{{ ssh_service_name[ansible_facts['os_family']] }}"
state: restarted
+77
View File
@@ -0,0 +1,77 @@
---
- name: Déposer la bannière d'avertissement (SSH et console)
ansible.builtin.template:
src: banner.j2
dest: "{{ item }}"
owner: root
group: root
mode: "0644"
loop:
- /etc/issue.net
- /etc/issue
when: ssh_banner | bool
- name: "Déposer le script MOTD (Debian/Ubuntu : update-motd.d)"
ansible.builtin.copy:
src: 00-basic
dest: /etc/update-motd.d/00-basic
owner: root
group: root
mode: "0755"
when:
- ssh_motd | bool
- ansible_facts['os_family'] == 'Debian'
- name: Désactiver les MOTD annexes d'Ubuntu
ansible.builtin.file:
path: "/etc/update-motd.d/{{ item }}"
mode: "0644"
loop:
- 10-help-text
- 50-motd-news
- 50-landscape-sysinfo
- 88-esm-announce
- 91-contract-ua-esm-status
failed_when: false
when:
- ssh_motd | bool
- ssh_motd_disable_ubuntu_extras | bool
- ansible_facts['distribution'] == 'Ubuntu'
- name: Désactiver motd-news (Ubuntu)
ansible.builtin.lineinfile:
path: /etc/default/motd-news
regexp: '^ENABLED='
line: "ENABLED=0"
create: true
owner: root
group: root
mode: "0644"
when:
- ssh_motd | bool
- ssh_motd_disable_ubuntu_extras | bool
- ansible_facts['distribution'] == 'Ubuntu'
- name: "Déposer le script MOTD (Red Hat : profile.d)"
ansible.builtin.copy:
src: 00-basic
dest: /usr/local/bin/motd-basic
owner: root
group: root
mode: "0755"
when:
- ssh_motd | bool
- ansible_facts['os_family'] == 'RedHat'
- name: Appeler le MOTD à l'ouverture d'un shell interactif (Red Hat)
ansible.builtin.copy:
dest: /etc/profile.d/zz-motd.sh
content: |
# {{ ansible_managed }}
[ -n "$PS1" ] && [ -x /usr/local/bin/motd-basic ] && /usr/local/bin/motd-basic
owner: root
group: root
mode: "0644"
when:
- ssh_motd | bool
- ansible_facts['os_family'] == 'RedHat'
+44
View File
@@ -0,0 +1,44 @@
---
- name: Créer le répertoire central des clés autorisées
ansible.builtin.file:
path: "{{ ssh_central_keys_dir }}"
state: directory
owner: root
group: root
mode: "0755"
- name: Écrire le fichier de clés de chaque compte
ansible.builtin.template:
src: authorized_keys.j2
dest: "{{ ssh_central_keys_dir }}/{{ item.name }}"
owner: root
group: root
mode: "0644"
loop: "{{ ssh_users }}"
loop_control:
label: "{{ item.name }}"
when: ssh_users_keys[item.name] | length > 0
- name: Supprimer le fichier central d'un compte sans clé
ansible.builtin.file:
path: "{{ ssh_central_keys_dir }}/{{ item.name }}"
state: absent
loop: "{{ ssh_users }}"
loop_control:
label: "{{ item.name }}"
when: ssh_users_keys[item.name] | length == 0
- name: Lister les fichiers de clés d'anciens comptes
ansible.builtin.find:
paths: "{{ ssh_central_keys_dir }}"
file_type: file
register: ssh_central_existing
- name: Supprimer les fichiers de clés des comptes qui ne sont plus gérés
ansible.builtin.file:
path: "{{ item.path }}"
state: absent
loop: "{{ ssh_central_existing.files }}"
loop_control:
label: "{{ item.path | basename }}"
when: item.path | basename not in ssh_allow_users_effective
+30
View File
@@ -0,0 +1,30 @@
---
- name: Installer le serveur OpenSSH
ansible.builtin.package:
name: openssh-server
state: present
- name: Préparer les comptes et leurs clés
ansible.builtin.import_tasks: users.yml
- name: Configurer le démon sshd
ansible.builtin.import_tasks: sshd.yml
- name: Déployer la bannière et le MOTD
ansible.builtin.import_tasks: banner_motd.yml
- name: Durcir le client ssh
ansible.builtin.template:
src: ssh_config.j2
dest: "{{ ssh_client_dropin_file }}"
owner: root
group: root
mode: "0644"
when: ssh_client_hardening | bool
- name: Appliquer la configuration sshd maintenant
ansible.builtin.meta: flush_handlers
- name: Vérifier qu'une nouvelle connexion SSH aboutit
ansible.builtin.import_tasks: verify.yml
when: ssh_verify_new_connection | bool
+138
View File
@@ -0,0 +1,138 @@
---
- name: Lire la version du paquet openssh-server
ansible.builtin.package_facts:
manager: auto
- name: Extraire la version d'OpenSSH
ansible.builtin.set_fact:
ssh_version: "{{ ansible_facts['packages']['openssh-server'][0].version | regex_search('([0-9]+\\.[0-9]+)') }}"
- name: Déterminer si sshd prend en charge Include (OpenSSH >= 8.2)
ansible.builtin.set_fact:
ssh_supports_include: "{{ ssh_version is version('8.2', '>=') }}"
- name: Sauvegarder le sshd_config d'origine une seule fois
ansible.builtin.copy:
src: /etc/ssh/sshd_config
dest: /etc/ssh/sshd_config.avant-ansible
remote_src: true
force: false
owner: root
group: root
mode: "0600"
- name: Appliquer le durcissement sshd
block:
- name: Créer le répertoire des drop-ins sshd
ansible.builtin.file:
path: "{{ ssh_dropin_dir }}"
state: directory
owner: root
group: root
mode: "0755"
when: ssh_supports_include | bool
- name: S'assurer que sshd_config inclut le répertoire des drop-ins
ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^\s*Include\s+/etc/ssh/sshd_config\.d/\*\.conf'
line: "Include /etc/ssh/sshd_config.d/*.conf"
insertbefore: BOF
when: ssh_supports_include | bool
notify: Redémarrer sshd
- name: Déposer le drop-in de durcissement
ansible.builtin.template:
src: sshd_durcissement.conf.j2
dest: "{{ ssh_dropin_file }}"
owner: root
group: root
mode: "0600"
when: ssh_supports_include | bool
notify: Redémarrer sshd
- name: Insérer le durcissement en tête de sshd_config (OpenSSH < 8.2)
ansible.builtin.blockinfile:
path: /etc/ssh/sshd_config
block: "{{ lookup('ansible.builtin.template', 'sshd_durcissement.conf.j2') }}"
marker: "# {mark} DURCISSEMENT ANSIBLE"
insertbefore: BOF
when: not ssh_supports_include | bool
notify: Redémarrer sshd
- name: Neutraliser dans sshd_config les directives qui contrediraient le durcissement
ansible.builtin.replace:
path: /etc/ssh/sshd_config
regexp: '^(\s*(?:PermitRootLogin|PasswordAuthentication|AuthorizedKeysFile|X11Forwarding|Banner|PrintMotd)\s.*)$'
replace: '#\1'
after: "# END DURCISSEMENT ANSIBLE"
when: not ssh_supports_include | bool
notify: Redémarrer sshd
- name: Valider la configuration sshd
ansible.builtin.command:
cmd: sshd -t
changed_when: false
rescue:
- name: Retirer le drop-in invalide
ansible.builtin.file:
path: "{{ ssh_dropin_file }}"
state: absent
when: ssh_supports_include | bool
- name: Restaurer sshd_config
ansible.builtin.copy:
src: /etc/ssh/sshd_config.avant-ansible
dest: /etc/ssh/sshd_config
remote_src: true
owner: root
group: root
mode: "0600"
when: not ssh_supports_include | bool
- name: Arrêter sur configuration sshd invalide
ansible.builtin.fail:
msg: "sshd -t a rejeté la configuration : elle a été retirée, le démon n'a pas été redémarré."
- name: Autoriser le port SSH dans SELinux
community.general.seport:
ports: "{{ ssh_port }}"
proto: tcp
setype: ssh_port_t
state: present
when:
- ansible_facts['os_family'] == 'RedHat'
- ansible_facts['selinux'].status | default('disabled') == 'enabled'
- ssh_port | int != 22
- name: Désactiver l'activation par socket (Ubuntu >= 22.10)
ansible.builtin.systemd:
name: ssh.socket
enabled: false
state: stopped
when:
- ansible_facts['distribution'] == 'Ubuntu'
- ansible_facts['distribution_version'] is version('22.10', '>=')
notify: Redémarrer sshd
- name: Lister les clés privées d'hôte
ansible.builtin.find:
paths: /etc/ssh
patterns: "ssh_host_*_key"
register: ssh_host_keys
- name: Restreindre les droits des clés privées d'hôte
ansible.builtin.file:
path: "{{ item.path }}"
owner: root
group: root
mode: "0600"
loop: "{{ ssh_host_keys.files }}"
loop_control:
label: "{{ item.path | basename }}"
- name: Activer et démarrer sshd
ansible.builtin.systemd:
name: "{{ ssh_service_name[ansible_facts['os_family']] }}"
enabled: true
state: started
+89
View File
@@ -0,0 +1,89 @@
---
- name: Recenser les clés publiques disponibles par compte
ansible.builtin.set_fact:
ssh_users_keys: >-
{{ ssh_users_keys | default({}) | combine({
item.name: lookup('ansible.builtin.fileglob', ssh_keys_dir ~ '/' ~ item.name ~ '/*.pub', wantlist=True)
}) }}
loop: "{{ ssh_users }}"
loop_control:
label: "{{ item.name }}"
- name: Calculer la liste AllowUsers
ansible.builtin.set_fact:
ssh_allow_users_effective: "{{ ssh_users | map(attribute='name') | list }}"
- name: Refuser une configuration qui enfermerait Ansible dehors
ansible.builtin.assert:
that:
- ssh_users | length > 0
- (ssh_users_keys | default({})).values() | map('length') | sum > 0
- ssh_ansible_login in ssh_allow_users_effective or ssh_allow_groups | length > 0
- ssh_users_keys[ssh_ansible_login] | default([]) | length > 0 or ssh_allow_groups | length > 0
- not (ssh_ansible_login == 'root' and ssh_permit_root_login == 'no')
fail_msg: >-
Le compte de connexion Ansible « {{ ssh_ansible_login }} » doit figurer dans ssh_users
avec au moins une clé dans {{ ssh_keys_dir }}/{{ ssh_ansible_login }}/*.pub,
et ssh_permit_root_login ne peut pas valoir « no » si Ansible se connecte en root.
vars:
ssh_ansible_login: "{{ ansible_user | default('root') }}"
- name: Créer les comptes (hors root)
ansible.builtin.user:
name: "{{ item.name }}"
shell: "{{ item.shell | default('/bin/bash') }}"
groups: "{{ item.groups | default([]) | map('replace', 'sudo_or_wheel', common_sudo_group_effective) | list }}"
append: true
password: "{{ item.password_hash | default(omit) }}"
create_home: true
state: present
loop: "{{ ssh_users }}"
loop_control:
label: "{{ item.name }}"
when: item.name != 'root'
no_log: true
- name: Autoriser sudo sans mot de passe pour les comptes de service
ansible.builtin.copy:
dest: "/etc/sudoers.d/90-{{ item.name }}"
content: |
# {{ ansible_managed }}
{{ item.name }} ALL=(ALL) NOPASSWD:ALL
owner: root
group: root
mode: "0440"
validate: /usr/sbin/visudo -cf %s
loop: "{{ ssh_users }}"
loop_control:
label: "{{ item.name }}"
when:
- item.name != 'root'
- item.sudo_nopasswd | default(false) | bool
- name: Retirer le sudo sans mot de passe des comptes qui ne le demandent plus
ansible.builtin.file:
path: "/etc/sudoers.d/90-{{ item.name }}"
state: absent
loop: "{{ ssh_users }}"
loop_control:
label: "{{ item.name }}"
when:
- item.name != 'root'
- not (item.sudo_nopasswd | default(false) | bool)
- name: Déployer les clés autorisées (répertoire central)
ansible.builtin.import_tasks: keys_central.yml
when: ssh_central_authorized_keys | bool
- name: Déployer les clés autorisées (~/.ssh)
ansible.posix.authorized_key:
user: "{{ item.name }}"
key: "{{ ssh_users_keys[item.name] | map('ansible.builtin.file') | join('\n') }}"
exclusive: true
manage_dir: true
loop: "{{ ssh_users }}"
loop_control:
label: "{{ item.name }}"
when:
- not ssh_central_authorized_keys | bool
- ssh_users_keys[item.name] | length > 0
+26
View File
@@ -0,0 +1,26 @@
---
- name: Construire la commande de vérification
ansible.builtin.set_fact:
ssh_verify_argv: >-
{{ ['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'StrictHostKeyChecking=accept-new',
'-o', 'ControlPath=none', '-p', ssh_port | string]
+ (['-i', ansible_ssh_private_key_file] if ansible_ssh_private_key_file is defined else [])
+ [(ansible_user | default('root')) ~ '@' ~ (ansible_host | default(inventory_hostname)), 'true'] }}
- name: Ouvrir une nouvelle session SSH depuis le contrôleur
ansible.builtin.command:
argv: "{{ ssh_verify_argv }}"
delegate_to: localhost
become: false
register: ssh_verify
changed_when: false
failed_when: false
- name: Signaler un échec de connexion après durcissement
ansible.builtin.fail:
msg: >-
Une NOUVELLE connexion SSH vers {{ inventory_hostname }} échoue (code {{ ssh_verify.rc }}).
La session courante reste ouverte : vérifier {{ ssh_dropin_file }} et
{{ ssh_central_keys_dir if ssh_central_authorized_keys else '~/.ssh/authorized_keys' }}
avant de la fermer.
when: ssh_verify.rc != 0
+5
View File
@@ -0,0 +1,5 @@
# {{ ansible_managed }}
# Source : files/keys/{{ item.name }}/*.pub
{% for key_file in ssh_users_keys[item.name] | sort %}
{{ lookup('ansible.builtin.file', key_file) | trim }}
{% endfor %}
+16
View File
@@ -0,0 +1,16 @@
{% if ssh_banner_logo | length > 0 %}
{{ ssh_banner_logo | regex_replace('\\s+$', '') }}
{% endif %}
AVERTISSEMENT : L'accès à ce système est réservé aux utilisateurs
dûment autorisés.
Toute tentative d'accès à ce système sans autorisation, ou de maintien
frauduleux dans ce système, fera l'objet de poursuites conformément à
la politique de {{ ssh_banner_organisation }}.
Tout utilisateur autorisé est informé et reconnaît que ses actions
peuvent être enregistrées, conservées et auditées conformément aux
chartes et politiques internes de {{ ssh_banner_organisation }}.
+10
View File
@@ -0,0 +1,10 @@
# {{ ansible_managed }}
Host *
ForwardAgent no
ForwardX11 no
HashKnownHosts yes
GSSAPIAuthentication no
StrictHostKeyChecking ask
SendEnv LANG LC_*
ServerAliveInterval 60
ServerAliveCountMax 3
@@ -0,0 +1,62 @@
# {{ ansible_managed }}
# Première valeur lue = valeur retenue : ce fichier est lu avant sshd_config.
Port {{ ssh_port }}
LogLevel {{ ssh_log_level }}
# Authentification : clé publique uniquement, jamais de mot de passe à distance.
PermitRootLogin {{ ssh_permit_root_login }}
PubkeyAuthentication yes
AuthenticationMethods publickey
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitEmptyPasswords no
HostbasedAuthentication no
IgnoreRhosts yes
StrictModes yes
UsePAM yes
{% if ssh_central_authorized_keys %}
AuthorizedKeysFile {{ ssh_central_keys_dir }}/%u
{% else %}
AuthorizedKeysFile .ssh/authorized_keys
{% endif %}
AllowUsers {{ ssh_allow_users_effective | join(' ') }}
{% if ssh_allow_groups | length > 0 %}
AllowGroups {{ ssh_allow_groups | join(' ') }}
{% endif %}
# Limites anti-force-brute et sessions inactives.
MaxAuthTries {{ ssh_max_auth_tries }}
MaxSessions {{ ssh_max_sessions }}
MaxStartups {{ ssh_max_startups }}
LoginGraceTime {{ ssh_login_grace_time }}
ClientAliveInterval {{ ssh_client_alive_interval }}
ClientAliveCountMax {{ ssh_client_alive_count_max }}
# Surface réduite.
X11Forwarding {{ 'yes' if ssh_x11_forwarding else 'no' }}
AllowAgentForwarding {{ 'yes' if ssh_agent_forwarding else 'no' }}
AllowTcpForwarding {{ 'yes' if ssh_tcp_forwarding else 'no' }}
PermitTunnel no
GatewayPorts no
PermitUserEnvironment no
UseDNS no
{% if ansible_facts['os_family'] == 'Debian' %}
DebianBanner no
# Algorithmes (Red Hat : gérés par crypto-policies).
KexAlgorithms {{ ssh_kex_algorithms | join(',') }}
Ciphers {{ ssh_ciphers | join(',') }}
MACs {{ ssh_macs | join(',') }}
HostKeyAlgorithms {{ ssh_host_key_algorithms | join(',') }}
PubkeyAcceptedAlgorithms {{ ssh_pubkey_accepted_algorithms | join(',') }}
{% endif %}
# Affichage.
{% if ssh_banner %}
Banner /etc/issue.net
{% else %}
Banner none
{% endif %}
PrintMotd no
PrintLastLog yes
+11
View File
@@ -0,0 +1,11 @@
---
ssh_service_name:
Debian: ssh
RedHat: sshd
ssh_dropin_dir: /etc/ssh/sshd_config.d
# « 00- » : les fichiers inclus sont lus par ordre lexical et la PREMIÈRE
# valeur rencontrée l'emporte. Nos réglages passent donc avant
# 50-cloud-init.conf (Ubuntu) et 50-redhat.conf (Red Hat).
ssh_dropin_file: "{{ ssh_dropin_dir }}/00-durcissement.conf"
ssh_client_dropin_file: /etc/ssh/ssh_config.d/00-durcissement.conf
ssh_central_keys_dir: /etc/ssh/authorized_keys
+10
View File
@@ -0,0 +1,10 @@
---
# Rôle updates — reprend 02-apt (update + full-upgrade) et ajoute les mises à
# jour de sécurité automatiques (unattended-upgrades / dnf-automatic).
updates_upgrade_now: true
updates_automatic: true
# Redémarrage automatique en fin de passage si le noyau l'exige.
# false par défaut : le résumé de fin de playbook signale le besoin.
updates_reboot_if_required: false
# Heure des mises à jour automatiques (dnf-automatic uniquement, format OnCalendar).
updates_automatic_schedule: "*-*-* 04:00"
+4
View File
@@ -0,0 +1,4 @@
---
- name: Recharger systemd
ansible.builtin.systemd:
daemon_reload: true
+45
View File
@@ -0,0 +1,45 @@
---
- name: Mettre à jour tous les paquets (full-upgrade)
ansible.builtin.apt:
update_cache: true
upgrade: full
autoremove: true
autoclean: true
when: updates_upgrade_now | bool
- name: Installer unattended-upgrades
ansible.builtin.apt:
name:
- unattended-upgrades
- apt-listchanges
state: present
when: updates_automatic | bool
- name: Activer les mises à jour automatiques
ansible.builtin.copy:
dest: /etc/apt/apt.conf.d/20auto-upgrades
content: |
// {{ ansible_managed }}
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
owner: root
group: root
mode: "0644"
when: updates_automatic | bool
- name: Limiter unattended-upgrades aux mises à jour de sécurité
ansible.builtin.template:
src: 52unattended-upgrades-local.j2
dest: /etc/apt/apt.conf.d/52unattended-upgrades-local
owner: root
group: root
mode: "0644"
when: updates_automatic | bool
- name: Activer le service unattended-upgrades
ansible.builtin.systemd:
name: unattended-upgrades
enabled: true
state: started
when: updates_automatic | bool
+31
View File
@@ -0,0 +1,31 @@
---
- name: Mettre à jour le système
ansible.builtin.include_tasks: "{{ ansible_facts['os_family'] | lower }}.yml"
- name: Déterminer si un redémarrage est nécessaire (Debian)
ansible.builtin.stat:
path: /var/run/reboot-required
register: updates_reboot_file
when: ansible_facts['os_family'] == 'Debian'
- name: Déterminer si un redémarrage est nécessaire (Red Hat)
ansible.builtin.command:
cmd: dnf needs-restarting -r
register: updates_needs_restarting
changed_when: false
failed_when: updates_needs_restarting.rc not in [0, 1]
when: ansible_facts['os_family'] == 'RedHat'
- name: Exposer l'état de redémarrage
ansible.builtin.set_fact:
updates_reboot_required: >-
{{ (updates_reboot_file.stat.exists | default(false))
or (updates_needs_restarting.rc | default(0) == 1) }}
- name: Redémarrer le serveur
ansible.builtin.reboot:
msg: "Redémarrage planifié par Ansible (mises à jour)"
reboot_timeout: 600
when:
- updates_reboot_if_required | bool
- updates_reboot_required | bool
+65
View File
@@ -0,0 +1,65 @@
---
- name: Mettre à jour tous les paquets # noqa: package-latest — mise à jour complète voulue
ansible.builtin.dnf:
name: "*"
state: latest
update_cache: true
when: updates_upgrade_now | bool
- name: Installer dnf-automatic
ansible.builtin.dnf:
name: dnf-automatic
state: present
when: updates_automatic | bool
- name: Limiter dnf-automatic aux mises à jour de sécurité
community.general.ini_file:
path: /etc/dnf/automatic.conf
section: "{{ item.section }}"
option: "{{ item.option }}"
value: "{{ item.value }}"
no_extra_spaces: true
owner: root
group: root
mode: "0644"
loop:
- { section: commands, option: upgrade_type, value: security }
- { section: commands, option: apply_updates, value: "yes" }
- { section: commands, option: download_updates, value: "yes" }
- { section: emitters, option: emit_via, value: stdio }
loop_control:
label: "{{ item.option }}"
when: updates_automatic | bool
- name: Créer le répertoire de surcharge du timer
ansible.builtin.file:
path: /etc/systemd/system/dnf-automatic.timer.d
state: directory
owner: root
group: root
mode: "0755"
when: updates_automatic | bool
- name: Planifier dnf-automatic
ansible.builtin.copy:
dest: /etc/systemd/system/dnf-automatic.timer.d/override.conf
content: |
# {{ ansible_managed }}
[Timer]
OnCalendar=
OnCalendar={{ updates_automatic_schedule }}
RandomizedDelaySec=30m
owner: root
group: root
mode: "0644"
when: updates_automatic | bool
notify: Recharger systemd
- name: Activer le timer dnf-automatic
ansible.builtin.systemd:
name: dnf-automatic.timer
enabled: true
state: started
daemon_reload: true
when: updates_automatic | bool
@@ -0,0 +1,14 @@
// {{ ansible_managed }}
Unattended-Upgrade::Origins-Pattern {
{% if ansible_facts['distribution'] == 'Ubuntu' %}
"origin=Ubuntu,archive=${distro_codename}-security";
"origin=UbuntuESMApps,archive=${distro_codename}-apps-security";
"origin=UbuntuESM,archive=${distro_codename}-infra-security";
{% else %}
"origin=Debian,codename=${distro_codename},label=Debian-Security";
"origin=Debian,codename=${distro_codename}-security,label=Debian-Security";
{% endif %}
};
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";
+68
View File
@@ -0,0 +1,68 @@
---
# Point d'entrée : configure et durcit l'ensemble des serveurs Linux.
#
# ansible-playbook site.yml # tout
# ansible-playbook site.yml --tags ssh # un seul rôle
# ansible-playbook site.yml --check --diff # simulation
#
# Ordre volontaire : le proxy et le DNS d'abord (sinon aucun paquet ne peut
# être téléchargé), le SSH avant le pare-feu (la règle SSH doit exister
# avant que la politique par défaut passe à « drop »).
- name: Configuration et durcissement des serveurs Linux
hosts: all
become: true
gather_facts: true
roles:
- role: common
tags: [common, always]
- role: proxy
when: enable_proxy | bool
tags: [proxy]
- role: dns
when: enable_dns | bool
tags: [dns]
- role: updates
when: enable_updates | bool
tags: [updates]
- role: ssh
when: enable_ssh | bool
tags: [ssh]
- role: firewall
when: enable_firewall | bool
tags: [firewall]
- role: fail2ban
when: enable_fail2ban | bool
tags: [fail2ban]
- role: os_hardening
when: enable_os_hardening | bool
tags: [os_hardening, hardening]
- role: snmp
when: enable_snmp | bool
tags: [snmp, supervision]
- role: nrpe
when: enable_nrpe | bool
tags: [nrpe, supervision]
- role: glpi_agent
when: enable_glpi_agent | bool
tags: [glpi, glpi_agent]
post_tasks:
- name: Résumé de fin de passage
ansible.builtin.debug:
msg:
- "Hôte : {{ inventory_hostname }} ({{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }})"
- "SSH : port {{ ssh_port }}, root={{ ssh_permit_root_login }}"
- "Pare-feu : {{ firewall_backend_effective | default('non géré') }}"
- "Redémarrage : {{ 'REQUIS' if (updates_reboot_required | default(false)) else 'non requis' }}"
tags: [always]