From 29ea40bf8eff121cbb2a0b149c5ef16908ade5ff Mon Sep 17 00:00:00 2001 From: maxime Date: Sat, 4 Apr 2026 18:25:21 +0200 Subject: [PATCH] 1.0 --- .gitignore | 2 + LICENSE | 73 +++ README.md | 90 ++++ ansible.cfg | 675 +++++++++++++++++++++++++++ ansible/inventory/inventory.ini | 5 + ansible/playbook/deploy_firewall.yml | 28 ++ ansible/playbook/setup_db.yml | 17 + ansible/playbook/site.yml | 8 + modules/nftables.conf | 30 ++ requirement/main.sh | 162 +++++++ 10 files changed, 1090 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 ansible.cfg create mode 100644 ansible/inventory/inventory.ini create mode 100644 ansible/playbook/deploy_firewall.yml create mode 100644 ansible/playbook/setup_db.yml create mode 100644 ansible/playbook/site.yml create mode 100644 modules/nftables.conf create mode 100755 requirement/main.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fc01323 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*log +.venv* \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ab478af --- /dev/null +++ b/LICENSE @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright 2026 maxime derick + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..de65a6a --- /dev/null +++ b/README.md @@ -0,0 +1,90 @@ + +>🚀 Ansible Training: Database & Firewall Deployment + + +Ce projet est un bac Ă  sable (sandbox) destinĂ© Ă  apprendre et pratiquer l'automatisation avec Ansible. L'objectif est de dĂ©ployer une pile de base de donnĂ©es sĂ©curisĂ©e sur une machine virtuelle Linux distante. +📋 PrĂ©sentation du Projet + +--- +L'automatisation rĂ©alise les actions suivantes : + + Mise Ă  jour des dĂ©pĂŽts et installation du serveur/client MariaDB. + + Configuration du Pare-feu via nftables (dĂ©ploiement d'un fichier de configuration personnalisĂ©). + + Gestion des services : s'assure que la base de donnĂ©es et le firewall sont actifs et activĂ©s au dĂ©marrage. + +--- + +### đŸ—ïž Architecture + + Machine de contrĂŽle : Mon PC local (sous Linux/WSL). + + Machine distante (Managed Node) : VM d'entraĂźnement Linux (Debian/Ubuntu). + + IP : 192.168.1.119 (configurĂ©e dans l'inventaire). + + Utilisateur : maxime avec privilĂšges sudo. + +--- + +### 📁 Structure du Projet + +``` +Plaintext + +. +├── ansible.cfg # Configuration globale d'Ansible (remote_user, become, etc.) +├── ansible/ +│ ├── inventory/ +│ │ └── inventory.ini # Liste des hĂŽtes et variables de connexion +│ ├── playbook/ +│ │ └── site.yml # Master Playbook (point d'entrĂ©e) +│ └── modules/ # Fichiers de configuration Ă  dĂ©ployer +│ └── nftables.conf +└── README.md # Cette documentation + +``` + + + +### 🚀 Utilisation + +## PrĂ©-requis + + Ansible installĂ© localement. + + L'utilitaire sshpass (pour la connexion par mot de passe). + + Une VM Linux accessible via SSH. + +--- + +## Lancer le dĂ©ploiement + +Pour exĂ©cuter l'intĂ©gralitĂ© de la configuration, utilise la commande suivante : +Bash + +ansible-playbook -i ansible/inventory/inventory.ini ansible/playbook/site.yml -k -K + + -k : Demande le mot de passe SSH. + + -K : Demande le mot de passe SUDO (become). + + +--- + +### Concepts abordĂ©s + +``` +Au cours de cet entraĂźnement, les concepts suivants ont Ă©tĂ© abordĂ©s : + + Idempotence : Relancer le playbook ne modifie le serveur que si nĂ©cessaire. + + Gestion des Handlers : RedĂ©marrage automatique des services uniquement en cas de changement de configuration. + + Escalade de privilĂšges : Utilisation de become pour les tĂąches administratives. + + Structure de projet : Organisation des fichiers et gestion des chemins relatifs. + +``` \ No newline at end of file diff --git a/ansible.cfg b/ansible.cfg new file mode 100644 index 0000000..9a357b0 --- /dev/null +++ b/ansible.cfg @@ -0,0 +1,675 @@ +[defaults] +# (boolean) By default Ansible will issue a warning when received from a task action (module or action plugin) +# These warnings can be silenced by adjusting this setting to False. +;action_warnings=True + +# (list) Accept list of cowsay templates that are 'safe' to use, set to empty list if you want to enable all installed templates. +;cowsay_enabled_stencils=bud-frogs, bunny, cheese, daemon, default, dragon, elephant-in-snake, elephant, eyes, hellokitty, kitty, luke-koala, meow, milk, moofasa, moose, ren, sheep, small, stegosaurus, stimpy, supermilker, three-eyes, turkey, turtle, tux, udder, vader-koala, vader, www + +# (string) Specify a custom cowsay path or swap in your cowsay implementation of choice +;cowpath= + +# (string) This allows you to chose a specific cowsay stencil for the banners or use 'random' to cycle through them. +;cow_selection=default + +# (boolean) This option forces color mode even when running without a TTY or the "nocolor" setting is True. +;force_color=False + +# (path) The default root path for Ansible config files on the controller. +;home=~/.ansible + +# (boolean) This setting allows suppressing colorizing output, which is used to give a better indication of failure and status information. +;nocolor=False + +# (boolean) If you have cowsay installed but want to avoid the 'cows' (why????), use this. +;nocows=False + +# (boolean) Sets the default value for the any_errors_fatal keyword, if True, Task failures will be considered fatal errors. +;any_errors_fatal=False + +# (path) The password file to use for the become plugin. --become-password-file. +# If executable, it will be run and the resulting stdout will be used as the password. +;become_password_file= + +# (pathspec) Colon separated paths in which Ansible will search for Become Plugins. +;become_plugins={{ ANSIBLE_HOME ~ "/plugins/become:/usr/share/ansible/plugins/become" }} + +# (string) Chooses which cache plugin to use, the default 'memory' is ephemeral. +;fact_caching=memory + +# (string) Defines connection or path information for the cache plugin +;fact_caching_connection= + +# (string) Prefix to use for cache plugin files/tables +;fact_caching_prefix=ansible_facts + +# (integer) Expiration timeout for the cache plugin data +;fact_caching_timeout=86400 + +# (list) List of enabled callbacks, not all callbacks need enabling, but many of those shipped with Ansible do as we don't want them activated by default. +;callbacks_enabled= + +# (string) When a collection is loaded that does not support the running Ansible version (with the collection metadata key `requires_ansible`). +;collections_on_ansible_version_mismatch=warning + +# (pathspec) Colon separated paths in which Ansible will search for collections content. Collections must be in nested *subdirectories*, not directly in these directories. For example, if ``COLLECTIONS_PATHS`` includes ``'{{ ANSIBLE_HOME ~ "/collections" }}'``, and you want to add ``my.collection`` to that directory, it must be saved as ``'{{ ANSIBLE_HOME} ~ "/collections/ansible_collections/my/collection" }}'``. + +;collections_path={{ ANSIBLE_HOME ~ "/collections:/usr/share/ansible/collections" }} + +# (boolean) A boolean to enable or disable scanning the sys.path for installed collections +;collections_scan_sys_path=True + +# (path) The password file to use for the connection plugin. --connection-password-file. +;connection_password_file= + +# (pathspec) Colon separated paths in which Ansible will search for Action Plugins. +;action_plugins={{ ANSIBLE_HOME ~ "/plugins/action:/usr/share/ansible/plugins/action" }} + +# (boolean) When enabled, this option allows lookup plugins (whether used in variables as ``{{lookup('foo')}}`` or as a loop as with_foo) to return data that is not marked 'unsafe'. +# By default, such data is marked as unsafe to prevent the templating engine from evaluating any jinja2 templating language, as this could represent a security risk. This option is provided to allow for backward compatibility, however users should first consider adding allow_unsafe=True to any lookups which may be expected to contain data which may be run through the templating engine late +;allow_unsafe_lookups=False + +# (boolean) This controls whether an Ansible playbook should prompt for a login password. If using SSH keys for authentication, you probably do not need to change this setting. +;ask_pass=False + +# (boolean) This controls whether an Ansible playbook should prompt for a vault password. +;ask_vault_pass=False + +# (pathspec) Colon separated paths in which Ansible will search for Cache Plugins. +;cache_plugins={{ ANSIBLE_HOME ~ "/plugins/cache:/usr/share/ansible/plugins/cache" }} + +# (pathspec) Colon separated paths in which Ansible will search for Callback Plugins. +;callback_plugins={{ ANSIBLE_HOME ~ "/plugins/callback:/usr/share/ansible/plugins/callback" }} + +# (pathspec) Colon separated paths in which Ansible will search for Cliconf Plugins. +;cliconf_plugins={{ ANSIBLE_HOME ~ "/plugins/cliconf:/usr/share/ansible/plugins/cliconf" }} + +# (pathspec) Colon separated paths in which Ansible will search for Connection Plugins. +;connection_plugins={{ ANSIBLE_HOME ~ "/plugins/connection:/usr/share/ansible/plugins/connection" }} + +# (boolean) Toggles debug output in Ansible. This is *very* verbose and can hinder multiprocessing. Debug output can also include secret information despite no_log settings being enabled, which means debug mode should not be used in production. +;debug=False + +# (string) This indicates the command to use to spawn a shell under for Ansible's execution needs on a target. Users may need to change this in rare instances when shell usage is constrained, but in most cases it may be left as is. +;executable=/bin/sh + +# (string) This option allows you to globally configure a custom path for 'local_facts' for the implied :ref:`ansible_collections.ansible.builtin.setup_module` task when using fact gathering. +# If not set, it will fallback to the default from the ``ansible.builtin.setup`` module: ``/etc/ansible/facts.d``. +# This does **not** affect user defined tasks that use the ``ansible.builtin.setup`` module. +# The real action being created by the implicit task is currently ``ansible.legacy.gather_facts`` module, which then calls the configured fact modules, by default this will be ``ansible.builtin.setup`` for POSIX systems but other platforms might have different defaults. +;fact_path= + +# (pathspec) Colon separated paths in which Ansible will search for Jinja2 Filter Plugins. +;filter_plugins={{ ANSIBLE_HOME ~ "/plugins/filter:/usr/share/ansible/plugins/filter" }} + +# (boolean) This option controls if notified handlers run on a host even if a failure occurs on that host. +# When false, the handlers will not run if a failure has occurred on a host. +# This can also be set per play or on the command line. See Handlers and Failure for more details. +;force_handlers=False + +# (integer) Maximum number of forks Ansible will use to execute tasks on target hosts. +forks=5 + +# (string) This setting controls the default policy of fact gathering (facts discovered about remote systems). +# This option can be useful for those wishing to save fact gathering time. Both 'smart' and 'explicit' will use the cache plugin. +;gathering=implicit + +# (list) Set the `gather_subset` option for the :ref:`ansible_collections.ansible.builtin.setup_module` task in the implicit fact gathering. See the module documentation for specifics. +# It does **not** apply to user defined ``ansible.builtin.setup`` tasks. +;gather_subset= + +# (integer) Set the timeout in seconds for the implicit fact gathering, see the module documentation for specifics. +# It does **not** apply to user defined :ref:`ansible_collections.ansible.builtin.setup_module` tasks. +;gather_timeout= + +# (string) This setting controls how duplicate definitions of dictionary variables (aka hash, map, associative array) are handled in Ansible. +# This does not affect variables whose values are scalars (integers, strings) or arrays. +# **WARNING**, changing this setting is not recommended as this is fragile and makes your content (plays, roles, collections) non portable, leading to continual confusion and misuse. Don't change this setting unless you think you have an absolute need for it. +# We recommend avoiding reusing variable names and relying on the ``combine`` filter and ``vars`` and ``varnames`` lookups to create merged versions of the individual variables. In our experience this is rarely really needed and a sign that too much complexity has been introduced into the data structures and plays. +# For some uses you can also look into custom vars_plugins to merge on input, even substituting the default ``host_group_vars`` that is in charge of parsing the ``host_vars/`` and ``group_vars/`` directories. Most users of this setting are only interested in inventory scope, but the setting itself affects all sources and makes debugging even harder. +# All playbooks and roles in the official examples repos assume the default for this setting. +# Changing the setting to ``merge`` applies across variable sources, but many sources will internally still overwrite the variables. For example ``include_vars`` will dedupe variables internally before updating Ansible, with 'last defined' overwriting previous definitions in same file. +# The Ansible project recommends you **avoid ``merge`` for new projects.** +# It is the intention of the Ansible developers to eventually deprecate and remove this setting, but it is being kept as some users do heavily rely on it. New projects should **avoid 'merge'**. +;hash_behaviour=replace + +# (pathlist) Comma separated list of Ansible inventory sources +inventory=./inventory/inventory.ini + +# (pathspec) Colon separated paths in which Ansible will search for HttpApi Plugins. +;httpapi_plugins={{ ANSIBLE_HOME ~ "/plugins/httpapi:/usr/share/ansible/plugins/httpapi" }} + +# (float) This sets the interval (in seconds) of Ansible internal processes polling each other. Lower values improve performance with large playbooks at the expense of extra CPU load. Higher values are more suitable for Ansible usage in automation scenarios, when UI responsiveness is not required but CPU usage might be a concern. +# The default corresponds to the value hardcoded in Ansible <= 2.1 +;internal_poll_interval=0.001 + +# (pathspec) Colon separated paths in which Ansible will search for Inventory Plugins. +;inventory_plugins={{ ANSIBLE_HOME ~ "/plugins/inventory:/usr/share/ansible/plugins/inventory" }} + +# (string) This is a developer-specific feature that allows enabling additional Jinja2 extensions. +# See the Jinja2 documentation for details. If you do not know what these do, you probably don't need to change this setting :) +;jinja2_extensions=[] + +# (boolean) This option preserves variable types during template operations. +;jinja2_native=False + +# (boolean) Enables/disables the cleaning up of the temporary files Ansible used to execute the tasks on the remote. +# If this option is enabled it will disable ``ANSIBLE_PIPELINING``. +;keep_remote_files=False + +# (boolean) Controls whether callback plugins are loaded when running /usr/bin/ansible. This may be used to log activity from the command line, send notifications, and so on. Callback plugins are always loaded for ``ansible-playbook``. +;bin_ansible_callbacks=False + +# (tmppath) Temporary directory for Ansible to use on the controller. +;local_tmp={{ ANSIBLE_HOME ~ "/tmp" }} + +# (list) List of logger names to filter out of the log file +;log_filter= + +# (path) File to which Ansible will log on the controller. When empty logging is disabled. +log_path=./ansible_log.log + +# (pathspec) Colon separated paths in which Ansible will search for Lookup Plugins. +;lookup_plugins={{ ANSIBLE_HOME ~ "/plugins/lookup:/usr/share/ansible/plugins/lookup" }} + +# (string) Sets the macro for the 'ansible_managed' variable available for :ref:`ansible_collections.ansible.builtin.template_module` and :ref:`ansible_collections.ansible.windows.win_template_module`. This is only relevant for those two modules. +;ansible_managed=Ansible managed + +# (string) This sets the default arguments to pass to the ``ansible`` adhoc binary if no ``-a`` is specified. +;module_args= + +# (string) Compression scheme to use when transferring Python modules to the target. +;module_compression=ZIP_DEFLATED + +# (string) Module to use with the ``ansible`` AdHoc command, if none is specified via ``-m``. +;module_name=command + +# (pathspec) Colon separated paths in which Ansible will search for Modules. +;library={{ ANSIBLE_HOME ~ "/plugins/modules:/usr/share/ansible/plugins/modules" }} + +# (pathspec) Colon separated paths in which Ansible will search for Module utils files, which are shared by modules. +;module_utils={{ ANSIBLE_HOME ~ "/plugins/module_utils:/usr/share/ansible/plugins/module_utils" }} + +# (pathspec) Colon separated paths in which Ansible will search for Netconf Plugins. +;netconf_plugins={{ ANSIBLE_HOME ~ "/plugins/netconf:/usr/share/ansible/plugins/netconf" }} + +# (boolean) Toggle Ansible's display and logging of task details, mainly used to avoid security disclosures. +;no_log=False + +# (boolean) Toggle Ansible logging to syslog on the target when it executes tasks. On Windows hosts this will disable a newer style PowerShell modules from writing to the event log. +;no_target_syslog=False + +# (raw) What templating should return as a 'null' value. When not set it will let Jinja2 decide. +;null_representation= + +# (integer) For asynchronous tasks in Ansible (covered in Asynchronous Actions and Polling), this is how often to check back on the status of those tasks when an explicit poll interval is not supplied. The default is a reasonably moderate 15 seconds which is a tradeoff between checking in frequently and providing a quick turnaround when something may have completed. +;poll_interval=15 + +# (path) Option for connections using a certificate or key file to authenticate, rather than an agent or passwords, you can set the default value here to avoid re-specifying --private-key with every invocation. +;private_key_file= + +# (boolean) Makes role variables inaccessible from other roles. +# This was introduced as a way to reset role variables to default values if a role is used more than once in a playbook. +;private_role_vars=False + +# (integer) Port to use in remote connections, when blank it will use the connection plugin default. +;remote_port= + +# (string) Sets the login user for the target machines +# When blank it uses the connection plugin's default, normally the user currently executing Ansible. +remote_user=maxime + +# (pathspec) Colon separated paths in which Ansible will search for Roles. +;roles_path={{ ANSIBLE_HOME ~ "/roles:/usr/share/ansible/roles:/etc/ansible/roles" }} + +# (string) Set the main callback used to display Ansible output. You can only have one at a time. +# You can have many other callbacks, but just one can be in charge of stdout. +# See :ref:`callback_plugins` for a list of available options. +;stdout_callback=default + +# (string) Set the default strategy used for plays. +;strategy=linear + +# (pathspec) Colon separated paths in which Ansible will search for Strategy Plugins. +;strategy_plugins={{ ANSIBLE_HOME ~ "/plugins/strategy:/usr/share/ansible/plugins/strategy" }} + +# (boolean) Toggle the use of "su" for tasks. +;su=False + +# (string) Syslog facility to use when Ansible logs to the remote target +;syslog_facility=LOG_USER + +# (pathspec) Colon separated paths in which Ansible will search for Terminal Plugins. +;terminal_plugins={{ ANSIBLE_HOME ~ "/plugins/terminal:/usr/share/ansible/plugins/terminal" }} + +# (pathspec) Colon separated paths in which Ansible will search for Jinja2 Test Plugins. +;test_plugins={{ ANSIBLE_HOME ~ "/plugins/test:/usr/share/ansible/plugins/test" }} + +# (integer) This is the default timeout for connection plugins to use. +;timeout=10 + +# (string) Default connection plugin to use, the 'smart' option will toggle between 'ssh' and 'paramiko' depending on controller OS and ssh versions +;transport=smart + +# (boolean) When True, this causes ansible templating to fail steps that reference variable names that are likely typoed. +# Otherwise, any '{{ template_expression }}' that contains undefined variables will be rendered in a template or ansible action line exactly as written. +;error_on_undefined_vars=True + +# (pathspec) Colon separated paths in which Ansible will search for Vars Plugins. +;vars_plugins={{ ANSIBLE_HOME ~ "/plugins/vars:/usr/share/ansible/plugins/vars" }} + +# (string) The vault_id to use for encrypting by default. If multiple vault_ids are provided, this specifies which to use for encryption. The --encrypt-vault-id cli option overrides the configured value. +;vault_encrypt_identity= + +# (string) The label to use for the default vault id label in cases where a vault id label is not provided +;vault_identity=default + +# (list) A list of vault-ids to use by default. Equivalent to multiple --vault-id args. Vault-ids are tried in order. +;vault_identity_list= + +# (string) If true, decrypting vaults with a vault id will only try the password from the matching vault-id +;vault_id_match=False + +# (path) The vault password file to use. Equivalent to --vault-password-file or --vault-id +# If executable, it will be run and the resulting stdout will be used as the password. +;vault_password_file= + +# (integer) Sets the default verbosity, equivalent to the number of ``-v`` passed in the command line. +verbosity=0 + +# (boolean) Toggle to control the showing of deprecation warnings +;deprecation_warnings=True + +# (boolean) Toggle to control showing warnings related to running devel +devel_warning=True + +# (boolean) Normally ``ansible-playbook`` will print a header for each task that is run. These headers will contain the name: field from the task if you specified one. If you didn't then ``ansible-playbook`` uses the task's action to help you tell which task is presently running. Sometimes you run many of the same action and so you want more information about the task to differentiate it from others of the same action. If you set this variable to True in the config then ``ansible-playbook`` will also include the task's arguments in the header. +# This setting defaults to False because there is a chance that you have sensitive values in your parameters and you do not want those to be printed. +# If you set this to True you should be sure that you have secured your environment's stdout (no one can shoulder surf your screen and you aren't saving stdout to an insecure file) or made sure that all of your playbooks explicitly added the ``no_log: True`` parameter to tasks which have sensitive values See How do I keep secret data in my playbook? for more information. +;display_args_to_stdout=False + +# (boolean) Toggle to control displaying skipped task/host entries in a task in the default callback +;display_skipped_hosts=True + +# (string) Root docsite URL used to generate docs URLs in warning/error text; must be an absolute URL with valid scheme and trailing slash. +;docsite_root_url=https://docs.ansible.com/ansible-core/ + +# (pathspec) Colon separated paths in which Ansible will search for Documentation Fragments Plugins. +;doc_fragment_plugins={{ ANSIBLE_HOME ~ "/plugins/doc_fragments:/usr/share/ansible/plugins/doc_fragments" }} + +# (string) By default Ansible will issue a warning when a duplicate dict key is encountered in YAML. +# These warnings can be silenced by adjusting this setting to False. +;duplicate_dict_key=warn + +# (boolean) Whether or not to enable the task debugger, this previously was done as a strategy plugin. +# Now all strategy plugins can inherit this behavior. The debugger defaults to activating when +# a task is failed on unreachable. Use the debugger keyword for more flexibility. +;enable_task_debugger=False + +# (boolean) Toggle to allow missing handlers to become a warning instead of an error when notifying. +;error_on_missing_handler=True + +# (list) Which modules to run during a play's fact gathering stage, using the default of 'smart' will try to figure it out based on connection type. +# If adding your own modules but you still want to use the default Ansible facts, you will want to include 'setup' or corresponding network module to the list (if you add 'smart', Ansible will also figure it out). +# This does not affect explicit calls to the 'setup' module, but does always affect the 'gather_facts' action (implicit or explicit). +;facts_modules=smart + +# (boolean) Set this to "False" if you want to avoid host key checking by the underlying tools Ansible uses to connect to the host +;host_key_checking=True + +# (boolean) Facts are available inside the `ansible_facts` variable, this setting also pushes them as their own vars in the main namespace. +# Unlike inside the `ansible_facts` dictionary, these will have an `ansible_` prefix. +;inject_facts_as_vars=True + +# (string) Path to the Python interpreter to be used for module execution on remote targets, or an automatic discovery mode. Supported discovery modes are ``auto`` (the default), ``auto_silent``, ``auto_legacy``, and ``auto_legacy_silent``. All discovery modes employ a lookup table to use the included system Python (on distributions known to include one), falling back to a fixed ordered list of well-known Python interpreter locations if a platform-specific default is not available. The fallback behavior will issue a warning that the interpreter should be set explicitly (since interpreters installed later may change which one is used). This warning behavior can be disabled by setting ``auto_silent`` or ``auto_legacy_silent``. The value of ``auto_legacy`` provides all the same behavior, but for backwards-compatibility with older Ansible releases that always defaulted to ``/usr/bin/python``, will use that interpreter if present. +interpreter_python=/usr/bin/python3 + +# (boolean) If 'false', invalid attributes for a task will result in warnings instead of errors +;invalid_task_attribute_failed=True + +# (boolean) Toggle to control showing warnings related to running a Jinja version older than required for jinja2_native +;jinja2_native_warning=True + +# (boolean) By default Ansible will issue a warning when there are no hosts in the inventory. +# These warnings can be silenced by adjusting this setting to False. +;localhost_warning=True + +# (int) Maximum size of files to be considered for diff display +;max_diff_size=104448 + +# (list) List of extensions to ignore when looking for modules to load +# This is for rejecting script and binary module fallback extensions +;module_ignore_exts={{(REJECT_EXTS + ('.yaml', '.yml', '.ini'))}} + +# (list) TODO: write it +;network_group_modules=eos, nxos, ios, iosxr, junos, enos, ce, vyos, sros, dellos9, dellos10, dellos6, asa, aruba, aireos, bigip, ironware, onyx, netconf, exos, voss, slxos + +# (boolean) Previously Ansible would only clear some of the plugin loading caches when loading new roles, this led to some behaviours in which a plugin loaded in prevoius plays would be unexpectedly 'sticky'. This setting allows to return to that behaviour. +;old_plugin_cache_clear=False + +# (path) A number of non-playbook CLIs have a ``--playbook-dir`` argument; this sets the default value for it. +;playbook_dir= + +# (string) This sets which playbook dirs will be used as a root to process vars plugins, which includes finding host_vars/group_vars +;playbook_vars_root=top + +# (path) A path to configuration for filtering which plugins installed on the system are allowed to be used. +# See :ref:`plugin_filtering_config` for details of the filter file's format. +# The default is /etc/ansible/plugin_filters.yml +;plugin_filters_cfg= + +# (string) Attempts to set RLIMIT_NOFILE soft limit to the specified value when executing Python modules (can speed up subprocess usage on Python 2.x. See https://bugs.python.org/issue11284). The value will be limited by the existing hard limit. Default value of 0 does not attempt to adjust existing system-defined limits. +;python_module_rlimit_nofile=0 + +# (bool) This controls whether a failed Ansible playbook should create a .retry file. +;retry_files_enabled=False + +# (path) This sets the path in which Ansible will save .retry files when a playbook fails and retry files are enabled. +# This file will be overwritten after each run with the list of failed hosts from all plays. +;retry_files_save_path= + +# (str) This setting can be used to optimize vars_plugin usage depending on user's inventory size and play selection. +;run_vars_plugins=demand + +# (bool) This adds the custom stats set via the set_stats plugin to the default output +;show_custom_stats=False + +# (string) Action to take when a module parameter value is converted to a string (this does not affect variables). For string parameters, values such as '1.00', "['a', 'b',]", and 'yes', 'y', etc. will be converted by the YAML parser unless fully quoted. +# Valid options are 'error', 'warn', and 'ignore'. +# Since 2.8, this option defaults to 'warn' but will change to 'error' in 2.12. +;string_conversion_action=warn + +# (boolean) Allows disabling of warnings related to potential issues on the system running ansible itself (not on the managed hosts) +# These may include warnings about 3rd party packages or other conditions that should be resolved if possible. +;system_warnings=True + +# (boolean) This option defines whether the task debugger will be invoked on a failed task when ignore_errors=True is specified. +# True specifies that the debugger will honor ignore_errors, False will not honor ignore_errors. +;task_debugger_ignore_errors=True + +# (integer) Set the maximum time (in seconds) that a task can run for. +# If set to 0 (the default) there is no timeout. +;task_timeout=0 + +# (string) Make ansible transform invalid characters in group names supplied by inventory sources. +;force_valid_group_names=never + +# (boolean) Toggles the use of persistence for connections. +;use_persistent_connections=False + +# (bool) A toggle to disable validating a collection's 'metadata' entry for a module_defaults action group. Metadata containing unexpected fields or value types will produce a warning when this is True. +;validate_action_group_metadata=True + +# (list) Accept list for variable plugins that require it. +;vars_plugins_enabled=host_group_vars + +# (list) Allows to change the group variable precedence merge order. +;precedence=all_inventory, groups_inventory, all_plugins_inventory, all_plugins_play, groups_plugins_inventory, groups_plugins_play + +# (bool) Force 'verbose' option to use stderr instead of stdout +;verbose_to_stderr=False + +# (integer) For asynchronous tasks in Ansible (covered in Asynchronous Actions and Polling), this is how long, in seconds, to wait for the task spawned by Ansible to connect back to the named pipe used on Windows systems. The default is 5 seconds. This can be too low on slower systems, or systems under heavy load. +# This is not the total time an async command can run for, but is a separate timeout to wait for an async command to start. The task will only start to be timed against its async_timeout once it has connected to the pipe, so the overall maximum duration the task can take will be extended by the amount specified here. +;win_async_startup_timeout=5 + +# (list) Check all of these extensions when looking for 'variable' files which should be YAML or JSON or vaulted versions of these. +# This affects vars_files, include_vars, inventory and vars plugins among others. +;yaml_valid_extensions=.yml, .yaml, .json + + +[privilege_escalation] +# (boolean) Display an agnostic become prompt instead of displaying a prompt containing the command line supplied become method +;agnostic_become_prompt=True + +# (boolean) This setting controls if become is skipped when remote user and become user are the same. I.E root sudo to root. +# If executable, it will be run and the resulting stdout will be used as the password. +;become_allow_same_user=False + +# (boolean) Toggles the use of privilege escalation, allowing you to 'become' another user after login. +become=True + +# (boolean) Toggle to prompt for privilege escalation password. +;become_ask_pass=False + +# (string) executable to use for privilege escalation, otherwise Ansible will depend on PATH +;become_exe= + +# (string) Flags to pass to the privilege escalation executable. +;become_flags= + +# (string) Privilege escalation method to use when `become` is enabled. +become_method=sudo + +# (string) The user your login/remote user 'becomes' when using privilege escalation, most systems will use 'root' when no user is specified. +become_user=root + + +[persistent_connection] +# (path) Specify where to look for the ansible-connection script. This location will be checked before searching $PATH. +# If null, ansible will start with the same directory as the ansible script. +;ansible_connection_path= + +# (int) This controls the amount of time to wait for response from remote device before timing out persistent connection. +command_timeout=5 + +# (integer) This controls the retry timeout for persistent connection to connect to the local domain socket. +;connect_retry_timeout=15 + +# (integer) This controls how long the persistent connection will remain idle before it is destroyed. +;connect_timeout=30 + +# (path) Path to socket to be used by the connection persistence system. +;control_path_dir={{ ANSIBLE_HOME ~ "/pc" }} + + +[connection] +# (boolean) This is a global option, each connection plugin can override either by having more specific options or not supporting pipelining at all. +# Pipelining, if supported by the connection plugin, reduces the number of network operations required to execute a module on the remote server, by executing many Ansible modules without actual file transfer. +# It can result in a very significant performance improvement when enabled. +# However this conflicts with privilege escalation (become). For example, when using 'sudo:' operations you must first disable 'requiretty' in /etc/sudoers on all managed hosts, which is why it is disabled by default. +# This setting will be disabled if ``ANSIBLE_KEEP_REMOTE_FILES`` is enabled. +;pipelining=False + + +[colors] +# (string) Defines the color to use on 'Changed' task status +changed=yellow + +# (string) Defines the default color to use for ansible-console +console_prompt=white + +# (string) Defines the color to use when emitting debug messages +debug=dark gray + +# (string) Defines the color to use when emitting deprecation messages +;deprecate=purple + +# (string) Defines the color to use when showing added lines in diffs +;diff_add=green + +# (string) Defines the color to use when showing diffs +;diff_lines=cyan + +# (string) Defines the color to use when showing removed lines in diffs +;diff_remove=red + +# (string) Defines the color to use when emitting error messages +error=red + +# (string) Defines the color to use for highlighting +highlight=white + +# (string) Defines the color to use when showing 'OK' task status +ok=green + +# (string) Defines the color to use when showing 'Skipped' task status +;skip=cyan + +# (string) Defines the color to use on 'Unreachable' status +unreachable=bright red + +# (string) Defines the color to use when emitting verbose messages. i.e those that show with '-v's. +verbose=blue + +# (string) Defines the color to use when emitting warning messages +warn=bright purple + + +[selinux] +# (boolean) This setting causes libvirt to connect to lxc containers by passing --noseclabel to virsh. This is necessary when running on systems which do not have SELinux. +;libvirt_lxc_noseclabel=False + +# (list) Some filesystems do not support safe operations and/or return inconsistent errors, this setting makes Ansible 'tolerate' those in the list w/o causing fatal errors. +# Data corruption may occur and writes are not always verified when a filesystem is in the list. +;special_context_filesystems=fuse, nfs, vboxsf, ramfs, 9p, vfat + + +[diff] +# (bool) Configuration toggle to tell modules to show differences when in 'changed' status, equivalent to ``--diff``. +;always=False + +# (integer) How many lines of context to show when displaying the differences between files. +;context=3 + + +[galaxy] +# (path) The directory that stores cached responses from a Galaxy server. +# This is only used by the ``ansible-galaxy collection install`` and ``download`` commands. +# Cache files inside this dir will be ignored if they are world writable. +;cache_dir={{ ANSIBLE_HOME ~ "/galaxy_cache" }} + +# (path) Collection skeleton directory to use as a template for the ``init`` action in ``ansible-galaxy collection``, same as ``--collection-skeleton``. +;collection_skeleton= + +# (list) patterns of files to ignore inside a Galaxy collection skeleton directory +;collection_skeleton_ignore=^.git$, ^.*/.git_keep$ + +# (bool) Disable GPG signature verification during collection installation. +;disable_gpg_verify=False + +# (bool) Some steps in ``ansible-galaxy`` display a progress wheel which can cause issues on certain displays or when outputing the stdout to a file. +# This config option controls whether the display wheel is shown or not. +# The default is to show the display wheel if stdout has a tty. +;display_progress= + +# (path) Configure the keyring used for GPG signature verification during collection installation and verification. +;gpg_keyring= + +# (boolean) If set to yes, ansible-galaxy will not validate TLS certificates. This can be useful for testing against a server with a self-signed certificate. +;ignore_certs= + +# (list) A list of GPG status codes to ignore during GPG signature verification. See L(https://github.com/gpg/gnupg/blob/master/doc/DETAILS#general-status-codes) for status code descriptions. +# If fewer signatures successfully verify the collection than `GALAXY_REQUIRED_VALID_SIGNATURE_COUNT`, signature verification will fail even if all error codes are ignored. +;ignore_signature_status_codes= + +# (str) The number of signatures that must be successful during GPG signature verification while installing or verifying collections. +# This should be a positive integer or all to indicate all signatures must successfully validate the collection. +# Prepend + to the value to fail if no valid signatures are found for the collection. +;required_valid_signature_count=1 + +# (path) Role skeleton directory to use as a template for the ``init`` action in ``ansible-galaxy``/``ansible-galaxy role``, same as ``--role-skeleton``. +;role_skeleton= + +# (list) patterns of files to ignore inside a Galaxy role or collection skeleton directory +;role_skeleton_ignore=^.git$, ^.*/.git_keep$ + +# (string) URL to prepend when roles don't specify the full URI, assume they are referencing this server as the source. +;server=https://galaxy.ansible.com + +# (list) A list of Galaxy servers to use when installing a collection. +# The value corresponds to the config ini header ``[galaxy_server.{{item}}]`` which defines the server details. +# See :ref:`galaxy_server_config` for more details on how to define a Galaxy server. +# The order of servers in this list is used to as the order in which a collection is resolved. +# Setting this config option will ignore the :ref:`galaxy_server` config option. +;server_list= + +# (path) Local path to galaxy access token file +;token_path={{ ANSIBLE_HOME ~ "/galaxy_token" }} + + +[inventory] +# (string) This setting changes the behaviour of mismatched host patterns, it allows you to force a fatal error, a warning or just ignore it +;host_pattern_mismatch=warning + +# (boolean) If 'true', it is a fatal error when any given inventory source cannot be successfully parsed by any available inventory plugin; otherwise, this situation only attracts a warning. + +;any_unparsed_is_failed=False + +# (bool) Toggle to turn on inventory caching. +# This setting has been moved to the individual inventory plugins as a plugin option :ref:`inventory_plugins`. +# The existing configuration settings are still accepted with the inventory plugin adding additional options from inventory configuration. +# This message will be removed in 2.16. +;cache=False + +# (string) The plugin for caching inventory. +# This setting has been moved to the individual inventory plugins as a plugin option :ref:`inventory_plugins`. +# The existing configuration settings are still accepted with the inventory plugin adding additional options from inventory and fact cache configuration. +# This message will be removed in 2.16. +;cache_plugin= + +# (string) The inventory cache connection. +# This setting has been moved to the individual inventory plugins as a plugin option :ref:`inventory_plugins`. +# The existing configuration settings are still accepted with the inventory plugin adding additional options from inventory and fact cache configuration. +# This message will be removed in 2.16. +;cache_connection= + +# (string) The table prefix for the cache plugin. +# This setting has been moved to the individual inventory plugins as a plugin option :ref:`inventory_plugins`. +# The existing configuration settings are still accepted with the inventory plugin adding additional options from inventory and fact cache configuration. +# This message will be removed in 2.16. +;cache_prefix=ansible_inventory_ + +# (string) Expiration timeout for the inventory cache plugin data. +# This setting has been moved to the individual inventory plugins as a plugin option :ref:`inventory_plugins`. +# The existing configuration settings are still accepted with the inventory plugin adding additional options from inventory and fact cache configuration. +# This message will be removed in 2.16. +;cache_timeout=3600 + +# (list) List of enabled inventory plugins, it also determines the order in which they are used. +;enable_plugins=host_list, script, auto, yaml, ini, toml + +# (bool) Controls if ansible-inventory will accurately reflect Ansible's view into inventory or its optimized for exporting. +;export=False + +# (list) List of extensions to ignore when using a directory as an inventory source +;ignore_extensions={{(REJECT_EXTS + ('.orig', '.ini', '.cfg', '.retry'))}} + +# (list) List of patterns to ignore when using a directory as an inventory source +;ignore_patterns= + +# (bool) If 'true' it is a fatal error if every single potential inventory source fails to parse, otherwise this situation will only attract a warning. + +;unparsed_is_failed=False + +# (boolean) By default Ansible will issue a warning when no inventory was loaded and notes that it will use an implicit localhost-only inventory. +# These warnings can be silenced by adjusting this setting to False. +;inventory_unparsed_warning=True + + +[netconf_connection] +# (string) This variable is used to enable bastion/jump host with netconf connection. If set to True the bastion/jump host ssh settings should be present in ~/.ssh/config file, alternatively it can be set to custom ssh configuration file path to read the bastion/jump host settings. +;ssh_config= + + +[paramiko_connection] +# (boolean) TODO: write it +;host_key_auto_add=False + +# (boolean) TODO: write it +;look_for_keys=True + + +[jinja2] +# (list) This list of filters avoids 'type conversion' when templating variables +# Useful when you want to avoid conversion into lists or dictionaries for JSON strings, for example. +;dont_type_filters=string, to_json, to_nice_json, to_yaml, to_nice_yaml, ppretty, json + + +[tags] +# (list) default list of tags to run in your plays, Skip Tags has precedence. +;run= + +# (list) default list of tags to skip in your plays, has precedence over Run Tags +;skip= + diff --git a/ansible/inventory/inventory.ini b/ansible/inventory/inventory.ini new file mode 100644 index 0000000..8659d0e --- /dev/null +++ b/ansible/inventory/inventory.ini @@ -0,0 +1,5 @@ +[firewall] +nftables ansible_host='192.168.1.119' + +[Database] +Database ansible_host='192.168.1.119' \ No newline at end of file diff --git a/ansible/playbook/deploy_firewall.yml b/ansible/playbook/deploy_firewall.yml new file mode 100644 index 0000000..8fb3b01 --- /dev/null +++ b/ansible/playbook/deploy_firewall.yml @@ -0,0 +1,28 @@ +--- + +- name: DĂ©ploiement des rĂšgles nftables + hosts: firewall + become: yes + + tasks: + - name: Installation nftables + apt: + name: nftables + state: present + + - name: Copie de la configuration du module 'nftables.conf' + copy: + src: ../../modules/nftables.conf + dest: /etc/nftables.conf + owner: root + group: root + mode: '0644' + notify: RedĂ©marrer nftables + + handlers: + - name: RedĂ©marrer nftables + service: + name: nftables + state: restarted + + diff --git a/ansible/playbook/setup_db.yml b/ansible/playbook/setup_db.yml new file mode 100644 index 0000000..eb227af --- /dev/null +++ b/ansible/playbook/setup_db.yml @@ -0,0 +1,17 @@ +--- +- name: "DĂ©ploiement Automatique Database" + hosts: Database + become: yes + + tasks: + - name: Installer mariadb-server + apt: + name: mariadb-server + state: present + update-cache: yes + + - name: Installer mariadb-client + apt: + name: mariadb-client + state: present + \ No newline at end of file diff --git a/ansible/playbook/site.yml b/ansible/playbook/site.yml new file mode 100644 index 0000000..240f436 --- /dev/null +++ b/ansible/playbook/site.yml @@ -0,0 +1,8 @@ +--- + +- name: Lancement de la configuration Database + import_playbook: setup_db.yml + +- name: Lancement de la configuration nftables + import_playbook: deploy_firewall.yml + diff --git a/modules/nftables.conf b/modules/nftables.conf new file mode 100644 index 0000000..efc2a3f --- /dev/null +++ b/modules/nftables.conf @@ -0,0 +1,30 @@ +table inet filter { + chain input { + type filter hook input priority 0; policy drop; + + # 1. Autoriser le trafic interne (loopback) + iif "lo" accept + + # 2. Autoriser les connexions dĂ©jĂ  Ă©tablies (rĂ©ponses au trafic sortant) + ct state established,related accept + + # 3. Autoriser le SSH (Port 22) - À adapter si tu as changĂ© le port + tcp dport 22 accept + + # 4. Autoriser le Ping (optionnel mais utile pour le diagnostic) + icmp type echo-request accept + icmpv6 type echo-request accept + + # 5. Optionnel : Autoriser MariaDB (Port 3306) + # Uniquement si d'autres serveurs doivent se connecter Ă  la DB + # tcp dport 3306 accept + } + + chain forward { + type filter hook forward priority 0; policy drop; + } + + chain output { + type filter hook output priority 0; policy accept; + } +} \ No newline at end of file diff --git a/requirement/main.sh b/requirement/main.sh new file mode 100755 index 0000000..82adf2d --- /dev/null +++ b/requirement/main.sh @@ -0,0 +1,162 @@ +#!/bin/bash + +cat << 'EOF' + + _____ _ _ __ __ _ + | __ \ (_) | | | \/ | (_) + | | | | ___ _ __ _ ___| | __ | \ / | __ ___ ___ _ __ ___ ___ + | | | |/ _ \ '__| |/ __| |/ / | |\/| |/ _` \ \/ / | '_ ` _ \ / _ \ + | |__| | __/ | | | (__| < | | | | (_| |> <| | | | | | | __/ + |_____/ \___|_| |_|\___|_|\_\ |_| |_|\__,_/_/\_\_|_| |_| |_|\___| + + + + +EOF + + + + + +set -euo pipefail + +SEPARATOR="==============================================" + +print_step() { + echo "" + echo "$SEPARATOR" + echo " $1" + echo "$SEPARATOR" +} + +# VĂ©rification des droits sudo +if [ "$EUID" -ne 0 ]; then + echo " Ce script doit ĂȘtre exĂ©cutĂ© avec sudo" + echo " Utilisation : sudo ./main.sh" + exit 1 +fi + +print_step " Lancement du programme des requirements" +sleep 1 + +# ---------------------------- +# 1. Mise Ă  jour du systĂšme +# ---------------------------- +print_step " Mise Ă  jour du systĂšme (apt update & upgrade)" +print_step " Mise Ă  jour du systĂšme (apt update & upgrade)" +if ! apt update && apt upgrade -y; then + echo " Erreur lors de la mise Ă  jour du systĂšme" + exit 1 +fi +echo "SystĂšme mis Ă  jour" +sleep 1 + + +# ---------------------------- +# 2. Installation de Python +# ---------------------------- +print_step "VĂ©rification / Installation de Python3" +if ! apt install python3 python3-pip python3-venv -y; then + echo "Erreur lors de l'installation de Python3" + exit 1 +fi +PYTHON_VERSION=$(python3 --version 2>&1) +echo " $PYTHON_VERSION installĂ©" + +sleep 1 + + + +# ---------------------------- +# 3. Recherche des venvs existants +# ---------------------------- +print_step "Recherche des environnements virtuels (venv) existants..." + +SEARCH_DIRS=("$(pwd)") +VENV_LIST=() + +for dir in "${SEARCH_DIRS[@]}"; do + if [ -d "$dir" ]; then + while IFS= read -r -d '' activate_path; do + venv_dir=$(dirname "$(dirname "$activate_path")") + if [ -f "$venv_dir/bin/python" ]; then + VENV_LIST+=("$venv_dir") + fi + done < <(find "$dir" -name "activate" -path "*/bin/activate" 2>/dev/null -print0) + fi +done + +echo "" +if [ ${#VENV_LIST[@]} -eq 0 ]; then + echo " Aucun environnement virtuel trouvĂ© dans : $(pwd)" +else + echo "${#VENV_LIST[@]} environnement(s) virtuel(s) trouvĂ©(s) :" + for i in "${!VENV_LIST[@]}"; do + venv="${VENV_LIST[$i]}" + python_ver=$("$venv/bin/python" --version 2>&1) + echo "" + echo " [$((i+1))] Chemin : $venv" + echo " Python : $python_ver" + echo " ▶ Activer : source $venv/bin/activate" + done + SELECTED_VENV="${VENV_LIST[0]}" + echo "$SELECTED_VENV" > ./.venv_path + echo "" + echo "Venv sĂ©lectionnĂ© et enregistrĂ© : $SELECTED_VENV" +fi + +# ---------------------------- +# 4. CrĂ©er un nouveau venv ? +# ---------------------------- +print_step " CrĂ©er un nouvel environnement virtuel ?" +echo "Voulez-vous crĂ©er un nouveau venv ? (o/n)" +read -r CREATE_VENV + +if [[ "$CREATE_VENV" =~ ^[oO]$ ]]; then + VENV_PATH="$SEARCH_DIRS/venv" + if python3 -m venv $SEARCH_DIRS/python/venv; then + echo "" + echo "Venv créé avec succĂšs !" + echo " Chemin : $VENV_PATH" + echo " ▶ Activer : source $VENV_PATH/bin/activate" + + + echo "$VENV_PATH" > ./.venv_path + echo "Chemin enregistrĂ© dans .venv_path" + + + "$VENV_PATH/bin/pip" install --upgrade pip + + + if [ -f "./requirements.txt" ]; then + echo "Installation des dĂ©pendances depuis requirements.txt..." + "$VENV_PATH/bin/pip" install -r ./python/requirements.txt + echo " DĂ©pendances installĂ©es" + + else + echo " Aucun requirements.txt trouvĂ©, installation des dĂ©pendances ignorĂ©e" + + fi + else + echo " Erreur lors de la crĂ©ation du venv Ă  : $VENV_PATH" + exit 1 + + fi +else + echo " CrĂ©ation ignorĂ©e" + +fi + +# ---------------------------- +# Fin +# ---------------------------- +print_step " Configuration terminĂ©e" + +echo "" +if [ -f "./.venv_path" ]; then + echo "Venv configurĂ© : $(cat ./.venv_path)" + echo " Pour l'activer manuellement : source $(cat ./.venv_path)/bin/activate" +else + echo " Aucun venv enregistrĂ© — relancez le script et crĂ©ez un venv" +fi +echo ""