ansible変数登録の多様な方式

20680 ワード

ansibleを使ったことがある人はみんな知っています.変数を登録して使います.よくある場面です.今日はよくある状況をまとめて、ansible変数の定義、引用及びフォーマットに関する内容を知る.
目次
  • .Registerを使用して変数を登録する
  • 1.1コマンドを実行し、その結果を変数
  • に登録する.
  • 1.2リストが巡回した結果、変数
  • として登録されます.
  • .set_を使用する.fact登録変数
  • 2.1 set_を使用するfact登録普通変数
  • 2.2 set_を使用する.factはlist変数に循環的に要素を追加する
  • .
    1.registerを使って変数を登録する
    playbookが運行する時、いつも途中でいくつかデータを収集しなければならなくて、後でそれを使います.registerを使って変数を登録するのは最も簡単で、最も一般的な方法です.
    1.1コマンドを実行し、その結果を変数に登録する
    私たちが最もよく使うのは、shellコマンドを実行し、その結果を変数として登録します.例えば、
     tasks:
        - name: define a var1
          shell: "whoami"
          register: whoami
    
        - debug:
            msg: "whoami: {{ whoami }}"
        
        - debug:
            msg: "whoami.stdout: {{whoami.stdout}}"
    
    ここで注意したいのですが、ansibleの実行結果は辞書の種類のデータを返します.多くの関心のないフィールドが見られます.例えば、stdoutやstdoutなどの辞書のkeyを指定してもいいです.LINEでは、あなたの関心のあるデータしか見られません.
    戻りの結果を見てください.
    TASK [define a var1] ************************************************************************************************************************************************************************
    changed: [vagrant1]
    
    TASK [debug] ********************************************************************************************************************************************************************************
    ok: [vagrant1] => {
        "msg": "whoami: {'stderr_lines': [], u'changed': True, u'end': u'2020-04-19 15:18:18.278098', 'failed': False, u'stdout': u'vagrant', u'cmd': u'whoami', u'rc': 0, u'start': u'2020-04-19 15:18:18.274052', u'stderr': u'', u'delta': u'0:00:00.004046', 'stdout_lines': [u'vagrant']}"
    }
    
    TASK [debug] ********************************************************************************************************************************************************************************
    ok: [vagrant1] => {
        "msg": "whoami.stdout: vagrant"
    }
    
    1.2リストが巡回した結果、変数として登録されます.
    このようなシーンは、一般的にリストの要素が一つ一つ演算に参加し、演算後の結果を変数に保存します.例を見てください.
    ---
    
    - hosts: "{{ hosts_group }}"
      remote_user: vagrant
      vars:
        userss: []
    
      tasks:
        - name: define users in a loop
          shell: "grep {{ item }} /etc/passwd|cat"
          register: users
          with_items:
            - vagrant
            - root
            - nginx
        
        - name: show users
          debug:
            msg: "{{ users }}"
    
        - name: show users.results
          debug:
            msg: "{{ users.results }}"
    
        - name: define userss by set_fact
          set_fact: 
            userss: "{{userss +item.stdout_lines}}"
          with_list: "{{ users.results }}"
    
        - name: print userss
          debug:
            msg: "{{ userss }}"
        
        - name: print userss one by one
          debug:
            msg: "{{ item }}"
          with_list: "{{ userss}}"
    
        - name: print part of userss one by one
          debug:
            msg: "{{ item.split(':')[6] }}"
          with_list: "{{ userss}}"
    
    この例は、キーワードが照会システムのユーザ及びshell情報であることによって、ansibleは辞書に戻り、クエリの結果は辞書名がresultsであるkeyに対応するvalueに記憶され、このvalue自体はlistである.何人のユーザーが調べられるか分かりませんので、結果リストを巡回して別の変数に保存します.私たちはセットを使いますfactは、サイクルが空list変数にデータを追加する効果を実現しました.最後に、行ごとにデータを取得し、分割して、7番目のフィールドを取得しました.
    戻りの結果を見てください.
    TASK [define users in a loop] ***************************************************************************************************************************************************************
    changed: [vagrant1] => (item=vagrant)
    changed: [vagrant1] => (item=root)
    changed: [vagrant1] => (item=nginx)
    
    TASK [show users] ***************************************************************************************************************************************************************************
    ok: [vagrant1] => {
        "msg": {
            "changed": true, 
            "msg": "All items completed", 
            "results": [
                {
                    "_ansible_ignore_errors": null, 
                    "_ansible_item_label": "vagrant", 
                    "_ansible_item_result": true, 
                    "_ansible_no_log": false, 
                    "_ansible_parsed": true, 
                    "changed": true, 
                    "cmd": "grep vagrant /etc/passwd|cat", 
                    "delta": "0:00:00.004695", 
                    "end": "2020-04-19 15:18:19.129083", 
                    "failed": false, 
                    "invocation": {
                        "module_args": {
                            "_raw_params": "grep vagrant /etc/passwd|cat", 
                            "_uses_shell": true, 
                            "argv": null, 
                            "chdir": null, 
                            "creates": null, 
                            "executable": null, 
                            "removes": null, 
                            "stdin": null, 
                            "warn": true
                        }
                    }, 
                    "item": "vagrant", 
                    "rc": 0, 
                    "start": "2020-04-19 15:18:19.124388", 
                    "stderr": "", 
                    "stderr_lines": [], 
                    "stdout": "vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash", 
                    "stdout_lines": [
                        "vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash"
                    ]
                }, 
                {
                    "_ansible_ignore_errors": null, 
                    "_ansible_item_label": "root", 
                    "_ansible_item_result": true, 
                    "_ansible_no_log": false, 
                    "_ansible_parsed": true, 
                    "changed": true, 
                    "cmd": "grep root /etc/passwd|cat", 
                    "delta": "0:00:00.004695", 
                    "end": "2020-04-19 15:18:19.421598", 
                    "failed": false, 
                    "invocation": {
                        "module_args": {
                            "_raw_params": "grep root /etc/passwd|cat", 
                            "_uses_shell": true, 
                            "argv": null, 
                            "chdir": null, 
                            "creates": null, 
                            "executable": null, 
                            "removes": null, 
                            "stdin": null, 
                            "warn": true
                        }
                    }, 
                    "item": "root", 
                    "rc": 0, 
                    "start": "2020-04-19 15:18:19.416903", 
                    "stderr": "", 
                    "stderr_lines": [], 
                    "stdout": "root:x:0:0:root:/root:/bin/bash
    operator:x:11:0:operator:/root:/sbin/nologin", "stdout_lines": [ "root:x:0:0:root:/root:/bin/bash", "operator:x:11:0:operator:/root:/sbin/nologin" ] }, { "_ansible_ignore_errors": null, "_ansible_item_label": "nginx", "_ansible_item_result": true, "_ansible_no_log": false, "_ansible_parsed": true, "changed": true, "cmd": "grep nginx /etc/passwd|cat", "delta": "0:00:00.004500", "end": "2020-04-19 15:18:19.714496", "failed": false, "invocation": { "module_args": { "_raw_params": "grep nginx /etc/passwd|cat", "_uses_shell": true, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "warn": true } }, "item": "nginx", "rc": 0, "start": "2020-04-19 15:18:19.709996", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": [] } ] } } TASK [show users.results] ******************************************************************************************************************************************************************* ok: [vagrant1] => { "msg": [ { "_ansible_ignore_errors": null, "_ansible_item_label": "vagrant", "_ansible_item_result": true, "_ansible_no_log": false, "_ansible_parsed": true, "changed": true, "cmd": "grep vagrant /etc/passwd|cat", "delta": "0:00:00.004695", "end": "2020-04-19 15:18:19.129083", "failed": false, "invocation": { "module_args": { "_raw_params": "grep vagrant /etc/passwd|cat", "_uses_shell": true, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "warn": true } }, "item": "vagrant", "rc": 0, "start": "2020-04-19 15:18:19.124388", "stderr": "", "stderr_lines": [], "stdout": "vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash", "stdout_lines": [ "vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash" ] }, { "_ansible_ignore_errors": null, "_ansible_item_label": "root", "_ansible_item_result": true, "_ansible_no_log": false, "_ansible_parsed": true, "changed": true, "cmd": "grep root /etc/passwd|cat", "delta": "0:00:00.004695", "end": "2020-04-19 15:18:19.421598", "failed": false, "invocation": { "module_args": { "_raw_params": "grep root /etc/passwd|cat", "_uses_shell": true, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "warn": true } }, "item": "root", "rc": 0, "start": "2020-04-19 15:18:19.416903", "stderr": "", "stderr_lines": [], "stdout": "root:x:0:0:root:/root:/bin/bash
    operator:x:11:0:operator:/root:/sbin/nologin", "stdout_lines": [ "root:x:0:0:root:/root:/bin/bash", "operator:x:11:0:operator:/root:/sbin/nologin" ] }, { "_ansible_ignore_errors": null, "_ansible_item_label": "nginx", "_ansible_item_result": true, "_ansible_no_log": false, "_ansible_parsed": true, "changed": true, "cmd": "grep nginx /etc/passwd|cat", "delta": "0:00:00.004500", "end": "2020-04-19 15:18:19.714496", "failed": false, "invocation": { "module_args": { "_raw_params": "grep nginx /etc/passwd|cat", "_uses_shell": true, "argv": null, "chdir": null, "creates": null, "executable": null, "removes": null, "stdin": null, "warn": true } }, "item": "nginx", "rc": 0, "start": "2020-04-19 15:18:19.709996", "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": [] } ] } TASK [define userss by set_fact] ************************************************************************************************************************************************************ ok: [vagrant1] => (item={'_ansible_parsed': True, 'stderr_lines': [], '_ansible_item_result': True, u'end': u'2020-04-19 15:18:19.129083', '_ansible_no_log': False, u'stdout': u'vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash', u'cmd': u'grep vagrant /etc/passwd|cat', u'rc': 0, 'item': u'vagrant', u'delta': u'0:00:00.004695', '_ansible_item_label': u'vagrant', u'stderr': u'', u'changed': True, u'invocation': {u'module_args': {u'warn': True, u'executable': None, u'_uses_shell': True, u'_raw_params': u'grep vagrant /etc/passwd|cat', u'removes': None, u'argv': None, u'creates': None, u'chdir': None, u'stdin': None}}, 'stdout_lines': [u'vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash'], u'start': u'2020-04-19 15:18:19.124388', '_ansible_ignore_errors': None, 'failed': False}) ok: [vagrant1] => (item={'_ansible_parsed': True, 'stderr_lines': [], '_ansible_item_result': True, u'end': u'2020-04-19 15:18:19.421598', '_ansible_no_log': False, u'stdout': u'root:x:0:0:root:/root:/bin/bash
    operator:x:11:0:operator:/root:/sbin/nologin', u'cmd': u'grep root /etc/passwd|cat', u'rc': 0, 'item': u'root', u'delta': u'0:00:00.004695', '_ansible_item_label': u'root', u'stderr': u'', u'changed': True, u'invocation': {u'module_args': {u'warn': True, u'executable': None, u'_uses_shell': True, u'_raw_params': u'grep root /etc/passwd|cat', u'removes': None, u'argv': None, u'creates': None, u'chdir': None, u'stdin': None}}, 'stdout_lines': [u'root:x:0:0:root:/root:/bin/bash', u'operator:x:11:0:operator:/root:/sbin/nologin'], u'start': u'2020-04-19 15:18:19.416903', '_ansible_ignore_errors': None, 'failed': False}) ok: [vagrant1] => (item={'_ansible_parsed': True, 'stderr_lines': [], '_ansible_item_result': True, u'end': u'2020-04-19 15:18:19.714496', '_ansible_no_log': False, u'stdout': u'', u'cmd': u'grep nginx /etc/passwd|cat', u'rc': 0, 'item': u'nginx', u'delta': u'0:00:00.004500', '_ansible_item_label': u'nginx', u'stderr': u'', u'changed': True, u'invocation': {u'module_args': {u'warn': True, u'executable': None, u'_uses_shell': True, u'_raw_params': u'grep nginx /etc/passwd|cat', u'removes': None, u'argv': None, u'creates': None, u'chdir': None, u'stdin': None}}, 'stdout_lines': [], u'start': u'2020-04-19 15:18:19.709996', '_ansible_ignore_errors': None, 'failed': False}) TASK [print userss] ************************************************************************************************************************************************************************* ok: [vagrant1] => { "msg": [ "vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash", "root:x:0:0:root:/root:/bin/bash", "operator:x:11:0:operator:/root:/sbin/nologin" ] } TASK [print userss one by one] ************************************************************************************************************************************************************** ok: [vagrant1] => (item=vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash) => { "msg": "vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash" } ok: [vagrant1] => (item=root:x:0:0:root:/root:/bin/bash) => { "msg": "root:x:0:0:root:/root:/bin/bash" } ok: [vagrant1] => (item=operator:x:11:0:operator:/root:/sbin/nologin) => { "msg": "operator:x:11:0:operator:/root:/sbin/nologin" } TASK [print part of userss one by one] ****************************************************************************************************************************************************** ok: [vagrant1] => (item=vagrant:x:1000:1000:vagrant:/home/vagrant:/bin/bash) => { "msg": "/bin/bash" } ok: [vagrant1] => (item=root:x:0:0:root:/root:/bin/bash) => { "msg": "/bin/bash" } ok: [vagrant1] => (item=operator:x:11:0:operator:/root:/sbin/nologin) => { "msg": "/sbin/nologin" }
    2.set_を使うfact登録変数
    実は前の例でset_に言及しました.fact、set_のためにfactはregisterに協力していくつかの重要かつ柔軟な機能を実現することができます.
    2.1 set_を使用するfactに通常の変数を登録します.
    tasks:
        - name: define a var1
          shell: "whoami"
          register: whoami
    
        - debug:
            msg: "whoami: {{ whoami }}"
        
        - debug:
            msg: "whoami.stdout: {{whoami.stdout}}"
        
        - name: define a var by set_fact
          set_fact:
             whoami: "{{ whoami.stdout  }}"
         
        - name:  show a var after defined by set_fact
          debug:
             msg: "{{ whoami }}" 
    
    このような方法を使うと、変数の呼び出しが簡単になります.
    2.2 set_を使用するfactはlist変数に要素を循環的に追加します.
    この機能はセットのみです.factは、多くのシーンで使われていますが、特に自分で登録した変数にはいくつの要素があるか分かりません.また、registerに合わせて、変数の後続の呼び出しと再フォーマットが大幅に簡略化されます.実際の例1.2のコード例は、このような方法で使用されている.
      vars:
        userss: []
    
    - name: define userss by set_fact
          set_fact: 
            userss: "{{userss +item.stdout_lines}}"
          with_list: "{{ users.results }}"
    
        - name: print userss
          debug:
            msg: "{{ userss }}"
        
        - name: print userss one by one
          debug:
            msg: "{{ item }}"
          with_list: "{{ userss}}"
    
        - name: print part of userss one by one
          debug:
            msg: "{{ item.split(':')[6] }}"
          with_list: "{{ userss}}"
    
    特に注意したいのですが、List変数に元素を循環的に添加する場合、この変数はすでに定義されていて、要素を循環的に追加することができます.最後のprint partの時に、ansibleでpythonの文字列の分割関数を呼び出して、遍歴した各行の要素を分解して、私達の最も必要なフィールドを取得します.文字列を結合してから文字列を分割すると、全体的なplaybookが簡略化され、理解しにくくて間違いやすい入れ子サイクルを避けることができます.
    完全な例は、ここを見ることができます.https://github.com/byygyy/ansible-best-practice/blob/master/test-vars-define.yml