为了能到远方,脚下的每一步都不能少.|

南哈哈

园龄:3年10个月粉丝:2关注:0

ansible 学习

配置epel源

装上了 EPEL 之后,就相当于添加了一个第三方源。

CentOS 源包含的大多数的库都是比较旧的。并且,很多流行的库也不存在。EPEL 在其基础上不仅全,而且还够新。

比如安装较新版 ansible 的过程中,需要解决依赖性,但是系统镜像源中对应的软件包都比较旧。所以需要配置epel源。

配置方法

yum 源的路径需要写到repodata的父目录,所以最简单直接的方法就是直接配置阿里云对应的baseurl

$ more epel.repo
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=http://mirrors.aliyun.com/epel/7/$basearch
failovermethod=priority
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

$basearch 介绍

查看已配置的源

$ yum repolist
源标识 源名称 状态
epel/x86_64 Extra Packages for Enterprise Linux 7 - x86_64 13,770

下载epel源

wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo

 

 

安装ansible

查看ansible信息

$ yum info ansible
已加载插件:fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.huaweicloud.com
* extras: mirrors.tuna.tsinghua.edu.cn
* updates: mirrors.tuna.tsinghua.edu.cn
已安装的软件包
名称 :ansible
架构 :noarch
版本 :2.9.27
发布 :1.el7
大小 :103 M
源 :installed
来自源:epel
简介 : SSH-based configuration management, deployment, and task execution system
网址 :http://ansible.com
协议 : GPLv3+
描述 : Ansible is a radically simple model-driven configuration management,
: multi-node deployment, and remote task execution system. Ansible works
: over SSH and does not require any software or daemons to be installed
: on remote nodes. Extension modules can be written in any language and
: are transferred to managed machines automatically.

通过yum的方式进行安装

$ yum -y install ansible

查看ansible文件列表

$ rpm -ql ansible
# 配置文件
/etc/ansible/ansible.cfg # 主配置文件,配置ansible工作特性
/etc/ansible/hosts # 主机清单,对那些主机进行管理
/etc/ansible/roles # 存放角色的目录
# 程序
/usr/bin/ansible # 主程序,临时命令执行工具
/usr/bin/ansible-doc # 查看配置文档,模块功能查看工具
/usr/bin/ansible-galaxy # 下载/上传优秀代码或Roles模块的官网平台
/usr/bin/ansible-playbook # 定制自动化任务,编排剧本工具
/usr/bin/ansible-pull # 远程执行命令的工具
/usr/bin/ansible-vault # 文件加密工具
/usr/bin/ansible-console # 基于Console界面与用户交互的执行工具
/usr/lib/python2.7/site-packages/ansible/executor/playbook_executor.py # 对应的库文件,很多
/usr/lib/python2.7/site-packages/ansible/module_utils/aws/elb_utils.py # module_utils 各种模块
/usr/lib/python2.7/site-packages/ansible/modules/files/file.py # 管理文件的模块
......

验证是否安装成功,查看版本

$ ansible --version
ansible 2.9.27
config file = /etc/ansible/ansible.cfg # 配置文件
configured module search path = [u'/root/.ansible/plugins/modules # 模块搜索路径', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible # 模版路径
executable location = /usr/bin/ansible # 二进制程序命令
python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]

测试ping模块

$ ansible -m ping 192.168.0.104
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
[WARNING]: Could not match supplied host pattern, ignoring: 192.168.0.104
[警告]:提供的主机列表为空,只有localhost可用。请注意,隐式localhost与“all”不匹配
[警告]:无法匹配提供的主机模式,忽略:192.168.0.104
# 想要对192.168.0.104 主机进行控制,需要将其加入到清单中。
# 配置主机清单
$ vi /etc/ansible/hosts
[myhosts]
192.168.0.104
192.168.128.129
# 再次测试ping模块,走了ssh协议
$ ansible 192.168.128.129 -m ping
The authenticity of host '192.168.128.129 (192.168.128.129)' can't be established.
ECDSA key fingerprint is SHA256:o8Tx+fBF1w/UXPeYRcwD+hjOnQY2ufvuPmZ9Vq+yCW8.
ECDSA key fingerprint is MD5:c0:b8:4f:42:65:66:d2:9a:98:69:7d:9a:51:83:39:6a.
Are you sure you want to continue connecting (yes/no)? yes
192.168.128.129 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: Warning: Permanently added '192.168.128.129' (ECDSA) to the list of known hosts.\r\nAuthentication failed.",
"unreachable": true
}
# 当前没有进行认证,无法访问 没有进行key的验证,可以使用-k参数 输入ssh root密码进行验证
# 返回结果巨慢,下面对其进行优化
$ ansible 192.168.128.129 -m ping -k

小问题:ansible执行结果非常慢进行调优

Ansible性能调优

优化参考

# 修改sshd_config文件
$ vim /etc/ssh/sshd_config
UseDNS no # 关闭DNS反向解析,极大提高ssh连接速度
GSSAPIAuthentication no # 关闭GSSAPI认证,极大提高ssh连接速度
# 重启sshd服务
$ systemctl restart sshd
修改完后再次执行ansible命令就会非常的快!

 再次ping测试

$ ansible 192.168.128.129 -m ping -k
SSH password:
192.168.128.129 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}

成功! 

多节点ping测试

$ ansible 192.168.128.129,192.168.0.104 -m ping -k
SSH password:
192.168.0.104 | FAILED! => {
"msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."
}
192.168.128.129 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
# 报错known_hosts 文件没有记录192.168.0.104 IP
$ cat /root/.ssh/known_hosts
192.168.128.129 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJlIj2A3fHTWUN4ZX3EV58DbO1+qGaVGQwH5os5sPnj7cip+/YL+zuqMY/9BKk6GdFfs7NsvzBF1CryzJDmBMGQ=
# 连接下104机器生成known_hosts文件
$ ssh root@192.168.0.104
# 再次使用ping测试
# 但是这里有一个问题,仅限于密码一致情况下使用
$ ansible 192.168.128.129,192.168.0.104 -m ping -k
SSH password:
192.168.128.129 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.0.104 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}

创建主机清单

$ vi /etc/ansible/hosts
[master]
192.168.0.104
192.168.128.129
[node]
192.168.0.105
192.168.0.106
192.168.0.107
[etcd]
192.168.0.10[5:7]

验证

$ ansible master -m ping -k
SSH password:
192.168.128.129 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.0.104 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}

ansible 配置文件

ansible 配置文件 /etc/ansible/ansible.cfg (一般保持默认)

[defaults]
# some basic default values...
#inventory = /etc/ansible/hosts # 主机列表配置文件
#library = /usr/share/my_modules/ # 库文件存放目录
#module_utils = /usr/share/my_module_utils/ # 模块目录
#remote_tmp = ~/.ansible/tmp # 临时py命令文件存放在远程主机目录
#local_tmp = ~/.ansible/tmp # 本机的临时命令执行目录
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml # 插件配置文件
#forks = 5 # 默认并发数
#poll_interval = 15 # 15秒间隔拉一次数据
#sudo_user = root # 默认sudo用户
#ask_sudo_pass = True # 每次执行ansible 命令是否询问ssh密码
#ask_pass = True # 提供用户名口令 -k
#transport = smart
#remote_port = 22 # 远程主机端口号
#module_lang = C
#host_key_checking = False # 检查对应服务器的host_key,建议取消注释
#module_set_locale = False
#log_path = /var/log/ansible.log # 日志文件

小验证

# 取消注释以禁用SSH密钥主机检查
host_key_checking = False
# 删除known_hosts文件
$ rm -rf /root/.ssh/known_hosts
# 再次进行ping测试,可以直接通
$ ansible all -m ping -k
SSH password:
192.168.0.105 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.0.104 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}

ansible系统命令

ansible
ansible-doc
ansible-playbook
ansible-vault
ansible-console
ansible-galaxy
ansible-pull

ansible-doc

ansible-doc:显示模块帮助
ansible-doc [options] [module]..
-l, --list 显示所有模块的文档
-s, --snippet 显示指定模块的playbook片段
示例:
ansible-doc -l # 列出所有模块
ansible-doc ping # 查看指定模块帮助用法
ansible-doc -s ping # 查看指定模块帮助用法

ansible

ansible通过ssh实现配置管理、应用部署、任务执行等功能,建议配置ansible端能基于密钥认证的方式联系各被管理节点。

ansible <host-pattern> [-m module_name] [-a args]
--version 显示版本
-m module 指定模块,默认为command
-v 详细过程,-vv -vvv 更详细
--list-host 显示主机列表
-k, --ask-pass 提示输入ssh连接密码,默认key验证
-u REMOTE_USER, --user REMOTE_USER 执行远程执行的用户
-b, --become 代替旧版的sudo 切换
-K, --ask-become-pass 提示输入sudo时的口令
-C, --check 检查,并不执行
-T TIMEOUT, --timeout TIMEOUT 执行命令的超市时间,默认10s

小验证

# 使用 command 命令通过 ls 进行查看
$ ansible all -m command -a 'ls /root' -k
SSH password:
192.168.0.104 | CHANGED | rc=0 >>
original-ks.cfg
# 使用 -u 参数 登录远程用户查看
$ ansible all -m command -a 'ls /root' -k -u nan
SSH password:
192.168.0.104 | FAILED | rc=2 >>
ls: 无法打开目录/root: 权限不够non-zero return code
# 使用 -b 参数 切换使用sudo
$ ansible all -m command -a 'ls /root' -k -u nan -b
SSH password:
192.168.0.104 | FAILED! => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"module_stderr": "Shared connection to 192.168.0.104 closed.\r\n",
"module_stdout": "sudo: 需要密码\r\n",
"msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
"rc": 1
}
# 使用-K输入sudo密码
$ ansible all -m command -a 'ls /root' -k -u nan -b -K
SSH password:
BECOME password[defaults to SSH password]:
192.168.0.105 | FAILED! => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"module_stderr": "Shared connection to 192.168.0.105 closed.\r\n",
"module_stdout": "\r\n我们信任您已经从系统管理员那里了解了日常注意事项。\r\n总结起来无外乎这三点:\r\n\r\n #1) 尊重别人的隐私。\r\n #2) 输入前要先考虑(后果和风险)。\r\n #3) 权力越大,责任越大。\r\n\r\n\r\nnan 不在 sudoers 文件中。此事将被报告。\r\n",
"msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
"rc": 1
}
$ visudo
$ cat -n /etc/sudoers|grep %wheel
%wheel ALL=(ALL) ALL
$ usermod -G wheel nan # 将用户nan加入到wheel组中
$ cat /etc/group | grep wheel
wheel:x:10:nan
# 再次验证可以查看
$ ansible all -a 'ls /root' -k -u nan -b -K
SSH password:
BECOME password[defaults to SSH password]:
192.168.0.104 | CHANGED | rc=0 >>
original-ks.cfg
# 增加visudo颜色
$ echo export EDITOR=vim >> /etc/profile.d/env.sh
$ source /etc/profile.d/env.sh
# 取消二次输入sudo密码
$ visudo
%wheel ALL=(ALL) NOPASSWD: ALL # 删除注释
$ ansible all -a 'ls /root' -k -u nan -b
SSH password:
192.168.0.104 | CHANGED | rc=0 >>
original-ks.cfg

基于key的方式进行验证,每次加-k输入ssh密码很麻烦

# 设置免密
$ ssh-keygen
$ ssh-copy-id root@192.168.0.104
# 不需要 -k 直接可以连通
$ ansible all -a 'ls /root'
192.168.0.104 | CHANGED | rc=0 >>
original-ks.cfg

ansible的Host-pattern

ansible的Host-pattern
匹配主机的列表
all:表示所有inventory中的所有主机
ansible all -m ping
* :通配符
ansible "*" -m ping
ansible 192.168.8.* -m ping
ansible *ter -m ping
或关系
ansible "master:slave" -m ping
ansible "192.168.8.132:192.168.8.133" -m ping
逻辑与
ansible "master:&slave" -m ping
在master组并且在slave组中的主机
逻辑非
ansible 'master:!slave' -m ping
在master组,但不在slave组中的主机
注意:此处为单引号
综合逻辑
ansible 'web:db:&app:!ftp' -m ping
正则表达式
ansible "~(web|db).*\.sers\.com" -m ping

 

ansible命令执行过程

  1. 加载自己的配置文件 默认 /etc/ansible/ansible.cfg
  2. 加载自己对应的模块文件,如 command
  3. 通过ansible 将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器的对应执行用户 $HOME/.ansible/tmp/anaible-tmp-数字/xxxx.py 文件
  4. 给文件 +x 执行权限
  5. 执行并返回结果
  6. 删除临时py文件,sleep 0 退出。

执行状态

  1. 绿色:执行成功并且不需要做改变的操作
  2. 黄色:执行成功并且对目标主机做变更
  3. 红色:执行失败
$ vi /etc/ansible/ansible.cfg
# 可以自定义输出颜色
[colors]
#highlight = white
#verbose = blue
#warn = bright purple
#error = red
#debug = dark gray
#deprecate = purple
#skip = cyan
#unreachable = red
#ok = green
changed = yellow
#diff_add = green
#diff_remove = red
#diff_lines = cyan

 

ansible常见模块

command

command:
在远程主机执行命令,默认模块可忽略-m选项
$ ansible all -m command -a "ls"
$ ansible all -m command -a "echo aaa > /root/aaac.txt"
此命令不支持$VARNAME < > | ; & 等参数。需要使用shell模块实现。
$ ansible all -m command -a "removes=/data mkdir /data" # 存在就执行后面的命令
$ ansible all -m command -a "creates=/data2 mkdir /data3" # 不存在就执行后面的命令
$ ansible all -m command -a "chdir=/tmp ls" # 切换目录执行后面的命令
# getent 从管理数据库中获取条目。
$ getent passwd nan
nan:x:1000:1000:v_nanruosen:/home/nan:/bin/bash
支持的数据库:
ahosts ahostsv4 ahostsv6 aliases ethers group gshadow hosts initgroups
netgroup networks passwd protocols rpc services shadow

shell

shell: 和command相似,用shell执行命令
$ ansible all -m shell -a "echo 123456 | passwd --stdin nan1"
$ ansible all -m shell -a "echo aaa > /data/aaaa.txt"
$ ansible all -m shell -a "cat /data/aaaa.txt"
调用bash执行命令 类似 cat /tmp/stanley.md | awk -F'|' '{print $1,$2}' &> /etc/example.txt 这些复杂命令,即使使用shell也可能会失败
解决方法:写到脚本后,copy到远程,执行,再把需要的结果拉回执行命令的机器
ansible-doc shell # 查看模块帮助

script

script: 执行脚本
$ -a '/PATH/SCRIPT_FILE'
$ ansible all -m script -a '/root/ansible/host.sh'

copy

copy: 从服务器复制文件到客户端
# 查看帮助文档
ansible-doc -s copy
$ ansible all -m copy -a 'src=/root/1.sh dest=/tmp/2.sh owner=nan mode=600 backup=yes' # 如果目标存在,默认覆盖,此处指定先备份
$ ansible all -m copy -a "content='test content\n' dest=/tmp/3.sh" # 利用内容,直接生成目标文件
$ ansible all -m copy -a 'src=/root/ansible/config dest=/etc/selinux/config backup=yes'
192.168.0.105 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"backup_file": "/etc/selinux/config.19823.2023-04-30@17:21:21~",
"changed": true,
"checksum": "086428e2a122b0fec18cd17858f334ca65116f69",
"dest": "/etc/selinux/config",
"gid": 0,
"group": "root",
"md5sum": "8a7e44af619a4538054b458dfa31941d",
"mode": "0644",
"owner": "root",
"secontext": "system_u:object_r:selinux_config_t:s0",
"size": 542,
"src": "/root/.ansible/tmp/ansible-tmp-1682846480.1-19689-174399399761739/source",
"state": "file",
"uid": 0
}
# 拷贝的文件不一致 backup=yes 会生效,文件一致则不会进行备份。

fetch

fetch: 从客户端取文件至服务器端,copy相反,目录可先打成tar包
ansible all -m fetch -a 'src=/var/log/messages dest=/4data'
ansible-doc -s fetch
$ tree /4data/
/4data/
├── 192.168.8.135
│   └── var
│   └── log
│   └── messages
└── 192.168.8.136
└── var
└── log
└── messages

archive

打包

unarchive

解压包

file

file: 设置文件属性
$ ansible-doc file
$ ansible all -m file -a 'path=/tmp/aaa state=directory owner=nan group=nan mode=0644' # 创建目录
$ ansible all -m file -a 'path=/tmp/file1 state=touch' # 创建文件
$ ansible all -m file -a 'src=/etc/fstab dest=/data/fstab.link state=link' # 创建软连接文件
$ ansible all -m file -a 'path=/tmp/aaa state=absent' # 删除使用absent

 

本文作者:南哈哈

本文链接:https://www.cnblogs.com/nanruosen/p/17263432.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   南哈哈  阅读(222)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起