記錄一下相關練習
以下的練習,  前提是
- SSH 可以使用 Key 登入 Remote Hosts
例如 在 Control Machine 上面( Mac / Linux )
$ ssh  -l   使用者名稱   -i   key檔案位置  RemoteHost_IP
可以直接登入SSH 建立以及複製到遠端可以參考 這篇
建立 playbooks  目錄來進行之後練習
$ mkdir   playbooks
Lab:  簡單的 ansible 指令練習
建立遠端主機相關資訊
$ vi  hosts 
# syntax: servername  options
# ansible_ssh_host -- Remote Host IP
# ansible_ssh_user -- Remote SSH User Name
# ansible_ssh_private_key_file -- SSH Key
testserver   ansible_ssh_host=遠端主機IP   ansible_ssh_user=遠端使用者名稱
測試 ansible 指令, 這邊使用 ping 的 module 
$ ansible   testserver   -i   hosts   -m   ping
testserver | success >> {
    "changed": false,
    "ping": "pong"
}
$ ansible   all   -i   hosts   -m   ping
testserver | success >> {
    "changed": false,
    "ping": "pong"
}
根據上面的指令來驗證
ansible
- 可以指定某台主機, 例如 testserver 或是全部 all
- -i 為 inventory 清單檔案所在
- -m 為 module name, 這個案例使用的是 ping
但是如果每台主機的使用者帳號還有 key 都是同一把, 那就可以建立 ansible.cfg 來設定成預設
Lab: 使用 ansible.cfg
建立 ansible.cfg 放在 playbook 目錄下
$ vi   ~/playbooks/ansible.cfg
[defaults]
# 主機清單的檔案, 這樣可以不用下 -i 選項指定
hostfile = hosts
# 遠端使用者名稱, 換成自己的使用者名稱
remote_user = cc
# SSH Key 位置, 換成自己的 key path
private_key_file = ~/.ssh/id_dsa
修改  ~/playbooks/hosts ( 因為 ansible.cfg 已經有設定 remote_user, 就不用重複設定 )
$ vi   ~/playbooks/hosts
# syntax: servername  options
# ansible_ssh_host -- Remote Host IP
# ansible_ssh_user -- Remote SSH User Name
# testserver   ansible_ssh_host=遠端主機IP   ansible_ssh_user=遠端使用者名稱
testserver   ansible_ssh_host=遠端主機IP
$ ansible   testserver    -m ping 
testserver | success >> {
    "changed": false,
    "ping": "pong"
}
但是如果對象是要用兩種以上的 ssh key 來控制, 那就可以考慮把相關的設定寫在 hosts, 並利用 群組的做法
$ cat   hosts 
ubuntu_utah ansible_ssh_host=遠端主機IP ansible_ssh_user=maxhuang ansible_ssh_private_key_file=~/id_ssh_rsa
ubuntu_cenic ansible_ssh_host=遠端主機IP ansible_ssh_user=maxhuang ansible_ssh_private_key_file=~/id_ssh_rsa
[geni]
ubuntu_utah
ubuntu_cenic
接下來嘗試使用 ansible 來安裝套件
Lab: 安裝套件
查詢套件是否安裝, 這邊使用 shell module
可以參考 http://docs.ansible.com/ansible/shell_module.html
$ ansible  ubuntu_utah   -m   shell   -a   "dpkg -l | grep nginx"
ubuntu_utah | FAILED | rc=1 >>
安裝套件
$ ansible ubuntu_utah  -s -m apt -a 'name=nginx update_cache=yes'
確認是否安裝
$ ansible ubuntu_utah  -m  shell  -a  "dpkg -l | grep nginx"
ubuntu_utah | success | rc=0 >>
ii  nginx                               1.4.6-1ubuntu3.3                    all          small, powerful, scalable web/proxy server
今天就先到這邊
~ enjoy it
 
 
沒有留言:
張貼留言