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. 《HTTPS权威指南》读书笔记——SSL/TLS协议

    记录协议(record protocol) 负责在传输连接上交换所有底层信息 每一条记录以短标头开始,标头包含记录内容的类型.协议版本和长度 握手协议(handshake protocol) 整个过程 ...

  2. 编译出错:must be index or base register

    指令 mov ds:[dx],dx 原因:上述指令使用寄存器相对寻址方式,只能使用BX,BP,SI,DI 方括号里必须是变址(index,指SI, DI)或基址(base,指BX, BP)寄存器 正确 ...

  3. Markdown数学公式语法

    详细网址:Markdown数学公式语法

  4. java之this关键字和super关键字的区别

    编号 区别点 this super 1 访问属性 访问本类中的属性,如果本类没有此 属性则从父类中继续查找 访问父类中的属性 2 调用方法 访问本类中的方法 直接访问父类中的方法 3 调用构造器 调用 ...

  5. Run-Time Check Failure #2 - Stack around the variable 's' was corrupted. 出现了 。

    程序中存在内存越界,注意数组大小和数据大小.

  6. C++入门到理解阶段二基础篇(8)——C++指针

    1.什么是指针? 为了更加清楚的了解什么是指针?我们首先看下变量和内存的关系,当我们定义了int a=10之后.相当于在内存之中找了块4个字节大小的空间,并且存储10,要想操作这块空间,就通过a这个变 ...

  7. 分布式应用监控: SkyWalking 快速接入实践

    分布式应用,会存在各种问题.而要解决这些难题,除了要应用自己做一些监控埋点外,还应该有一些外围的系统进行主动探测,主动发现. APM工具就是干这活的,SkyWalking 是国人开源的一款优秀的APM ...

  8. C#之Form表单认证

    原文地址: https://blog.csdn.net/chadcao/article/details/7859394 ASP.NET的安全认证,共有“Windows”.“Form”.“Passpor ...

  9. C# detect latest .net framework installed on PC

    static void GetNetVersionDemo() { using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.L ...

  10. .net Core数据的幕等性

    一.背景 代码实例:https://gitee.com/D_C_L/CurtainEtcAOP.git我们实际系统中有很多操作,是不管做多少次,都应该产生一样的效果或返回一样的结果. 例如: 1. 前 ...