3.ansibleの使用とモジュール化の深い解析


1.メインプロファイルの説明
ansible     /etc/ansible/ansible.cfg(      )
[defaults]  #   
#inventory      = /etc/ansible/hosts  #        
#library        = /usr/share/my_modules/  #       
#module_utils   = /usr/share/my_module_utils/
#remote_tmp     = ~/.ansible/tmp   #           
#local_tmp      = ~/.ansible/tmp  #                                 
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml
#forks          = 5   #    5 
#poll_interval  = 15  #15       
#sudo_user      = root  #             root      sudo
#ask_sudo_pass = True   #    ansible      ssh  
#ask_pass      = True
#transport      = smart
#remote_port    = 22   #         
#module_lang    = C
#module_set_locale = False  
#host_key_checking = False #        host_key,                     2  
#log_path=/var/log/ansible.log #     (    ,    )

2.接続が確立されていないためpingできない
[root@ansible ~]# cd .ssh/
[root@ansible .ssh]# ls
known_hosts   #          ssh            ping               
[root@ansible .ssh]# rm -rf known_hosts

[root@ansible .ssh]# ansible all -m ping -k
SSH password:
10.0.0.48 | FAILED! => {
    "msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host's fingerprint to your known_hosts file to manage this host."
}
10.0.0.49 | FAILED! => {
    "msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host's fingerprint to your known_hosts file to manage this host."
}

         ssh       
  
#host_key_checking = False #        host_key,      


#   
[root@ansible .ssh]# ansible all -m ping -k
SSH password:
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}


3.ansibleシリーズコマンド
[root@ansible ~]# ansible  # tab
ansible               ansible-console       ansible-doc-2.7       ansible-playbook      ansible-pull-2.7
ansible-2             ansible-console-2     ansible-galaxy        ansible-playbook-2    ansible-test
ansible-2.7           ansible-console-2.7   ansible-galaxy-2      ansible-playbook-2.7  ansible-vault
ansible-config        ansible-doc           ansible-galaxy-2.7    ansible-pull          ansible-vault-2
ansible-connection    ansible-doc-2         ansible-inventory     ansible-pull-2        ansible-vault-2.7


Ansible    
ansible ansible-doc ansible-playbookansible-vault
ansible-consoleansible-galaxyansible-pull
ansible-doc:      
ansible-doc [options][module...]
         
-a
-l,--list      
-s, --snippet       playbook  
  :
ansible-docl      
ansible-doc ping          
ansible-doc -s ping          

[root@ansible ~]# ansible doc ping  #            
usage: ansible [-h] [--version] [-v] [-b] [--become-method BECOME_METHOD]
               [--become-user BECOME_USER] [-K] [-i INVENTORY] [--list-hosts]
               [-l SUBSET] [-P POLL_INTERVAL] [-B SECONDS] [-o] [-t TREE] [-k]
               [--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER]
               [-c CONNECTION] [-T TIMEOUT]
               [--ssh-common-args SSH_COMMON_ARGS]
               [--sftp-extra-args SFTP_EXTRA_ARGS]
               [--scp-extra-args SCP_EXTRA_ARGS]
               [--ssh-extra-args SSH_EXTRA_ARGS] [-C] [--syntax-check] [-D]
               [-e EXTRA_VARS] [--vault-id VAULT_IDS]
               [--ask-vault-pass | --vault-password-file VAULT_PASSWORD_FILES]
               [-f FORKS] [-M MODULE_PATH] [--playbook-dir BASEDIR]
               [-a MODULE_ARGS] [-m MODULE_NAME]
               pattern
ansible: error: unrecognized arguments: ping

#  ansible    
[root@ansible ~]# ansible-doc -l | wc -l
3387

[root@ansible ~]# ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
  ping:
      data:                  # Data to return for the `ping' return value. If this parameter is set to `crash', the
                               module will cause an exception.


ansibleはsshを通じて構成管理、応用配置、タスク実行などの機能を実現し、ansibleエンドエネルギーベースサブキー認証を構成する方法で各管理ノードansible–version表示バージョン-m module指定モジュールに連絡することを提案し、デフォルトはcommand-v詳細プロセス→vv-vvより詳細である
-list-hostsホストのリストを表示します.簡単に書くことができます.list
[root@ansible ~]# ansible all --list-hosts
  hosts (2):
    10.0.0.48
    10.0.0.49

-k,–ask-passヒントssh接続パスワード、デフォルトKey検証-K、–ask-become-passヒントsudo入力時のパスワード-C、–checkチェック、Tは実行されず、–timeout=TIMEOUT実行コマンドのタイムアウト時間、デフォルト10 s-u、–user=REMOTE_USERリモート実行を実行するユーザ
[root@ansible ~]# ansible webserver -m ping -u y -k
SSH password:
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

[root@ansible ~]# ansible webserver -u y -k -m command -a'ls /root'
SSH password:
10.0.0.48 | FAILED | rc=2 >>
ls: cannot open directory /root: Permission deniednon-zero return code
#         

-b,-becomeはl旧版のsudo切り替えに代わる
実戦
1.鍵の生成
[root@ansible ansible]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:jd0oYIQ0Ms/MYd5V3mV3W3DEr4xfOHbP2dCV3ZIATv0 root@ansible
The key's randomart image is:
+---[RSA 2048]----+
|  o.=.. ..+o  ++*|
|   X.= . + .oo o=|
|    * +   o .o o=|
|     . . + o  E.=|
|        S + .o =.|
|         .  . B +|
|             o *+|
|              ..+|
|                 |
+----[SHA256]-----+

2.コピー先ホスト
[root@ansible ansible]# ssh-copy-id 10.0.0.48
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '10.0.0.48'"
and check to make sure that only the key(s) you wanted were added.
[root@ansible ansible]# ssh-copy-id 10.0.0.49
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '10.0.0.49'"
and check to make sure that only the key(s) you wanted were added.

3.ansibleのHost-pattern
3.1 all
ansible all -m ping
すべてのInventoryのすべてのホストを表します
[root@ansible ansible]# ansible all -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
[root@ansible ansible]#

3.2グループ化のサポート
ansible webserver -m ping
[root@ansible ansible]# ansible webserver -m ping
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
[root@ansible ansible]# ansible dbserver -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

3.3*:ワイルドカード
ansible *server -m ping
[root@ansible ansible]# ansible *server -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

ansible “10.0.0.*” -m ping
[root@ansible ansible]# ansible "10.0.0.*" -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

ansible “*” -m ping
[root@ansible ansible]# ansible "*" -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

3.4関係
:論理または
[root@ansible ansible]# ansible webserver:dbserver -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

:&論理と
#                    
ansible 'webserver:&dbserver' -m ping

:!ろんりひ
#     
ansible 'webserver:!dbserver' -m ping

そうごうロジック
#  webserver dbserver     appserver     ftpserver  
ansible 'webserver:dbserver:&appservers:!ftpserver' -m ping

3.5正規表現
ansible "webserver:&dbserver" -m ping
ansible "~(web|db).*\.magedu\.com" -m ping
~ :       web|db   
.      magedu
[root@ansible ansible]# ansible '~(web|db)' -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}



[root@ansible ansible]# ansible '~(web|db)server' -m ping
10.0.0.49 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
10.0.0.48 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}


4.ansibleコマンド実行のプロセス
ansibleコマンド実行プロセス
  • 独自のプロファイルをロードデフォルト/etc/ansible/ansible.cfg
  • command
  • などの対応するモジュールファイルをロード
  • は、ansibleを介してモジュールまたはコマンドから対応する一時pyファイルを生成し、リモートサーバの対応する実行ユーザ$HOME/.ansible/tmp/ansible-tmp-デジタル/xxX.PYファイル
  • に転送する.
  • ファイル+xに対して
  • を実行する.
  • 実行結果
  • を返す.
  • 一時pyファイルを削除し、sleep oは
  • を終了します.
    実行ステータス:
  • 緑色:実行に成功し、変更を必要としない操作
  • イエロー:実行に成功し、ターゲットホストを変更
  • 赤:実行失敗
  • 詳細な実行コマンドの表示
     ansible all -m ping -vvv
    

    5.ansible使用例
    # wang    ping    
    ansible all -m ping-u wang -k
    
    # wang sudo root  ping    
    ansible all -m ping -u wang-b-k
    
    # wang sudo mage    ping    
    ansible all -m|ping-u wang -b-k --become-user mage
    
    # wang sudo root    ls
    ansible all -m command -u wang --become-user=root -a 'ls /root' -b -k -K
    

    6.ansible共通モジュール
    1.概要
  • Command:リモートホストでコマンドを実行、デフォルトモジュール、無視可能-mオプション
  • 
    ```bash
    ansible srvs -m command -a 'service vsftpd start'
    ansible srvs-m command -a 'echo magedu |passwd --stdin wang’   
    >      $VARNAME< > |;& , shell    
    
  • Shell:commandと同様shellでコマンド
  • を実行
    ansible srv-m shell -a 'echo magedu |passwd -stdin wang'
      bash      cat/tmp/stanley.md | awk -F'I'‘iprint $1,$2y&>
    /tmp/example.txt      ,    shell      ,    ∶    
     ,copy   ,  ,                
    
  • Script:実行スクリプト
  • -a "/PATH/TO/SCRIPT_FILE“
    snsible websrvs -m script -a f1.sh
    
  • Copy:サーバからクライアントにファイルをコピーする
  • ansible all -m copy -a "src=/root/f1.sh dest=/tmp/f2.sh owner=wang mode=600 backup=yes"
          ,    ,       
    ansible all -m copy -a "content='test content
    ' dest=/tmp/f1.txt"
  • Fetch:クライアントからサーバ側にファイルを取り、copyとは逆にターゲットをtar
  • にすることができる.
    ansible all -m fetch -a 'src=/root/a.sh dest=/data/scripts'
    

    File:ファイルのプロパティの設定
    ansible all -m file -a "path=/root/a.sh owner=wang mode=755"
    ansible web -m file -a 'src=/app/testfile dest=/app/testfile-link state=link'
    

    2.例
    1.デフォルトcommandモジュール
    1.条件判断
    removes           
    creates            
    
    #    /etc/fs       cat
    ansible all -a 'removes=/etc/fs cat /etc/fstab'
    
    #           
    ansible all -a 'creates=/etc/fs cat /etc/fstab'
    

    2.ディレクトリの切り替え
     ansible all -a 'chdir=/boot ls'
    

    3.ユーザーの作成
    [root@ansible ansible]# ansible 10.0.0.48 -a 'useradd test1'
    10.0.0.48 | CHANGED | rc=0 >>
    
    [root@ansible ansible]# ansible 10.0.0.48 -a 'getent passwd test1'
    10.0.0.48 | CHANGED | rc=0 >>
    test1:x:1002:1002::/home/test1:/bin/bash
    

    4.command特殊記号にバグがある
    shellモジュールの推奨
    [root@ansible ansible]# ansible 10.0.0.48 -a 'echo magedu|passwd --stdin test1'
    10.0.0.48 | CHANGED | rc=0 >>
    magedu|passwd --stdin test1
    [root@ansible ansible]# ansible 10.0.0.48 -a 'getent shadow test1'
    10.0.0.48 | CHANGED | rc=0 >>
    test1:!!:18488:0:99999:7:::   #!!     
    [root@ansible ansible]# ansible 10.0.0.48 -a 'echo $HOSTNAME'
    10.0.0.48 | CHANGED | rc=0 >>
    $HOSTNAME   #     $HOSTNAME
    

    2.shellモジュール
    シェルはcommandより強い
    [root@ansible ansible]# ansible 10.0.0.48 -m shell -a 'echo $HOSTNAME'
    10.0.0.48 | CHANGED | rc=0 >>
    c7-48    #    
    
    #          
    [root@ansible ansible]# ansible 10.0.0.48 -m shell -a "echo magedu|passwd --stdin test1"
    10.0.0.48 | CHANGED | rc=0 >>
    Changing password for user test1.
    passwd: all authentication tokens updated successfully.
    [root@ansible ansible]# ansible 10.0.0.48 -m shell -a "getent shadow test1"       10.0.0.48 | CHANGED | rc=0 >>
    test1:$6$2zu5Lawc$5UgDQI8CR7cImwOu.AcTzM9pnM4UjW.svTM9mY3h3HI4nX4ECMEnoVzzwY0kWPaYVRRLL1p/FFzQQEsvaD.hU/:18488:0:99999:7:::
    
    

    scriptモジュール
    ##          
    [root@ansible ansible]# vim host.sh 
    #!/bin/bash
    hostname
    [root@ansible ansible]# chmod +X host.sh
    [root@ansible ansible]# pwd
    /etc/ansible
      script               
    
    [root@ansible ansible]# ansible all -m script -a "/etc/ansible/host.sh"
    10.0.0.48 | CHANGED => {
        "changed": true,
        "rc": 0,
        "stderr": "Shared connection to 10.0.0.48 closed.\r
    "
    , "stderr_lines": [ "Shared connection to 10.0.0.48 closed." ], "stdout": "c7-48\r
    "
    , "stdout_lines": [ "c7-48" ] } 10.0.0.49 | CHANGED => { "changed": true, "rc": 0, "stderr": "Shared connection to 10.0.0.49 closed.\r
    "
    , "stderr_lines": [ "Shared connection to 10.0.0.49 closed." ], "stdout": "c7-49\r
    "
    , # "stdout_lines": [ "c7-49" ] }

    copyモジュール
    copyオプションの検索
    ansible-doc -s copy 
    
  • ファイルを宛先ホスト
  • にコピーする
    ansible all -m copy -a 'src=/root/ansible/selinux dest=/etc/selinux/config backup=yes'
    
    ansible all -a 'cat /etc/selinux/config' #  
    ansible all -a 'ls /etc/selinux'  #      
    ansible all -m shell -a 'rm -f /etc/selinux/config.*'  #       
    
    ansible all -m shell -a 'reboot'
    #   selinux       
    ansible all -m shell -a 'getenforce' #  
    
    #       
    ansible all -m copy -a 'src=/etc/shadow dest=/data/ mode=000 owner=wang'
    ansible all -a 'ls -l /data/'  #  
    
    #           
    ansible all -m copy -a 'content="hello
    thanks
    " dest=/data/f2'
    ansible all -m ping -a 'cat /data/f2' #content

    srcがネイティブソースファイルdestであるターゲットファイルbackup=yesプッシュする場合はコピー保留ソースファイルmode=権限を設定owner=所有者を設定するかansible all-a'cat/etc/selinux/configを設定するか