Hyperion
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: Fiche Aide Ansible author: Rémi Maubanc tags: CGI --- Fiche Aide Ansible === ## Ansible Playbook ### Configuration des hotes #### Ajout des clés SSH sur les clients Génération d'une clé SSH : ```bash ssh-keygen -t rsa -b 4096 -f .ssh/ansible_master ``` Voir le [tutoriel](https://wiki-prog.infoprepa.epita.fr/index.php/Practical_GIT.html) Ajout de la clé sur un client : ```bash ssh-copy-id -i .ssh/ansible_master root@192.168.1.1 ssh-copy-id -i .ssh/ansible_master hyperion@192.168.1.2 ``` Commande de tests ``` ssh root@192.168.1.1 ^D ssh hyperion@192.168.1.2 ^D ``` Si l'injection a fonctionné, on n'a pas besoin de taper de mot de passe pour se connecter Malgré que le compte soit dans le groupe sudo, il nécessite toujours de taper un mot de passe pour Les commandes nécessitant une élévation de privilège. Pour la retirer, il faut : `sudo visudo` ```git - %sudo ALL=(ALL:ALL) ALL + %sudo ALL=(ALL:ALL) NOPASSWD: ALL ``` #### Inventaire des clients Fichier par défaut du système : */etc/ansible/hosts* ```yaml [mes_servers] # Pas d'espace entre le texte et les crochets 192.168.1.1 ansible_user=root # Pour préciser à Ansible l'utilisateur à utiliser 192.168.1.2 ``` Fichier d'inventaire par projet : [ A compléter ] ### Liste des commandes ansible basiques #### Réalisation d'un ping Réaliser un ping sur tous les clients ```bash ansible all -m ping ``` | Option | Arguments | Description | |--------|-----------|---------------------------------------------------| | -m | ping | Charge le module en argument | | None | all | Selectionne toutes les IP du fichier d'inventaire | #### Récupération de la configuration ```bash ansible 192.168.1.1 -m setup -a "filter=*python*" ``` | Option | Arguments | Description | |--------|---------------------|----------------------------------------------| | None | 192.168.1.1 | IP du client à utiliser | | -m | setup | Charge le module `shell` | | -a | "filter=\*python\*" | Filtre les résultats en fonction de leur clé | #### Elevation de privilège ```bash ansible 192.168.1.1 -m shell -a "fdisk -l" -b -K ``` | Option | Arguments | Description | |--------|-------------|-----------------------------------------| | None | 192.168.1.1 | IP du client à utiliser | | -m | shell | Charge le module `shell` | | -b | None | Elevation de privilège sudo | | -K | None | Demande le mot de passe sudo dans stdin | **Note :** Eviter les modules *shell* et *raw* dans les playbooks car ils ne sont pas idempotents #### Envoyer un fichier ```bash # Création d'un fichier pour le test echo "Hello World!" > test.txt ansible all -m copy -a "src=test.txt dest=/home/hyperion/ansible owner=hyperion mode=0644" ``` | Option | Arguments | Description | |--------|--------------------|----------------------------------------------------------| | None | all | Utilise toutes les IP présentes dans l'inventaire | | -m | copy | Charge le module `copy` pour la copie de fichier | | -a | "src=test.txt ..." | Précise les paramètres de commande pour le module | #### Recevoir un fichier ```bash ansible all -m fetch -a "src=/etc/passwd dest=/tmp flat=yes" ls /tmp # Une copie du fichier passwd doit se trouver dans le /tmp du master ``` | Option | Arguments | Description | |--------|--------------------|----------------------------------------------------------| | None | all | Utilise toutes les IP présentes dans l'inventaire | | -m | fetch | Charge le module `fetch` pour télécharger des fichiers | | -a | "src=test.txt ..." | Précise les paramètres de commande pour le module | ### Installation packages Ouvrir le port HTTP pour nginx : [article](https://www.thegeekdiary.com/how-to-open-a-ports-in-centos-rhel-7/) + ajouter nginx dans le fichier */etc/services* aux lignes commencant par http: ```bash - http 80/tcp www www-http # WorldWideWeb HTTP - http 80/udp www www-http # HyperText Transfert Protocol + http 80/tcp www www-http nginx # WorldWideWeb HTTP + http 80/udp www www-http nginx # HyperText Transfert Protocol ``` :::danger => Problème rencontré pour le Lab4 de la formation Ansible ::: Installation de nginx dans deux clients (Debian et Centos 7) Dans un fichier playbook *nginx.yml* ```yaml --- - name: Nginx server installed hosts: demoservers become: yes tasks: - name: Add epel-release repo yum: name: epel-release state: present when: ansible_facts['os_family'] == "RedHat" - name: latest Nginx version installed Centos yum: name: nginx state: present when: ansible_facts['os_family'] == "RedHat" - name: latest Nginx version installed Debian apt: name: nginx state: latest when: ansible_facts['os_family'] == "Debian" - name: Nginx enable and running Centos service: name: nginx enabled: true state: started when: ansible_facts['os_family'] == "RedHat" - name: Add nginx index template copy: src: index.html dest: /var/www/html/ when: ansible_facts['os_family'] == "Debian" - name: Nginx enable and running Debian systemd: name: nginx enabled: true state: started when: ansible_facts['os_family'] == "Debian" ``` OS_Family vs Distribution : [Lien Article](https://techviewleo.com/list-of-ansible-os-family-distributions-facts/) ### Gestion des variables Les variables peuvent être définies de deux manières: - Directement dans le fichier ```yaml vars: user: admin group: wheel ``` - Dans un fichier séparé ```yaml # Fichier dédié --- user: admin group: wheel ``` ```yaml # Dans le fichier principal vars_files: - vars/users.yml ``` Arborescence du projet : ``` |- webserver.yml |- group_vars |- demoservers # Un groupe d'hotes défini dans l'inventaire |- host_vars |- 192.168.1.1 # Un hote existant dans l'inventaire |- html |- dev_index.html |- prod_index.html ``` *webserver.yml* ```yaml --- - name: Copy index.html hosts: demoservers become: yes tasks: - name: copy right index.html copy: src: "html/{{ stage }}_index.html" dest: /var/www/html/index.html ``` *group_vars/demoservers* ```yaml --- stage: dev ``` *host_vars/192.168.1.1* ```yaml --- stage: prod ``` ### Valeur de retour [Documentation](https://docs.ansible.com/ansible/latest/reference_appendices/common_return_values.html) Dans le playbook : ```yaml --- - name: Installs a package and prints the result hosts: dbservers become: True tasks: - name: Install the package yum: name: git state: present update_cache: yes register: install_result # Récupération du stdout - debug: var=install_result.result ``` :::info `install_result` est un dictionnaire et peut être déréférencé. ::: ### Valeur dans le playbook ```yaml --- - name: Create users hosts: all become: yes vars: user: admin group: wheel homedir: /dev/null shell: /bin/false tasks: - user: name: "{{ user }}" # Avec ou sans espace entre la variable et les accolades group: "{{ group }}" home: "{{ homedir }}" shell: "{{ shell }}" ``` ### Utilisation des facts ```yaml --- - name: Output facts within a playbook hosts: webservers tasks: - name: Prints Ansible facts debug: msg: The default IPv4 address of {{ ansible_fqdn }} is {{ ansible_enp0s3.ipv4.address }} ``` ```bash ok: [192.168.1.1] => { "msg": "The default IPv4 address of debian is 192.168.1.1" } ok: [192.168.1.2] => { "msg": "The default IPv4 address of localhost.localdomain is 192.168.1.Z" } ``` ### Les boucles ```yaml --- - name: Loop demo hosts: 192.168.1.92 vars: check_services: - nginx - sshd tasks: - name: Check if service is started service: name: "{{ item }}" state: started loop: "{{ check_services }}" # Iteration sur chaque élement ``` ### Conditions multiples ```yaml --- - name: MySQL server installation hosts: all become: yes tasks: - name: Install latest MySQL server when host RAM greater than 1 GB with YUM yum: name: mysql-server state: latest when: ansible_facts['os_family'] == "RedHat" and ansible_memtotal_mb > 1024 - name: Install latest MySQL server when host RAM greater than 1 GB with APT apt: name: mysql-server state: latest when: ansible_facts['os_family'] == "Debian" and ansible_memtotal_mb > 1024 ``` ### Handlers/Trigger ```yaml --- - name: Manage Nginx hosts: 192.168.1.57 become: yes tasks: - name: Copy Nginx configuration file copy: src: conf/default.conf dest: /etc/nginx/sites-enabled/ notify: - restart_nginx # Si l'état est "changed", le handler sera appelé handlers: - name: restart_nginx service: name: nginx state: restarted ``` ### Les templates *test_server.yml* ```yaml --- - hosts: demoservers gather_facts: yes become: yes tasks: - name: Install index.html template: src: html/index.html.j2 dest: /var/www/html/index.html mode: 0644 ``` *html/index.html.j2* ```html <html> <h1>Hostname: {{ ansible_fqdn | default('undefined') }}</h1> <center> <ul> <li>System : {{ ansible_os_family | default ('linux') }}</li> <li>Type : {{ stage | upper }}</li> <li>Stage : {{ stage | replace("prod", "Production") | replace("dev", "Development" }}</li> </ul> </center> </html> ``` [Documentation Jinja2](https://jinja.palletsprojects.com/en/2.10.x/templates/) ## Ansible Galaxy ### Création d'un role ```bash ansible-galaxy init nginx ``` Cette commande génère une arborescence de dossier de fichier à la manière de `django startapp nginx` avec les structures essentielles à la déclaration d'un rôle ```bash ├── nginx │ ├── README.md │ ├── defaults │ │ └── main.yml │ ├── files │ ├── handlers │ │ └── main.yml │ ├── meta │ │ └── main.yml │ ├── tasks │ │ └── main.yml │ ├── templates │ ├── tests │ │ ├── inventory │ │ └── test.yml │ └── vars | └── main.yml ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully