操屁眼的视频在线免费看,日本在线综合一区二区,久久在线观看免费视频,欧美日韩精品久久综

新聞資訊

    inux 用戶環境變量可以幫助你找到你需要的命令,無須了解系統如何配置的細節而完成大量工作。而這些設置來自哪里和如何被修改它們是另一個話題。

    -- Sandra Henry-stocker(作者)

    在 Linux 系統上的用戶賬戶配置以多種方法簡化了系統的使用。你可以運行命令,而不需要知道它們的位置。你可以重新使用先前運行的命令,而不用發愁系統是如何追蹤到它們的。你可以查看你的電子郵件,查看手冊頁,并容易地回到你的家目錄,而不用管你在文件系統中身在何方。并且,當需要的時候,你可以調整你的賬戶設置,以便其更符合你喜歡的方式。

    Linux 環境設置來自一系列的文件:一些是系統范圍(意味著它們影響所有用戶賬戶),一些是處于你的家目錄中的配置文件里。系統范圍的設置在你登錄時生效,而本地設置在其后生效,所以,你在你賬戶中作出的更改將覆蓋系統范圍設置。對于 bash 用戶,這些文件包含這些系統文件:

    /etc/environment
    /etc/bash.bashrc
    /etc/profile
    

    以及一些本地文件:

    ~/.bashrc
    ~/.profile # 如果有 ~/.bash_profile 或 ~/.bash_login 就不會讀此文件
    ~/.bash_profile
    ~/.bash_login
    

    你可以修改本地存在的四個文件的任何一個,因為它們處于你的家目錄,并且它們是屬于你的。

    查看你的 Linux 環境設置

    為查看你的環境設置,使用 env 命令。你的輸出將可能與這相似:

    $ env
    LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;
    01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:
    *.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:
    *.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:
    *.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;
    31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:
    *.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:
    *.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:
    *.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:
    *.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:
    *.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:
    *.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:
    *.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:
    *.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:
    *.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:
    *.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:
    *.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:
    *.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.spf=00;36:
    SSH_CONNECTION=192.168.0.21 34975 192.168.0.11 22
    LESSCLOSE=/usr/bin/lesspipe %s %s
    LANG=en_US.UTF-8
    OLDPWD=/home/shs
    XDG_SESSION_ID=2253
    USER=shs
    PWD=/home/shs
    HOME=/home/shs
    SSH_CLIENT=192.168.0.21 34975 22
    XDG_DATA_DIRS=/usr/local/share:/usr/share:/var/lib/snapd/desktop
    SSH_TTY=/dev/pts/0
    MAIL=/var/mail/shs
    TERM=xterm
    SHELL=/bin/bash
    SHLVL=1
    LOGNAME=shs
    DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
    XDG_RUNTIME_DIR=/run/user/1000
    PATH=/home/shs/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
    LESSOPEN=| /usr/bin/lesspipe %s
    _=/usr/bin/env
    

    雖然你可能會看到大量的輸出,上面顯示的第一大部分用于在命令行上使用顏色標識各種文件類型。當你看到類似 *.tar=01;31: 這樣的東西,這告訴你 tar 文件將以紅色顯示在文件列表中,然而 *.jpg=01;35: 告訴你 jpg 文件將以紫色顯現出來。這些顏色旨在使它易于從一個文件列表中分辨出某些文件。你可以在《 在 Linux 命令行中自定義你的顏色 》處學習更多關于這些顏色的定義,和如何自定義它們。

    當你更喜歡一種不加裝飾的顯示時,一種關閉顏色顯示的簡單方法是使用如下命令:

    $ ls -l --color=never
    

    這個命令可以簡單地轉換到一個別名:

    $ alias ll2='ls -l --color=never'
    

    你也可以使用 echo 命令來單獨地顯現某個設置。在這個命令中,我們顯示在歷史緩存區中將被記憶命令的數量:

    $ echo $HISTSIZE
    1000
    

    如果你已經移動到某個位置,你在文件系統中的最后位置會被記在這里:

    PWD=/home/shs
    OLDPWD=/tmp
    

    作出更改

    你可以使用一個像這樣的命令更改環境設置,但是,如果你希望保持這個設置,在你的 ~/.bashrc 文件中添加一行代碼,例如 HISTSIZE=1234。

    $ export HISTSIZE=1234
    

    “export” 一個變量的本意是什么

    導出一個環境變量可使設置用于你的 shell 和可能的子 shell。默認情況下,用戶定義的變量是本地的,并不被導出到新的進程,例如,子 shell 和腳本。export 命令使得環境變量可用在子進程中發揮功用。

    添加和移除變量

    你可以很容易地在命令行和子 shell 上創建新的變量,并使它們可用。然而,當你登出并再次回來時這些變量將消失,除非你也將它們添加到 ~/.bashrc 或一個類似的文件中。

    $ export MSG="Hello, World!"
    

    如果你需要,你可以使用 unset 命令來消除一個變量:

    $ unset MSG
    

    如果變量是局部定義的,你可以通過加載你的啟動文件來簡單地將其設置回來。例如:

    $ echo $MSG
    Hello, World!
    $ unset $MSG
    $ echo $MSG
    $ . ~/.bashrc
    $ echo $MSG
    Hello, World!
    

    小結

    用戶賬戶是用一組恰當的啟動文件設立的,創建了一個有用的用戶環境,而個人用戶和系統管理員都可以通過編輯他們的個人設置文件(對于用戶)或很多來自設置起源的文件(對于系統管理員)來更改默認設置。


    via: https://www.networkworld.com/article/3385516/how-to-manage-your-linux-environment.html

    作者: Sandra Henry-Stocker 選題: lujun9972 譯者: robsean 校對: wxy

    本文由 LCTT 原創編譯, Linux中國 榮譽推出

    點擊“了解更多”可訪問文內鏈接

    寫在前面

    • 今天和小伙伴分享使用lookup插件模板化外部數據
    • 博文內容比較簡單
    • 主要介紹的常用lookup插件和對應的Demo
    • 外部數據如何代替cat等通過lookup插件讀取
    • 理解不足小伙伴幫忙指正
    • 食用方式:了解Ansible基礎語法

    「運維箴言:重啟試試 」


    lookup插件

    lookup 插件是 Jinja2 模板化語言的 Ansible 擴展。這些插件使 Ansible 能夠使用外部來源的數據,如文件和Shell 環境。

    默認的Ansible安裝中有幾十個可用的插件。ansible-doc-t lookup -l,獲取可用查找插件的完整列表。

    [student@workstation data-filters]$ ansible-doc -t lookup -l
    aws_account_attribute Look up AWS account attributes
    aws_secret            Look up secrets stored in AWS Secrets Manager
    aws_service_ip_ranges Look up the IP ranges for services provided in AWS such as EC2 and S3
    aws_ssm               Get the value for a SSM parameter or all parameters under a path
    cartesian             returns the cartesian product of lists
    

    可以運行 ansible-doc -t lookup PLUGIN_NAME 命令。我們隨便看一個模塊

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible-doc -t lookup vars
    > VARS    (/usr/lib/python2.7/site-packages/ansible/plugins/lookup/vars.py)
    
            Retrieves the value of an Ansible variable.
    
      * This module is maintained by The Ansible Community
    OPTIONS (=is mandatory):=_terms
            The variable names to look up.
            ......
    

    嗯,獲取一個Ansible變量的值,順便研究下代碼怎么寫

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$cat /usr/lib/python2.7/site-packages/ansible/plugins/lookup/vars.py
    # (c) 2017 Ansible Project
    # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
    from __future__ import (absolute_import, division, print_function)
    __metaclass__=type
    
    ## 一些模塊的說明
    DOCUMENTATION="""
        lookup: vars
        author: Ansible Core
        version_added: "2.5"
        short_description: Lookup templated value of variables
        description:
          - Retrieves the value of an Ansible variable.
        options:
          _terms:
            description: The variable names to look up.
            required: True
          default:
            description:
                - What to return if a variable is undefined.
                - If no default is set, it will result in an error if any of the variables is undefined.
    """
    ## 模塊使用方法
    。。。。
    
    RETURN="""
    _value:
      description:
        - value of the variables requested.
    """
    
    from ansible.errors import AnsibleError, AnsibleUndefinedVariable
    from ansible.module_utils.six import string_types
    from ansible.plugins.lookup import LookupBase
    
    
    class LookupModule(LookupBase):
        ##只有一個方法,接收所有參數
        def run(self, terms, variables=None, **kwargs):
            # variables不為none的話
            if variables is not None:
                self._templar.available_variables=variables
            myvars=getattr(self._templar, '_available_variables', {})
    
            self.set_options(direct=kwargs)
            default=self.get_option('default')
    
            ret=[]
            for term in terms:
                if not isinstance(term, string_types):
                    raise AnsibleError('Invalid setting identifier, "%s" is not a string, its a %s' % (term, type(term)))
    
                try:
                    try:
                        value=myvars[term]
                    except KeyError:
                        try:
                            value=myvars['hostvars'][myvars['inventory_hostname']][term]
                        except KeyError:
                            raise AnsibleUndefinedVariable('No variable found with this name: %s' % term)
    
                    ret.append(self._templar.template(value, fail_on_undefined=True))
                except AnsibleUndefinedVariable:
                    if default is not None:
                        ret.append(default)
                    else:
                        raise
    
            return ret
    

    可以看到,和回調插件的編寫方式類似,繼承基類,重寫方法。主要用于根據變量名獲取當前劇本中的變量,變量名可以是經過運行的變量,我編寫一個Demo來測試下

    ---
    - name: vars Demo
      hosts: master
      tasks:
      - name: Show value of 'variablename'
        debug:
          msg: "{{ lookup('vars', 'variabl' + myvar)}}"
        vars:
          variablename: hello
          myvar: ename
    
      - name: Show default empty since i dont have 'variablnotename'
        debug:
          msg: "{{ lookup('vars', 'variabl' + myvar, default='變量不存在')}}"
        vars:
          variablename: hello
          myvar: notename
    
      - name: Produce an error since i dont have 'variablnotename'
        debug:
            msg: "{{ lookup('vars', 'variabl' + myvar)}}"
        ignore_errors: True
        vars:
            variablename: hello
            myvar: notename
    
      - name: find several related variables
        debug:
            msg: "{{ lookup('vars', 'ansible_play_hosts', 'ansible_play_batch', 'ansible_play_hosts_all') }}"
    
      - name: alternate way to find some 'prefixed vars' in loop
        debug:
          msg: "{{ lookup('vars', 'ansible_play_' + item) }}"
        loop:
          - hosts
          - batch
          - hosts_all
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible-playbook vars.yaml
    
    PLAY [vars Demo] ****************************************************************
    
    TASK [Gathering Facts] **********************************************************
    ok: [192.168.26.81]
    
    TASK [Show value of 'variablename'] *********************************************
    ok: [192.168.26.81]=> {
        "msg": "hello"
    }
    
    TASK [Show default empty since i dont have 'variablnotename'] *******************
    ok: [192.168.26.81]=> {
        "msg": "變量不存在"
    }
    
    TASK [Produce an error since i dont have 'variablnotename'] *********************
    fatal: [192.168.26.81]: FAILED!=> {"msg": "The task includes an option with an undefined variable. The error was: No variable found with this name: variablnotename\n\nThe error appears to be in '/root/ansible/vars.yaml': line 19, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: Produce an error since i dont have 'variablnotename'\n    ^ here\n"}
    ...ignoring
    
    TASK [find several related variables] *******************************************
    ok: [192.168.26.81]=> {
        "msg": [
            [
                "192.168.26.81"
            ],
            [
                "192.168.26.81"
            ],
            [
                "192.168.26.81"
            ]
        ]
    }
    
    TASK [alternate way to find some 'prefixed vars' in loop] ***********************
    ok: [192.168.26.81]=> (item=hosts)=> {
        "msg": [
            "192.168.26.81"
        ]
    }
    ok: [192.168.26.81]=> (item=batch)=> {
        "msg": [
            "192.168.26.81"
        ]
    }
    ok: [192.168.26.81]=> (item=hosts_all)=> {
        "msg": [
            "192.168.26.81"
        ]
    }
    
    PLAY RECAP **********************************************************************
    192.168.26.81              : ok=6    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=1
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$
    

    可以使用lookup和query來調用查找插件。使用方法與過濾器相似;指定函數的名稱,并在括號中添加要調用的查找插件的名稱以及該插件所需的所有參數。

    調用lookup插件

    可以使用兩個 Jinja2 模板函數lookup 或 query)中的一個來調用插件。

    這兩種方法都具有和過濾器非常相似的語法。指定函數的名稱,并在圓括號中指定要調用的lookup插件的名稱和插件需要的任何參數。

    通過lookup的file插件獲取指定文件的內容,編寫劇本

    - name: lookup Demo
      hosts: master
      vars:
        hosts: "{{ lookup('file', '/etc/hosts')}}"
      tasks:
        - debug:
            var: hosts
    

    模擬執行劇本

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible-playbook jinja2.yaml  -C
    PLAY [lookup Demo] **********************************************************************************
    TASK [Gathering Facts] ******************************************************************************ok: [192.168.26.81]
    TASK [debug] ****************************************************************************************ok: [192.168.26.81]=> {
        "hosts": "127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4\n::1         localhost localhost.localdomain localhost6 localhost6.localdomain6\n192.168.26.81 vms81.liruilongs.github.io vms81\n192.168.26.82 vms82.liruilongs.github.io vms82\n192.168.26.83 vms83.liruilongs.github.io vms83"
    }
    
    PLAY RECAP ******************************************************************************************192.168.26.81              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    

    使用逗號分隔,可以在 file 插件中包含多個文件名:

    - name: lookup Demo
      hosts: master
      vars:
        issue: "{{ lookup( 'file','/etc/hosts','/etc/issue')}}"
      tasks:
        - debug:
            var: issue
    

    Ansible 2.5和更高版本中,可以使用query函數,而不是 lookup來調用查找插件。兩者之間的區別在于,query 始終會返回?個更容易解析和使用的列表,而不是返回逗號分隔的值

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible-playbook query.yaml
    PLAY [query] **********************************************************************************
    TASK [Gathering Facts] ************************************************************************
    ok: [192.168.26.81]
    TASK [debug] **********************************************************************************
    ok: [192.168.26.81]=> {
        "param": [
            "\\S\nKernel \\r on an \\m\n\n192.168.26.81",
            "127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4\n::1         localhost localhost.localdomain localhost6 localhost6.localdomain6\n192.168.26.81 vms81.liruilongs.github.io vms81\n192.168.26.82 vms82.liruilongs.github.io vms82\n192.168.26.83 vms83.liruilongs.github.io vms83"
        ]
    }
    PLAY RECAP ************************************************************************************
    192.168.26.81              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$
    
    - name: query
      hosts: master
      vars:
        param: "{{ query('file','/etc/issue','/etc/hosts')}}"
      tasks:
        - debug:
            var: param
    

    那這里有一個問題,lookup獲取文件的內容適控制節點,還是被控節點,實際上是控制節點

    讀取文件的內容

    file 插件允許 Ansible 將本地文件的內容加載到變量。來看一個傳遞SSH密鑰的Demo

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ssh root@vms82.liruilongs.github.io useradd fred
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ssh root@vms82.liruilongs.github.io useradd naoko
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ssh-keygen  -N '' -f fred.key
    Generating public/private rsa key pair.
    Your identification has been saved in fred.key.
    Your public key has been saved in fred.key.pub.
    The key fingerprint is:
    SHA256:AABygrfjKr2zllYikm0DCbxHaEvt/5fLwN6jY/OaXN8 root@vms81.liruilongs.github.io
    The key's randomart image is:
    +---[RSA 2048]----+
    |*.=..            |
    |+B.o .           |
    |+o=.  .          |
    |oooo   .         |
    |=...   S        |
    |+ * ...          |
    |.==.o ..      |
    |o *   o=*+. .    |
    |.oo+  .*B=o. E   |
    +----[SHA256]-----+
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ssh-keygen  -N '' -f naoko.key
    Generating public/private rsa key pair.
    Your identification has been saved in naoko.key.
    Your public key has been saved in naoko.key.pub.
    The key fingerprint is:
    SHA256:UDtUESSooboZtIungph4VJoLa3mwVqekwp6wdoExwaI root@vms81.liruilongs.github.io
    The key's randomart image is:
    +---[RSA 2048]----+
    |.      .+o=o     |
    |.o  . .o o       |
    |o .. o. o        |
    |E+. o  . .       |
    |..=+    S        |
    |++++ .           |
    |BOO.+            |
    |&@=+             |
    |X*o              |
    +----[SHA256]-----+
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ls | grep key
    fred.key
    fred.key.pub
    naoko.key
    naoko.key.pub
    
    - name: Add authorized keys
      hosts: 192.168.26.82
      vars:
        users:
          - fred
          - naoko
      tasks:
        - name: Add keys
          authorized_key:
             user: "{{ item }}"
             key: "{{ lookup('file',item + '.key.pub')}}"
          loop: "{{ users }}"
    
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible-playbook file_vars.yaml
    
    PLAY [Add authorized keys] **************************************************************************
    
    TASK [Gathering Facts] ******************************************************************************
    ok: [192.168.26.82]
    
    TASK [Add keys] *************************************************************************************
    changed: [192.168.26.82]=> (item=fred)
    changed: [192.168.26.82]=> (item=naoko)
    
    PLAY RECAP ******************************************************************************************
    192.168.26.82              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ssh -i fred.key  fred@vms82.liruilongs.github.io id
    uid=1001(fred) gid=1001(fred) 組=1001(fred)
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ssh -i naoko.key  naoko@vms82.liruilongs.github.io id
    uid=1002(naoko) gid=1002(naoko) 組=1002(naoko)
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$
    

    對于公鑰的獲取,也可以直接通過變量拼接,不使用運算符。

     key: "{{ lookup('file', '{{ item }}.key.pub')}}"
    

    如果文件是JSON 或 YAML格式,可以使用from_yaml 或 from_json過濾器將其解析為正確結構化的數據:

    我們讀取一個pod資源文件試試

    ---
    - name: yaml to vars
      hosts: 192.168.26.82
      tasks:
        - name: show yaml
          debug:
             var: " lookup('file', 'static-pod.yaml') | from_yaml"
    
    ---
    apiVersion: v1
    kind: Pod
    metadata:
      creationTimestamp: null
      labels:
        run: pod-static
      name: pod-static
      namespeace: default
    spec:
      containers:
      - image: nginx
        imagePullPolicy: IfNotPresent
        name: pod-demo
        resources: {}
      dnsPolicy: ClusterFirst
      restartPolicy: Always
    status: {}
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible-playbook file_yaml.yaml
    
    PLAY [yaml to vars] *********************************************************************************
    
    TASK [Gathering Facts] ******************************************************************************
    ok: [192.168.26.82]
    
    TASK [show yaml] ************************************************************************************
    ok: [192.168.26.82]=> {
        " lookup('file', 'static-pod.yaml') | from_yaml": {
            "apiVersion": "v1",
            "kind": "Pod",
            "metadata": {
                "creationTimestamp": null,
                "labels": {
                    "run": "pod-static"
                },
                "name": "pod-static",
                "namespeace": "default"
            },
            "spec": {
                "containers": [
                    {
                        "image": "nginx",
                        "imagePullPolicy": "IfNotPresent",
                        "name": "pod-demo",
                        "resources": {}
                    }
                ],
                "dnsPolicy": "ClusterFirst",
                "restartPolicy": "Always"
            },
            "status": {}
        }
    }
    
    PLAY RECAP ******************************************************************************************
    192.168.26.82              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    

    json也是一樣的,我們來看一下,這是傳遞一個docker加速器設置

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$cat daemon.json
    {
      "registry-mirrors": ["https://2tefyfv7.mirror.aliyuncs.com"]
    }
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$cat file_json.yaml
    ---
    - name: json to vars
      hosts: 192.168.26.82
      tasks:
       - debug:
            var: lookup('file', 'daemon.json') | from_json
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible-playbook file_json.yaml
    
    PLAY [json to vars] *********************************************************************************
    
    TASK [Gathering Facts] ******************************************************************************
    ok: [192.168.26.82]
    
    TASK [debug] ****************************************************************************************
    ok: [192.168.26.82]=> {
        "lookup('file', 'daemon.json') | from_json": {
            "registry-mirrors": [
                "https://2tefyfv7.mirror.aliyuncs.com"
            ]
        }
    }
    
    PLAY RECAP ******************************************************************************************
    192.168.26.82              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    

    ini插件查詢控制節點ini格式文件特定參數值。

    ---
    - name:  lookup or query Play
      hosts:  192.168.26.82
      gather_facts: false
      tasks:
       - debug:
          msg: >
           first name in file /etc/foo. ini section liruilong is {{ lookup('ini', 'first_name  lest_name section=liruilong file=/etc/foo.ini') }}
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible-playbook file_ini.yaml
    
    PLAY [lookup or query Play] ********************************************************************************************
    
    TASK [debug] ***********************************************************************************************************
    ok: [192.168.26.82]=> {
        "msg": "first name in file /etc/foo. ini section liruilong is []\n"
    }
    
    PLAY RECAP *************************************************************************************************************
    192.168.26.82              : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    

    使用模板應用數據

    file插件一樣,template 插件也會返回文件的內容,不同之處在于,template 插件預期文件內容為 Jinja2 模 板,并在應用之前評估該模板。

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$echo "hello {{ name }}" > hello.j2
    
    ---
    - name: template Demo
      hosts: 192.168.26.82
      vars:
        name: liruilong
      tasks:
        - name: mes deml
          debug:
            var: lookup('template', 'hello.j2')
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible-playbook template_demo.yaml
    [WARNING]: Found variable using reserved name: name
    
    PLAY [template Demo] ********************************************************************************
    
    TASK [Gathering Facts] ******************************************************************************
    ok: [192.168.26.82]
    
    TASK [mes deml] *************************************************************************************
    ok: [192.168.26.82]=> {
        "lookup('template', 'hello.j2')": "hello liruilong\n"
    }
    
    PLAY RECAP ******************************************************************************************
    192.168.26.82              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    

    讀取控制節點上的環境變量

    env插件查詢控制節點環境變量。當控制主機是容器化的應用程序,并且將環境變量注入configmap和secret到主機中時,此功能很有用。

    ---
    - name: lookup or query play
      hosts: 192.168.26.82
      tasks:
        - name: show env LANG
          debug:
            var: lookup('env', 'LANG')
        - name: show env
          debug:
            var: ansible_env
    
    
    PLAY [lookup or query play] ********************************************************************************************
    
    TASK [Gathering Facts] *************************************************************************************************
    ok: [192.168.26.82]
    
    TASK [show env LANG] ***************************************************************************************************
    ok: [192.168.26.82]=> {
        "lookup('env', 'LANG')": "zh_CN.UTF-8"
    }
    
    TASK [show env] ********************************************************************************************************
    ok: [192.168.26.82]=> {
        "ansible_env": {
            "HOME": "/root",
            "LANG": "zh_CN.UTF-8",
            "LESSOPEN": "||/usr/bin/lesspipe.sh %s",
            "LOGNAME": "root",
            "LS_COLORS": "rs=0:di=38;5;27:ln=38;5;51:mh=44;38;5;15:pi=40;38;5;11:so=38;5;13:do=38;5;5:bd=48;5;232;38;5;11:cd=48;5;232;38;5;3:or=48;5;232;38;5;9:mi=05;48;5;232;38;5;15:su=48;5;196;38;5;15:sg=48;5;11;38;5;16:ca=48;5;196;38;5;226:tw=48;5;10;38;5;16:ow=48;5;10;38;5;21:st=48;5;21;38;5;15:ex=38;5;34:*.tar=38;5;9:*.tgz=38;5;9:*.arc=38;5;9:*.arj=38;5;9:*.taz=38;5;9:*.lha=38;5;9:*.lz4=38;5;9:*.lzh=38;5;9:*.lzma=38;5;9:*.tlz=38;5;9:*.txz=38;5;9:*.tzo=38;5;9:*.t7z=38;5;9:*.zip=38;5;9:*.z=38;5;9:*.Z=38;5;9:*.dz=38;5;9:*.gz=38;5;9:*.lrz=38;5;9:*.lz=38;5;9:*.lzo=38;5;9:*.xz=38;5;9:*.bz2=38;5;9:*.bz=38;5;9:*.tbz=38;5;9:*.tbz2=38;5;9:*.tz=38;5;9:*.deb=38;5;9:*.rpm=38;5;9:*.jar=38;5;9:*.war=38;5;9:*.ear=38;5;9:*.sar=38;5;9:*.rar=38;5;9:*.alz=38;5;9:*.ace=38;5;9:*.zoo=38;5;9:*.cpio=38;5;9:*.7z=38;5;9:*.rz=38;5;9:*.cab=38;5;9:*.jpg=38;5;13:*.jpeg=38;5;13:*.gif=38;5;13:*.bmp=38;5;13:*.pbm=38;5;13:*.pgm=38;5;13:*.ppm=38;5;13:*.tga=38;5;13:*.xbm=38;5;13:*.xpm=38;5;13:*.tif=38;5;13:*.tiff=38;5;13:*.png=38;5;13:*.svg=38;5;13:*.svgz=38;5;13:*.mng=38;5;13:*.pcx=38;5;13:*.mov=38;5;13:*.mpg=38;5;13:*.mpeg=38;5;13:*.m2v=38;5;13:*.mkv=38;5;13:*.webm=38;5;13:*.ogm=38;5;13:*.mp4=38;5;13:*.m4v=38;5;13:*.mp4v=38;5;13:*.vob=38;5;13:*.qt=38;5;13:*.nuv=38;5;13:*.wmv=38;5;13:*.asf=38;5;13:*.rm=38;5;13:*.rmvb=38;5;13:*.flc=38;5;13:*.avi=38;5;13:*.fli=38;5;13:*.flv=38;5;13:*.gl=38;5;13:*.dl=38;5;13:*.xcf=38;5;13:*.xwd=38;5;13:*.yuv=38;5;13:*.cgm=38;5;13:*.emf=38;5;13:*.axv=38;5;13:*.anx=38;5;13:*.ogv=38;5;13:*.ogx=38;5;13:*.aac=38;5;45:*.au=38;5;45:*.flac=38;5;45:*.mid=38;5;45:*.midi=38;5;45:*.mka=38;5;45:*.mp3=38;5;45:*.mpc=38;5;45:*.ogg=38;5;45:*.ra=38;5;45:*.wav=38;5;45:*.axa=38;5;45:*.oga=38;5;45:*.spx=38;5;45:*.xspf=38;5;45:",
            "MAIL": "/var/mail/root",
            "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin",
            "PWD": "/root",
            "SHELL": "/bin/bash",
            "SHLVL": "2",
            "SSH_CLIENT": "192.168.26.81 43056 22",
            "SSH_CONNECTION": "192.168.26.81 43056 192.168.26.82 22",
            "SSH_TTY": "/dev/pts/0",
            "TERM": "xterm-256color",
            "USER": "root",
            "XDG_RUNTIME_DIR": "/run/user/0",
            "XDG_SESSION_ID": "2",
            "_": "/usr/bin/python"
        }
    }
    
    PLAY RECAP *************************************************************************************************************
    192.168.26.82              : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    

    讀取控制節點執行命令輸出

    pipe lines插件都在Ansible控制節點上運行命令,并返回輸出。pipe 插件返回命令生成的原始輸出,lines 插件將該命令的輸出拆分為行。

    ---
    - name: pipe & lines demo
      hosts: 192.168.26.82
      tasks:
        - name: pipe demo
          debug:
            var: lookup('pipe' , 'pwd','uname -a','ls -l k8s-volume-create/')
        - name: lines demo
          debug:
            var: lookup('lines', 'pwd','uname -a','ls -l k8s-volume-create/')
    
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible-playbook pipe_demo.yaml
    
    PLAY [pipe & lines demo] ****************************************************************************
    
    TASK [Gathering Facts] ******************************************************************************
    ok: [192.168.26.82]
    
    TASK [pipe demo] ************************************************************************************
    ok: [192.168.26.82]=> {
        "lookup('pipe' , 'pwd','uname -a','ls -l k8s-volume-create/')": "/root/ansible,Linux vms81.liruilongs.github.io 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux,總用量 40\ndrwxr-xr-x 2 root root 135 12月  1 19:54 nfsdy\n-rw-r--r-- 1 root root 442 12月  1 23:04 pod_storageclass.yaml\n-rw-r--r-- 1 root root 438 11月 27 17:14 PodVolumeHostPath.yaml\n-rw-r--r-- 1 root root 478 11月 28 11:10 podvolumenfs.yaml\n-rw-r--r-- 1 root root 695 11月 27 16:15 pod_volume_r.yaml\n-rw-r--r-- 1 root root 206 11月 28 17:17 pod_volumes-pvc.yaml\n-rw-r--r-- 1 root root 442 11 月 28 17:43 pod_volumespvc.yaml\n-rw-r--r-- 1 root root 615 11月 27 15:51 pod_volumes.yaml\n-rw-r--r-- 1 root root 646 11月 27 15:28 pod_volume.yaml\n-rw-r--r-- 1 root root 330 11月 28 17:18 pod_volunms-pv.yaml\n-rw-r--r-- 1 root root 199 12月  1 20:15 pvc_nfs.yaml"
    }
    
    TASK [lines demo] ***********************************************************************************
    ok: [192.168.26.82]=> {
        "lookup('lines', 'pwd','uname -a','ls -l k8s-volume-create/')": "/root/ansible,Linux vms81.liruilongs.github.io 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux,總用量 40,drwxr-xr-x 2 root root 135 12月  1 19:54 nfsdy,-rw-r--r-- 1 root root 442 12月  1 23:04 pod_storageclass.yaml,-rw-r--r-- 1 root root 438 11月 27 17:14 PodVolumeHostPath.yaml,-rw-r--r-- 1 root root 478 11月 28 11:10 podvolumenfs.yaml,-rw-r--r-- 1 root root 695 11月 27 16:15 pod_volume_r.yaml,-rw-r--r-- 1 root root 206 11月 28 17:17 pod_volumes-pvc.yaml,-rw-r--r-- 1 root root 442 11月 28 17:43 pod_volumespvc.yaml,-rw-r--r-- 1 root root 615 11月 27 15:51 pod_volumes.yaml,-rw-r--r-- 1 root root 646 11月 27 15:28 pod_volume.yaml,-rw-r--r-- 1 root root 330 11月 28 17:18 pod_volunms-pv.yaml,-rw-r--r-- 1 root root 199 12月  1 20:15 pvc_nfs.yaml"
    }
    
    PLAY RECAP ******************************************************************************************
    192.168.26.82              : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    

    看一個簡單的

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible master -m debug -a "msg={{ query('lines', 'ls /etc/host*')}}"
    192.168.26.81 | SUCCESS=> {
        "msg": [
            "/etc/host.conf",
            "/etc/hostname",
            "/etc/hosts",
            "/etc/hosts.allow",
            "/etc/hosts.deny"
        ]
    }
    

    lookup使用fileglob插件,返回逗號分隔的文件名清單。

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible master -m debug -a "msg={{ lookup('fileglob', '/etc/hosts*') }}"
    192.168.26.81 | SUCCESS=> {
        "msg": "/etc/hosts,/etc/hosts.allow,/etc/hosts.deny"
    }
    

    query使用fileglob插件,強制返回文件列表值。

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible master -m debug -a "msg={{ query('fileglob', '/etc/hosts*') }}"
    192.168.26.81 | SUCCESS=> {
        "msg": [
            "/etc/hosts",
            "/etc/hosts.allow",
            "/etc/hosts.deny"
        ]
    }
    

    從 URL 獲取內容

    url 插件從 URL 獲取內容:

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible master -m debug -a "msg={{ query('url', 'https://liruilongs.github.io/') }}"
    192.168.26.81 | SUCCESS=> {
        "msg": [
            "<!doctype html>",
            "<html lang=\"zh\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\"><meta><title>山河已無恙</title><link rel=\"manifest\" href=\"/manifest.json\"><meta name=\"application-name\" content=\"山河已無恙\"><meta name=\"msapplication-TileImage\" content=\"https://cdn.jsdelivr.net/gh/removeif/removeif-demo@latest/img/favicon.png\"><meta name=\"apple-mobile-web-app-capable\" content=\"yes\"><meta name=\"apple-mobile-web-app-title\" content=\"山河已無恙\"><meta name=\"apple-mobile-web-app-status-bar-style\" content=\"default\"><meta property=\"og:type\" content=\"blog\"><meta property=\"og:title\" content=\"山河已無恙\"><meta property=\"og:url\" ....
    

    同時具有許多選項用于控制身份驗證、web代理或將結果拆分為行等。

    從 Kubernetes API 獲取信息

    k8s 插件通過 openshift Python 模塊提供對 Kubernetes API 的完全訪問權限。必須使用 kind 選項來提供對象類型:

    - name: k8s demo
      hosts: 192.168.26.81
      tasks:
        - name: debug demo k8s
          debug:
            var: lookup('k8s',kind='pod',namespect='kube-system',resource_name='kube-proxy')
    

    注意:k8s 插件是一個 lookup 插件,主要用途是從 Kubernetes 集群提取信息,而不是對其進行更新。使用 k8s模塊來管理 Kubernetes 集群。

    - name: Fetch all deployments 
      set_fact: 
        deployments: "{{ lookup(k8s',kind='Deployment)}"
    - name: Fetch all deployments in a namespace 
      set_fact: 
        deployments: "{{ lookup(k8s',kind='Deployment',namespace='testing)}}"
    - name: Fetch a specific deployment by name 
      set_fact: 
        deployments: {{ lookup(k8s',kind='Deployment',namespace='testing, resource_name='elastic)}}
    - name: Fetch with label selector 
      set_fact: 
        service: "{{ lookup('k8s',kind='Service',label_ selector='app=galaxy') }}"
    

    這個Demo有問題,之后需要在看下

    查詢插件etcd,redis,mongodb還可以從數據庫中獲取信息。

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible-doc -t lookup etcd
    
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible master  -m debug -a "msg={{ lookup('etcd', 'foo')}} "
    192.168.26.81 | SUCCESS=> {
        "msg": ""
    }
    
    - name: a value from a locally running etcd
      debug: 
        msg: "{{ lookup('etcd', 'foo/bar')}"
    - name: "values from multiple folders on a locally running etcd"
      debug: 
        msg: "{{ lookup('etcd', 'foo','bar','baz')}}"
    - name: "since Ansible 2.5 you can set server options inline"
      debug: 
        msg: "{{ lookup('etcd','foo', version='v2', url='http://192.168.0.27') }}"
    

    password插件生成密碼

    password插件可用于創建用戶密碼,并保存在文件中。、

    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ansible 192.168.26.82 -m user -a "name=liruilong password={{ lookup('password','password-liruilong chars=digits lengt
    h=6 encrypt=sha512_crypt') }}"
    192.168.26.82 | CHANGED=> {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        },
        "changed": true,
        "comment": "",
        "create_home": true,
        "group": 1003,
        "home": "/home/liruilong",
        "name": "liruilong",
        "password": "NOT_LOGGING_PASSWORD",
        "shell": "/bin/bash",
        "state": "present",
        "system": false,
        "uid": 1003
    }
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$cat password-liruilong
    747437 salt=Uy3I0UCN
    ┌──[root@vms81.liruilongs.github.io]-[~/ansible]
    └─$ssh liruilong@192.168.26.82
    liruilong@192.168.26.82's password:
    [liruilong@vms82 ~]$
    

    處理liikup錯誤

    大多數 Ansible 插件可在失敗時中止 Ansible Playbook,但是,lookup 功能將執行委托給其它插件,這些插件可能不需要在失敗時中止 Ansible Playbook。

    - name: error demo
      hosts: 192.168.26.81
      tasks:
        - name: debug demo error
          debug:
            var: lookup('file', '/etc/passwd',error='warn') | default("Default file conten")
    

    lookup 插件接受 error 參數:

    • error 選項的默認值為 strict,如果基礎腳本失敗,lookup 插件會導致嚴重錯誤。
    • error 選項可以設置為 warn,則 lookup 插件在基礎腳本失敗時記錄警告并返回空字符串(或空列表)
    • error 選項可以設置為 ignore,則 lookup 插件會以靜默方式忽略錯誤,并返回空字符串(或空列表)

    實戰

    本地生成密碼遠程批量創建用戶

    讀取文件創建用戶

    $ cat users.txt
    jonfoo
    janebar
    philbaz
    $
    

    編寫劇本

    $ cat site.yml
    - name: Populate users from file
      hosts: all
      gather_facts: no
      tasks:
        - name: Create remote user
          vars:
            password: "{{ lookup('password', 'credentials/' + item + ' length=9') }}"
          user:
            name: "{{ item }}"
            password: "{{ password | password_hash('sha512') }}"
            update_password: on_create
            state: present
          loop: "{{ query('lines','cat users.txt') }}"
    $
    
    $ ansible-playbook  site.yml
    
    PLAY [Populate users from file] ******************************************************************************
    
    TASK [Create remote user] ************************************************************************************
    changed: [serverf.lab.example.com]=> (item=jonfoo)
    changed: [serverf.lab.example.com]=> (item=janebar)
    changed: [serverf.lab.example.com]=> (item=philbaz)
    
    PLAY RECAP ***************************************************************************************************
    serverf.lab.example.com    : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    
    
    $ ls credentials/* | xargs cat
    4qj2fAR6_
    FrQRx7XR4
    DgJoh1e7:
    

    博文參考

    《Red Hat Ansible Engine 2.8 DO447》

網站首頁   |    關于我們   |    公司新聞   |    產品方案   |    用戶案例   |    售后服務   |    合作伙伴   |    人才招聘   |   

友情鏈接: 餐飲加盟

地址:北京市海淀區    電話:010-     郵箱:@126.com

備案號:冀ICP備2024067069號-3 北京科技有限公司版權所有