sl-may
      • 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
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners 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 New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy 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
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners 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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    [toc] ### Syntax-check and Linting in Ansible #### Syntax Check :::warning ansible-playbook <playbook-name> --syntax-check ::: #### Ansible Lint :::warning Ansible has a command line linter called ansible-lint. It does not come by default and can be installed very easily by using one of the following methods: ##### Using apt: ````yaml= sudo apt install ansible-lint ```` ##### Using pip: ````yaml= python3 -m pip install --user ansible-lint ```` ::: ##### How to use ansible-lint ````yaml= Get help: ansible-lint --help Check a playbook for lint errors: ansible-lint <playbook-name> Check all ansible-lint rules: ansible-lint -L ```` #### Listing the hosts affected by the playbook ````yaml= ansible-playbook <playbook-name> --list-hosts ```` #### Limiting playbook to run on specific host or hostgroups ````yaml= ansible-playbook <playbook-name> --limit mynode.mycompany.com ```` #### ask-pass and ask-become-pass ````yaml= --ask-pass --> ask password for ssh (in case passwordless authentication not setup) --ask-become-pass --> ask for sudo password, if needed ```` ### Working with Jinja2 templates #### installation Jinja2 ````yaml= sudo apt-get update -y sudo apt-get install -y python-jinja2 ```` #### Create a jinja template ````yaml= mkdir templates && cd templates ## vi motd.j2 Welcome to {{ ansible_hostname }}! This node is running on {{ ansible_distribution }} {{ ansible_distribution_version }} The architecture of this node is ..... This Linux node is running on ...... Kernel ```` #### Write a playbook to use the template ````yaml= ## vi motd.yaml --- ## Playbook to create motd file on worker nodes - hosts: nodes become: true tasks: - name: write motd file with host specific information template: src: motd.j2 dest: /etc/motd owner: root group: root mode: '0644' ```` #### This is how your directory should look like now: ``` labsuser@controller:~/templates$ tree . ├── motd.j2 └── motd.yaml ``` #### Run the playbook and validate the changes ````yaml= Run the playbook: ansible-playbook motd.yaml Validate the changes: run the following command on worker nodes: cat /etc/motd or ssh to the worker nodes and verify the output from motd file ```` ### Tags in Ansible ````yaml= --- ## Playbook to install and configure Apache - name: install and configure apache ## Play 1 hosts: nodes become: yes tasks: - name: install apache ## Apache installation apt: name: apache2 state: present - name: Upload index file. ## copy index.html file from controller to all web nodes copy: src: index.html dest: /var/www/html/index.html mode: 0755 notify: start the apache2 service tags: - installation - package - apache handlers: - name: start the apache2 service ## make sure the service is up and running service: name: apache2 state: restarted - name: create multiple db users ## Play 2 hosts: all become: yes tasks: - name: install elinks user: name: "{{item}}" state: present loop: - db1 - db2 - db3 tags: - db - users - name: install specified packages ## Play 3 hosts: all become: yes tasks: - name: install elinks apt: name: "{{item}}" state: present loop: - tree - git - elinks - telnet - screen - net-tools - nodejs tags: - package - installation ```` :mag: More information on Tagging in Ansible --> https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_tags.html ### Running part of a playbook (Typically for troubleshooting) ````yaml=1 List all tags in the specified playbook: ansible-playbook <playbookname> --list-tags Run only specified tags: ansible-playbook <playbookname> --tags <tag1,tag2> Run everything except specified tags: ansible-playbook <playbookname> --skip-tags <tag1,tag2> Run from a specific play/task: ansible-playbook:<playbookname> --start-at-task Step-by-step execution of the playbook: ansible-playbook <playbookname> --step ## This will cause ansible to stop on each task, and ask if it should execute that task. (y/n/c) ```` :mag: More information on ansible-playbook command --> https://docs.ansible.com/ansible/latest/cli/ansible-playbook.html ### Parallelism in Ansible #### ad-hoc commands ````yaml= Syntax: -f, --fork Example: ansible all -m shell -a "ls /tmp" -f 2 ```` #### Playbooks ````yaml= --- ## Using playbook to install elinks package - hosts: all become: yes serial: - 3 - 25% tasks: - name: install elinks apt: name: elinks update_cache: yes state: present ```` :mag: *More information --> https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_strategies.html* ### Ansible Vault Ansible Vault is used to secure and ecncrypt / decrypt files within Ansible. It can perform operations list below (but not limited to): #### With ansible Vault, you can: ````yaml - Encrypt an existing file/playbooks - Decryt a file - Edit and encrypted file - Generate or reset key ```` #### Ansible-vault CLI sub-commands ````yaml= {create,decrypt,edit,view,encrypt,encrypt_string,rekey} create Create new vault encrypted file decrypt Decrypt vault encrypted file edit Edit vault encrypted file view View vault encrypted file encrypt Encrypt YAML file encrypt_string Encrypt a string rekey Re-key a vault encrypted file ```` #### Ansible Vault Tasks ````yaml= Create an encrypted playbook: ansible-vault create vault-demo.yaml view the encrypted playbook: ansible-vault view vault-demo.yaml Edit the encrypted playbook: ansible-vault edit vault-demo.yaml decrypt the playbook: ansible-vault decrypt vault-demo.yaml encrypt the playbook again: ansible-vault encrypt vault-demo.yaml Run the playbook (and watch it faile as no password given): ansible-playbook vault-demo.yaml Run the playbook with the flag to ask for vault password: ansible-playbook vault-demo.yaml --ask-vault-pass Change the vault password for an existing file: ansible-vault rekey vault-demo.yaml ```` :mag: *More information --> https://docs.ansible.com/ansible/latest/vault_guide/vault.html* ### Metadata in Ansible (Ansible Local Facts) :::warning **Create a directory where all local facts would be kept:** ``` mkdir /etc/ansible/facts.d ``` :arrow_right: *Please note that **'/etc/ansible'** directory would not be present on the managed nodes, so you have to manually create the directory in order to put all the fact files inside facts.d directory.* **create your metadata files:** 1. Create a file called dc.fact ``` vi dc.fact ``` 2. Put the following content: ``` [location] datacenter=mumbai-dc country=india ``` 3. Create another file called cost.fact ``` vi cost.fact ``` 4. Put the following content: ``` [cost] costcenter=100005 department=marketing ``` **Once done, this is how your directory structure should look like:** ``` root@worker1:/etc/ansible# tree . ├── facts.d │ ├── cost.fact │ └── dc.fact ``` **Run the ansible command to get the local facts:** ``` ansible localhost -m setup -a "filter=ansible_local" ``` Expected output: ``` root@Controller:/etc/ansible/facts.d# ansible localhost -m setup -a "filter=ansible_local" localhost | SUCCESS => { "ansible_facts": { "ansible_local": { "cost": { "location": { "country": "india", "datacenter": "mumbai-dc" } }, "dc": { "cost": { "costcenter": "100005", "department": "marketing" } } }, "discovered_interpreter_python": "/usr/bin/python3" }, "changed": false } ``` ::: ### Error handling in Ansible ![](https://hackmd.io/_uploads/H15Be65qn.png) #### Ignore errors in ansible ```yaml= --- ## Playbook example for error handling - hosts: localhost tasks: - name: create-file file: path: /tmp/error.txt mode: '0755' ## state: touch ## ignore_errors: yes - name: ping localhost action: ping ``` #### Using block/rescue/always in Ansible playbook: ```yaml= --- ## Playbook example for error handling - hosts: localhost tasks: - name: create-file block: - file: path: /tmp/error.txt mode: '0755' ## state: touch rescue: - debug: msg="this part is on screen because main block failed" - name: ping localhost action: ping always: - debug: msg="This part of the playbook always runs" ``` ### References :::info - https://www.linuxtechi.com/configure-use-ansible-jinja2-templates/ - https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_tags.html - https://docs.ansible.com/ansible/latest/cli/ansible-playbook.html :::

    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