Hu Josh
    • 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
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- type: title: 明新科大2022年ansible-8 # 簡報的名稱 tags: presentation # 簡報的標籤 slideOptions: # 簡報相關的設定 theme: sky # 顏色主題 transition: 'fade' # 換頁動畫 --- ## 課程八:Ansible 進階用法 ### 2022年下學期,明新科技大學資管系 ### 講師:胡嘉璽 --- ## 課程重點 * Ansible Facts * Ansible Template * Ansible Role * Ansible專案 --- ## 課程重點 * <font color="#00F">Ansible Facts</font> * Ansible Template * Ansible Role * Ansible專案 ---- ### Ansible Facts是什麼 * 每次執行`playbook`時,系統會自動執行`setup`這個模組 ![](https://hackmd.io/_uploads/HJ0pqFp_i.png) ---- ### `setup`模組的用處 * 收集系統變數 * 包括網路、硬體、作業系統所有資料都在裏面 ---- ### 利用`ad hoc`指令查看系統變數 ```shell= ansible all -m setup > server1.info ``` 查看`server1.info` ```shell= vi server1.info ``` ---- ### 利用`filer`來過濾出系統變數 ``` ansible server1 -m setup -a "filter=ansible_distribution*" ``` ![](https://hackmd.io/_uploads/BJB0hY6dj.png) ---- ### 查看套件管理器 ``` ansible server1 -m setup -a "filter=ansible_pkg_mgr" ``` ![](https://hackmd.io/_uploads/r1GHTYTdj.png) ---- ### 安裝docker時讀取系統變數 ```yaml= --- - name: Install docker hosts: server1 become: true vars_files: - vars.yaml tasks: - name: Test Connection ping: - name: Install required packages apt: name: "{{ item }}" state: latest update_cache: true loop: "{{ requried_packages }}" - name: Add docker's official GPG key apt_key: url: https://download.docker.com/linux/ubuntu/gpg state: present - name: Add docker repository apt_repository: repo: deb https://download.docker.com/linux/ubuntu "{{ ansible_distribution_release }}" stable state: present ``` ---- ### 不需指定ubuntu版本代號 ![](https://hackmd.io/_uploads/Bkockcaui.png) --- ## 課程重點 * Ansible Facts * <font color="#00F">Ansible Template</font> * Ansible Role * Ansible專案 ---- ### template的用處 * 當在遠端要有一個設定檔時,指定其中的變數 * 事先定義變數和模板 * 動態產生遠端的 Shell Scripts、設定檔 * 使用jinja2格式,是一種python的模板檔案 * 使用`j2`作為副檔名 * 必須從主機端複製到被控端 ---- ### 在遠端`git clone` ```yaml= --- - name: clone git repo hosts: server1 tasks: - name: clone dotenv ansible.builtin.git: repo: https://github.com/joshhu/dotenvs.git dest: /home/ansible/dotenvs ``` ---- ### `.zshrc.j2`的部分內容 ```jinj2= (must)ansible:dotenvs/ (main✓) $ cat .zshrc.j2 [16:35:39] #uto Path to your oh-my-zsh installation. export ZSH=$HOME/.oh-my-zsh # Set name of the theme to load. # Look in ~/.oh-my-zsh/themes/ # Optionally, if you set this to "random", it'll load a random theme each # time that oh-my-zsh is loaded. ZSH_THEME="{{ zsh_theme }}" # Uncomment the following line to use case-sensitive completion. CASE_SENSITIVE="true" ``` ---- ### 設定`zsh`的主題 ```yaml= --- - name: clone git repo hosts: server1 vars: zsh_theme: "myclean" tasks: - name: clone dotenv to node ansible.builtin.git: repo: https://github.com/joshhu/dotenvs.git dest: /home/ansible/dotenvs - name: copy .zshrc to home directory ansible.builtin.template: src: /home/ansible/dotenvs/.zshrc.j2 dest: /home/ansible/.zshrc ``` ---- ### 執行後的結果 ``` ansible-playbook git2.yaml ``` ```.zshrc= ansible@server:~$ cat .zshrc.aa #uto Path to your oh-my-zsh installation. export ZSH=$HOME/.oh-my-zsh # Set name of the theme to load. # Look in ~/.oh-my-zsh/themes/ # Optionally, if you set this to "random", it'll load a random theme each # time that oh-my-zsh is loaded. ZSH_THEME="joshhu" ``` --- ## 課程重點 * Ansible Facts * Ansible Template * <font color="#00F">Ansible Role</font> * Ansible專案 ---- ### 什麼是Roles * 全名是 Playbooks Roles,是 Playbooks 的延伸使用 * 把重複的 Tasks 獨立出來 * 無法分享給其它專案使用 * 把寫好的程式封裝成套件 (Packages) 並重用及分享 * 用 Roles 來完成 ---- ### 什麼是Roles * Tasks:執行的工作 * Variables:執行時的變數 * Templates:複製時常用模板 * Metadata:一些共用的中繼資料 * Handles:和Ansible互動的callback ---- ### 如何建立一個Role ```shell= ansible-galaxy init test_role ``` ![](https://hackmd.io/_uploads/H18d6padi.png) ---- ### Role的結構目錄 ![](https://hackmd.io/_uploads/r1-app6_o.png) ---- ### 包括內部的檔案 ![](https://hackmd.io/_uploads/SJb10aaus.png) ---- ### 檔案說明 * defaults – 資料的預設值,但通常會被其它role的值取代 * files – 靜態不會更動的檔案 * handlers – 由tasks或roles所觸發的機制 * meta – 各種中繼資料,如作者,相依套件 * tasks – 就是playbook中的task * templates – jinja2格式的模板檔案 * tests – 測試role功能的 * vars – 這個role使用的變數,優先序高 ---- ### Role的使用 ```yaml= - hosts: all roles: - role: "/custom_path/to/the/role" ``` ---- ### 建立一個Webserver的Role ```shell= (must)ansible:ansible_git/ $ ansible-galaxy init webserver [19:54:26] - Role webserver was created successfully (must)ansible:ansible_git/ $ tree [19:54:39] . ├── ansible.cfg ├── git1.yaml ├── git2.yaml ├── templates └── webserver ├── defaults │   └── main.yml ├── files ├── handlers │   └── main.yml ├── meta │   └── main.yml ├── README.md ├── tasks │   └── main.yml ├── templates ├── tests │   ├── inventory │   └── test.yml └── vars └── main.yml 10 directories, 11 files ``` --- ## 課程重點 * Ansible Facts * Ansible Template * Ansible Role * <font color="#00F">Ansible專案</font> ---- ### 建立專案目錄及設定 ```shell= cd ~ mkdir project01 cd project01 cp ../ansible.cfg . cp ../inventory . mkdir roles cd roles ``` ---- ### 建立需要的Roles ```shell= ansible-galaxy init apt ansible-galaxy init zsh ansible_galaxy init omz ``` ---- ### 建立apt的role ```shell= cd roles cd tasks vi main.yml ``` ---- ### apt的task * `~/project01/roles/apt/tasks/main.yml` ```yaml= --- # tasks file for apt - name: apt update and upgrade apt: update_cache: true upgrade: full ``` ---- ### 撰寫專案`yaml` * `~/project01/main.yaml` ```yaml= --- - hosts: server1 roles: - { role: apt } ``` ---- ### 測試專案 ```shell= cd ~/project01 ansible-playbook main.yaml -C ``` ![](https://hackmd.io/_uploads/BkvisJRus.png) ---- ### 撰寫`zsh`的task * `~/project01/roles/zsh/tasks/main.yaml` ```yaml= --- - name: install zsh and dependencies package: name: "{{ zsh_dependencies }}" state: present become: true ``` ---- ### 撰寫`zsh`的task * `~/project01/roles/zsh/vars/main.yaml` ```yaml= --- # dependencies for zsh zsh_dependencies: - git - zsh - autojump ``` ---- ### 幹嘛自己寫role? * 網路上充滿了別人寫好,適用於各種場景的roles * 考慮的十分完整 * 參考其說明檔,將自己的改變加入即可 * 重新設定playbook的變數 * 會被安裝在`~/.ansible/roles`中,隨時可取用 ---- ### 安裝`oh-my-zsh`的role ```shell= (must)ansible:~/ $ ansible-galaxy install gantsign.oh-my-zsh Starting galaxy role install process - changing role gantsign.oh-my-zsh from 2.6.0 to unspecified - downloading role 'oh-my-zsh', owned by gantsign - downloading role from https://github.com/gantsign/ansible-role-oh-my-zsh/archive/2.6.0.tar.gz - extracting gantsign.oh-my-zsh to /home/ansible/.ansible/roles/gantsign.oh-my-zsh - gantsign.oh-my-zsh (2.6.0) was installed successfully ``` ---- ### 查看其網頁說明檔 ![](https://hackmd.io/_uploads/HJWZieAus.png) ---- ### 修改原來的playbook * `~/project01/main.yaml` ```yaml= --- - hosts: server1 roles: - { role: apt } - { role: zsh } - role: gantsign.oh-my-zsh users: - username: ansible ``` ---- ### 將`oh-my-zsh`的主題及設定檔修改 * 建立新的角色 ```shell= cd ~/project01/roles ansible-galaxy init omz ``` ---- ### 下載之前定義好的設定檔 ```shell= cd ~ git clone https://github.com/joshhu/dotenvs.git cp ~/dotenvs/.zshrc ~/project01/roles/omz/files cp ~/dotenvs/.myclean.zsh-theme ~/project01/roles/omz/files ``` ---- ### 撰寫新role的工作 * `~/project01/roles/omz/tasks/main.yml` ```yaml --- - name: update configuration files ansible.builtin.copy: src: myclean.zsh-theme dest: /home/ansible/.oh-my-zsh/custom/themes/myclean.zsh-theme - name: update .zshrc ansible.builtin.copy: src: .zshrc dest: /home/ansible/.zshrc - name: clone omz plugins ansible.builtin.git: repo: https://github.com/zsh-users/zsh-completions dest: /home/ansible/.oh-my-zsh/custom/plugins/zsh-completions - name: clone synteax highlight ansible.builtin.git: repo: https://github.com/zsh-users/zsh-syntax-highlighting.git dest: /home/ansible/.oh-my-zsh/custom/plugins/zsh-syntax-highlighting ``` ---- ### 修改專案的`main.yaml` ```yaml= --- - hosts: server1 roles: - { role: apt } - { role: zsh } - role: gantsign.oh-my-zsh users: - username: ansible - { role: omz } ```

    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