Ansible可以集中地控制多个节点,批量地执行ssh命令。由于其使用ssh进行操作,因此远端服务器除了安装openssh-server(一般服务器已经内置)之外,不需要安装额外的软件,因此使用非常简单和方便。这里以Ubuntu上的使用为例,说明其安装和使用方法。

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)

MAAS装机后的设置和应用软件安装

Ansible快速开始-指挥集群的更多相关文章

  1. 使用 Ansible 快速部署 HBase 集群

    背景 出于数据安全的考虑,自研了一个低成本的时序数据存储系统,用于存储历史行情数据. 系统借鉴了 InfluxDB 的列存与压缩策略,并基于 HBase 实现了海量存储能力. 由于运维同事缺乏 Had ...

  2. ansible快速部署cassandra3集群

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  3. Ansible自动化部署K8S集群

    Ansible自动化部署K8S集群 1.1 Ansible介绍 Ansible是一种IT自动化工具.它可以配置系统,部署软件以及协调更高级的IT任务,例如持续部署,滚动更新.Ansible适用于管理企 ...

  4. MariaDB Galera Cluster 部署(如何快速部署 MariaDB 集群)

    MariaDB Galera Cluster 部署(如何快速部署 MariaDB 集群)  OneAPM蓝海讯通7月3日 发布 推荐 4 推荐 收藏 14 收藏,1.1k 浏览 MariaDB 作为 ...

  5. MariaDB Galera Cluster 部署(如何快速部署MariaDB集群)

    MariaDB Galera Cluster 部署(如何快速部署MariaDB集群) [日期:--] 来源:Linux社区 作者:Linux [字体:大 中 小] MariaDB作为Mysql的一个分 ...

  6. docker 快速部署ES集群 spark集群

    1) 拉下来 ES集群  spark集群 两套快速部署环境, 并只用docker跑起来,并保存到私库. 2)弄清楚怎么样打包 linux镜像(或者说制作). 3)试着改一下,让它们跑在集群里面. 4) ...

  7. Kubernetes探索学习001--Centos7.6使用kubeadm快速部署Kubernetes集群

    Centos7.6使用kubeadm快速部署kubernetes集群 为什么要使用kubeadm来部署kubernetes?因为kubeadm是kubernetes原生的部署工具,简单快捷方便,便于新 ...

  8. [k8s]kubespray(ansible)自动化安装k8s集群

    kubespray(ansible)自动化安装k8s集群 https://github.com/kubernetes-incubator/kubespray https://kubernetes.io ...

  9. Docker快速构建Redis集群(cluster)

    Docker快速构建Redis集群(cluster) 以所有redis实例运行在同一台宿主机上为例子 搭建步骤 redis集群目录清单 . ├── Dockerfile ├── make_master ...

随机推荐

  1. SpringBoot条件注解的总结

    https://blog.csdn.net/qq_31142553/article/details/86439950

  2. [考试反思]1113csp-s模拟测试114:一梦

    自闭.不废话.写一下低错. T1:觉得信心赛T1不会很恶心一遍过样例直接没对拍(其实是想写完T2之后回来对拍的) 状态也不好,基本全机房都开始码了我还没想出来(skyh已经开T2了).想了40多分钟. ...

  3. 【RTOS】基于V7开发板的uCOS-III,uCOS-II,RTX4,RTX5,FreeRTOS原版和带CMSIS-RTOS V2封装层版全部集齐

    RTOS模板制作好后,后面堆各种中间件就方便了. 1.基于V7开发板的最新版uCOS-II V2.92.16程序模板,含MDK和IAR,支持uC/Probe https://www.cnblogs.c ...

  4. 分布式文件服务器FastDFS的使用

    分布式项目中涉及到的文件上传与下载,此时使用之前的上传方式,将上传的文件与当前项目所在服务器放在同一个位置,显然不符合分布式项目的理念,此时我们借助FastDFS将上传的文件数据存储到单纯的一个服务器 ...

  5. React 从入门到进阶之路(二)

    在之前的文章中我们介绍了 React 开发的环境搭建及目录介绍和整理,本篇文章将介绍 React 创建组件.JSX 语法.绑定数据和绑定对象. 之前我们已经将项目运行了起来,我们再来看一下目录结构: ...

  6. 解决root无法登陆

    今天重装了一下虚拟机,用filezilla往Linux扔文件需要用root的超级权限,但是却不能建立连接,使用账号密码也无法登录root账户 鼓捣好一阵才知道,因为root权限太高了,可以针对root ...

  7. 学习强国docker文件用法

    学习强国docker用法 docker文件地址   https://github.com/fuck-xuexiqiangguo/docker 构建  docker  docker build -t D ...

  8. VS2019 .Net Core 3.0 Web 项目启用动态编译

    VS2019 中 .Net Core 3.0 项目默认没有启用动态编译, 这导致按F5调试的时候,修改了 HTML 代码,在浏览器上刷新没有效果. 启用动态编译方法如下: 1. 安装 Microsof ...

  9. Python进阶一

    文章目录 异常处理 1 基本用法 2高级用法 逻辑运算符 循环的高级用法 异常处理1 基本用法应对所有情况 try: 1/0 except: print('某原因异常') 应对特定异常情况 try: ...

  10. SSM框架之Spring(5)JdbcTemplate及spring事务控制

    Spring(5)JdbcTemplate及spring事务控制 ##1.JdbcTmeplate 它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装.spring ...