Ansible可以集中地控制多个节点,批量地执行ssh命令。由于其使用ssh进行操作,因此远端服务器除了安装openssh-server(一般服务器已经内置)之外,不需要安装额外的软件,因此使用非常简单和方便。这里以Ubuntu上的使用为例,说明其安装和使用方法。
- 空的物理机安装考虑使用MAAS或者kickStart/Cobbler。
1、快速安装
包括Ansible和sshpass,其中sshpass是用于交互输入密码的组件。因为我们要批量处理大量节点,因此节点的密码设为一样可以大大简化配置过程,但这会增加安全性风险,需要设置足够强度的密码并妥善保存。
运行命令如下:
sudo apt install -y ansible sshpass
2、创建Hosts清单
这是Ansible要操作的节点主机名或IP地址的清单,可以分组和指定登录账号、密码等参数。该清单有一个系统级的默认存储位置(参考/etc/ansible/hosts),但不建议应用使用。可以在自己的目录下创建一个清单,然后使用环境变量 ANSIBLE_HOSTS 来指示文件位置,或者直接放在当前目录下,使用-i来指定清单的文件名。
创建主机清单
- 创建一个hosts主机清单文件:
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
3、操作多台主机
ansible可以自动按照清单在多个主机上通过ssh执行命令。
马上试一下
- 现在来试一下,ping清单中所有的机器:
ansible all -m ping
- 或者提示输入 ssh 密码:
ansible all -m ping --ask-pass
使用--ask-pass提示用户在运行时输入密码,避免将密码保存在配置文件中,增加一定程度上的安全性。
- 指定清单文件,远程获取清单中所有机器的hostname:
ansible all -m shell -a "hostname" --ask-pass -i ~/ansible_hosts
- 获取Docker信息:
ansible all -m shell -a "docker info" --ask-pass
- 获取主机信息:
ansible all -m shell -a "uname -a" --ask-pass
执行sudo操作
下面的命令执行apt update操作,远程更新各个主机的软件包。
ansible all -m shell -a "apt update && apt upgrade -y" --ask-sudo-pass --become --become-method=sudo
注意上面的--ask-sudo-pass和--become参数,在Ubuntu里远程使用sudo来执行系统级的命令。
4、密钥登录设置
上面使用的是密码登录ssh,另外一种方法是使用密钥进行登录,安全性更强一些,使用也更为方便。
- 创建密钥:
ssh-keygen -t rsa
- 上传密钥到远程主机:
ansible all -m copy -a "src=/home/openthings/.ssh/id_rsa.pub dest=/tmp/id_rsa.pub" --ask-pass
-
把公钥文件追加到远程服务器的授权清单里。输入:
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
- 试一下(现在不需要输入密码了,也不需使用--ask-pass参数):
ansible all -m shell -a "hostname" -u root
- 注意:
- 使用mass装机的节点,可以(设置)自动注入maas controller的ssh密钥,不需要再次配置。
5、Playbook使用
Playbook将主机清单和命令合成为一个yaml文件,使用更为方便。
- 把上面的ssh密钥分发的过程编写为一个playbook文件,如下:
--- - 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的格式。
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
Playbook使用
使用ansible playbook的命令是ansible-playbook,其它参数与ansible是基本一致的。
ansible-playbook testPlaybook.yaml -f 10
注意,上面的 -f 参数指的是并行执行的数量。
6、Ansible命令参考
使用 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)