Ansible能夠集中地控制多個節點,批量地執行ssh命令。因爲其使用ssh進行操做,所以遠端服務器除了安裝openssh-server(通常服務器已經內置)以外,不須要安裝額外的軟件,所以使用很是簡單和方便。這裏以Ubuntu上的使用爲例,說明其安裝和使用方法。javascript
包括Ansible和sshpass,其中sshpass是用於交互輸入密碼的組件。由於咱們要批量處理大量節點,所以節點的密碼設爲同樣能夠大大簡化配置過程,但這會增長安全性風險,須要設置足夠強度的密碼並妥善保存。css
運行命令以下:java
sudo apt install -y ansible sshpass
這是Ansible要操做的節點主機名或IP地址的清單,能夠分組和指定登陸帳號、密碼等參數。該清單有一個系統級的默認存儲位置(參考/etc/ansible/hosts),但不建議應用使用。能夠在本身的目錄下建立一個清單,而後使用環境變量 ANSIBLE_HOSTS 來指示文件位置,或者直接放在當前目錄下,使用-i來指定清單的文件名。node
echo "127.0.0.1" > ~/ansible_hosts
# 將hosts清單放在home目錄,每次系統啓動時自動加載。 echo "export ANSIBLE_HOSTS=~/ansible_hosts" >> ~/.profile # 當即使用。 source ~/.proflie
[local] 192.168.199.188 ansible_ssh_port=22 ansible_ssh_host=192.168.199.188 ansible_ssh_user=superwork ansible_ssh_pass=SuperMap 192.168.199.249 ansible_ssh_port=22 ansible_ssh_host=192.168.199.249 ansible_ssh_user=supermap ansible_ssh_pass=SuperMap 192.168.199.174 ansible_ssh_port=22 ansible_ssh_host=192.168.199.174 ansible_ssh_user=smt ansible_ssh_pass=SuperMap
# ansible主機清單格式 # This is the default ansible 'hosts' file. # # It should live in /etc/ansible/hosts # # - Comments begin with the '#' character # - Blank lines are ignored # - Groups of hosts are delimited by [header] elements # - You can enter hostnames or ip addresses # - A hostname/ip can be a member of multiple groups # Ex 1: Ungrouped hosts, specify before any group headers. #green.example.com #blue.example.com #192.168.100.1 #192.168.100.10 # Ex 2: A collection of hosts belonging to the 'webservers' group #[webservers] #alpha.example.org #beta.example.org #192.168.1.100 #192.168.1.110 # If you have multiple hosts following a pattern you can specify # them like this: #www[001:006].example.com # Ex 3: A collection of database servers in the 'dbservers' group #[dbservers] # #db01.intranet.mydomain.net #db02.intranet.mydomain.net #10.25.1.56 #10.25.1.57 # Here's another example of host ranges, this time there are no # leading 0s: #db-[99:101]-node.example.com
ansible能夠自動按照清單在多個主機上經過ssh執行命令。python
ansible all -m ping
ansible all -m ping --ask-pass
使用--ask-pass提示用戶在運行時輸入密碼,避免將密碼保存在配置文件中,增長必定程度上的安全性。git
ansible all -m shell -a "hostname" --ask-pass -i ~/ansible_hosts
ansible all -m shell -a "docker info" --ask-pass
ansible all -m shell -a "uname -a" --ask-pass
下面的命令執行apt update操做,遠程更新各個主機的軟件包。github
ansible all -m shell -a "apt update && apt upgrade -y" --ask-sudo-pass --become --become-method=sudo
注意上面的--ask-sudo-pass和--become參數,在Ubuntu裏遠程使用sudo來執行系統級的命令。web
上面使用的是密碼登陸ssh,另一種方法是使用密鑰進行登陸,安全性更強一些,使用也更爲方便。sql
ssh-keygen -t rsa
ansible all -m copy -a "src=/home/openthings/.ssh/id_rsa.pub dest=/tmp/id_rsa.pub" --ask-pass
把公鑰文件追加到遠程服務器的受權清單裏。輸入:docker
ansible all -m shell -a "cat /tmp/id_rsa.pub >> /root/.ssh/authorized_keys" --ask-pass -u root
而後,把 /tmp 中的公鑰文件刪除:
ansible all -m file -a "dest=/tmp/id_rsa.pub state=absent" -u root
ansible all -m shell -a "hostname" -u root
Playbook將主機清單和命令合成爲一個yaml文件,使用更爲方便。
---
- hosts: SUSEBased
remote_user: mike
sudo: yes tasks: - authorized_key: user=root key="{{ lookup('file', '/home/openthings/.ssh/id_rsa.pub') }}" path=/root/.ssh/authorized_keys manage_dir=no - hosts: RHELBased remote_user: mdonlon sudo: yes tasks: - authorized_key: user=root key="{{ lookup('file', '/home/openthings/.ssh/id_rsa.pub') }}" path=/root/.ssh/authorized_keys manage_dir=no
仍是比較簡明的,下面進一步解釋playbook的格式。
一個簡單的例子:
---
- hosts: showtermClients
remote_user: root
tasks:
- yum: name=rubygems state=latest - yum: name=ruby-devel state=latest - yum: name=gcc state=latest - gem: name=showterm state=latest user_install=no
主要包括hosts、user和tasks三個主要部分,即主機、用戶和命令。
一個完整的主機配置playbook以下:
---
- hosts: showtermServers
remote_user: root
tasks:
- name: ensure packages are installed
yum: name={{item}} state=latest
with_items:
- postgresql
- postgresql-server
- postgresql-devel
- python-psycopg2
- git
- ruby21
- ruby21-passenger
- name: showterm server from github git: repo=https://github.com/ConradIrwin/showterm.io dest=/root/showterm - name: Initdb command: service postgresql initdb creates=/var/lib/pgsql/data/postgresql.conf - name: Start PostgreSQL and enable at boot service: name=postgresql enabled=yes state=started - gem: name=pg state=latest user_install=no handlers: - name: restart postgresql service: name=postgresql state=restarted - hosts: showtermServers remote_user: root sudo: yes sudo_user: postgres vars: dbname: showterm dbuser: showterm dbpassword: showtermpassword tasks: - name: create db postgresql_db: name={{dbname}} - name: create user with ALL priv postgresql_user: db={{dbname}} name={{dbuser}} password={{dbpassword}} priv=ALL - hosts: showtermServers remote_user: root tasks: - name: database.yml template: src=database.yml dest=/root/showterm/config/database.yml - hosts: showtermServers remote_user: root tasks: - name: run bundle install shell: bundle install args: chdir: /root/showterm - hosts: showtermServers remote_user: root tasks: - name: run rake db tasks shell: 'bundle exec rake db:create db:migrate db:seed' args: chdir: /root/showterm - hosts: showtermServers remote_user: root tasks: - name: apache config template: src=showterm.conf dest=/etc/httpd/conf.d/showterm.conf
使用ansible playbook的命令是ansible-playbook,其它參數與ansible是基本一致的。
ansible-playbook testPlaybook.yaml -f 10
注意,上面的 -f 參數指的是並行執行的數量。
使用 ansible -h 能夠獲取ansible的命令詳細列表,以下:
Usage: ansible <host-pattern> [options] Define and run a single task 'playbook' against a set of hosts Options: -a MODULE_ARGS, --args=MODULE_ARGS module arguments --ask-vault-pass ask for vault password -B SECONDS, --background=SECONDS run asynchronously, failing after X seconds 異步運行,能夠指定超時的時長。 (default=N/A) -C, --check don't make any changes; instead, try to predict some of the changes that may occur -D, --diff when changing (small) files and templates, show the differences in those files; works great with --check -e EXTRA_VARS, --extra-vars=EXTRA_VARS set additional variables as key=value or YAML/JSON, if filename prepend with @ -f FORKS, --forks=FORKS specify number of parallel processes to use 並行執行,可指定併發數,缺省爲5。 (default=5) -h, --help show this help message and exit -i INVENTORY, --inventory=INVENTORY, --inventory-file=INVENTORY specify inventory host path or comma separated host list. --inventory-file is deprecated 指定host文件路徑或者分隔的host清單。 -l SUBSET, --limit=SUBSET further limit selected hosts to an additional pattern --list-hosts outputs a list of matching hosts; does not execute anything else 列出hosts主機清單。 -m MODULE_NAME, --module-name=MODULE_NAME module name to execute (default=command) -M MODULE_PATH, --module-path=MODULE_PATH prepend colon-separated path(s) to module library (def ault=[u'/home/openswitch/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']) -o, --one-line condense output --playbook-dir=BASEDIR Since this tool does not use playbooks, use this as a subsitute playbook directory.This sets the relative path for many features including roles/ group_vars/ etc. 指定playbook的主目錄。 -P POLL_INTERVAL, --poll=POLL_INTERVAL set the poll interval if using -B (default=15) pull的時間間隔。 --syntax-check perform a syntax check on the playbook, but do not execute it -t TREE, --tree=TREE log output to this directory 日誌輸出目錄。 --vault-id=VAULT_IDS the vault identity to use --vault-password-file=VAULT_PASSWORD_FILES vault password file -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) --version show program's version number and exit Connection Options: control as whom and how to connect to hosts -k, --ask-pass ask for connection password 詢問密碼。 --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE use this file to authenticate the connection -u REMOTE_USER, --user=REMOTE_USER 指定遠端主機上的用戶名,將用該用戶操做。 connect as this user (default=None) -c CONNECTION, --connection=CONNECTION connection type to use (default=smart) -T TIMEOUT, --timeout=TIMEOUT override the connection timeout in seconds 指定鏈接超時,缺省爲1 (default=10) --ssh-common-args=SSH_COMMON_ARGS specify common arguments to pass to sftp/scp/ssh (e.g. ProxyCommand) --sftp-extra-args=SFTP_EXTRA_ARGS specify extra arguments to pass to sftp only (e.g. -f, -l) --scp-extra-args=SCP_EXTRA_ARGS specify extra arguments to pass to scp only (e.g. -l) --ssh-extra-args=SSH_EXTRA_ARGS specify extra arguments to pass to ssh only (e.g. -R) Privilege Escalation Options: control how and which user you become as on target hosts -s, --sudo run operations with sudo (nopasswd) (deprecated, use become) 指定使用sudo操做,已過期,使用become。 -U SUDO_USER, --sudo-user=SUDO_USER desired sudo user (default=root) (deprecated, use become) 已過期,使用become。 -S, --su run operations with su (deprecated, use become) 已過期,使用become。 -R SU_USER, --su-user=SU_USER run operations with su as this user (default=None) (deprecated, use become) 已過期,使用become。 -b, --become run operations with become (does not imply password prompting) 使用become操做。 --become-method=BECOME_METHOD privilege escalation method to use (default=sudo), valid choices: [ sudo | su | pbrun | pfexec | doas | dzdo | ksu | runas | pmrun | enable ] become操做方法,缺省爲sudo。 --become-user=BECOME_USER run operations as this user (default=root) become操做的用戶名,缺省爲root。 --ask-sudo-pass ask for sudo password (deprecated, use become) 已過期,使用become。 --ask-su-pass ask for su password (deprecated, use become) 已過期,使用become。 -K, --ask-become-pass ask for privilege escalation password Some modules do not make sense in Ad-Hoc (include, meta, etc)