# 使用 pip(python的包管理模块)安装
首先,我们需要安装一个python-pip包,安装完成以后,则直接使用pip命令来安装我们的包
yum install python-pip
pip install ansible
# 使用 yum 安装
yum install epel-release -y
yum install ansible - y
# 安装目录如下(yum安装):
配置文件目录:/etc/ansible/
执行文件目录:/usr/bin/
Lib库依赖目录:/usr/lib/pythonX.X/site-packages/ansible/
Help文档目录:/usr/share/doc/ansible-X.X.X/
Man文档目录:/usr/share/man/man1/
# 配置文件
/etc/ansible/ansible.cfg #主配置文件
/etc/ansible/hosts #主机清单
/etc/ansible/roles/ #存放角色目录
# 主配置文件
vim /etc/ansible/ansible.cfg
inventory = /etc/ansible/hosts #存放主机清单文件
forks = 5 #并发执行数量
poll_interval = 15 #回频率或轮询间隔时间,单位s
sudo_user = root #远程主机sudo到什么用户,默认为root
ask_sudo_pass = True #sudo时是否需要输入密码
ask_pass = True #执行ansible-playbook是否需要密码.默认为no
transport = smart
remote_port = 22 #远程主机端口号
module_lang = C #模块和系统之间通信的语言
module_set_locale = False
roles_path = /etc/ansible/roles #默认下载的Roles存放的目录
host_key_checking = False #首次连接是否需要检查key认证。设置为False,第一次连接远程主机不需要输入yes
timeout = 10 #SSH超时时间
remote_user = root #使用/usr/bin/ansible-playbook链接的默认用户名,默认使用当前用户名称
log_path = /var/log/ansible.log #日志文件存放路径
executable = /bin/sh #执行的shell环境,用户shell模块
jinja2_extensions = jinja2.ext.do,jinja2.ext.i18 #允许开启jinja2扩展模块
private_key_file = /path/to/file #私钥文件存储位置
system_warnings = True #禁用系统运行Ansible潜在问题警告
deprecation_warnings = True #PlayBook输出禁用“不建议使用”警告
nocolor = 1 #输出带上颜色区别,0表示开启,1表示关闭
pipelining = False #是否开启pipe SSH通道优化
host_key_checking = False #配置ssh免密时不提示yes/no
gathering = explicit #不收集系统信息,默认收集
[privilege_escalation]
become=True #是否sudo
become_method=sudo #sudo方式
become_user=root #sudo后变为root用户
become_ask_pass=False #sudo后不验证密码
# 主机清单
vim /etc/ansible/hosts
[tencent]
42.192.248.144
47.114.180.11
[ali]
119.45.145.201
# 远程主机免密登录
以root用户登录到主控端机器,ssh-keygen生成密钥对,通过ssh-copy-id 远程主机,将公钥拷贝到远程主机以root用户登录到主控端机器,ssh-keygen生成密钥对,通过ssh-copy-id 远程主机,将公钥拷贝到远程主机
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
#####批量推送#######
批量推送公钥到远程机器
将以下文件命名为:push.ssh.ymal
- hosts: tencent
user: root
tasks:
- name: ssh-copy
authorized_key: user=root key="{ { lookup('file', '/root/.ssh/id_rsa.pub') }}"
tags:
- sshkey
# 执行推送命令
ansible-playbook push.ssh.ymal
#####模块命令使用#########
ping模块:
ansible 主机ip/组 -m ping
command模块和shell模块
说明:用于在各受控端节点运行指定的命令,shell和command的区别:shell模块可以特殊字符,而command是不支持。ansible不支持命令别名,如ls -l不能简写成ll。
ansible -i /etc/ansible/hosts tencent -m command -a 'hostname'
ansible -i /etc/ansible/hosts tencent -m shell -a 'hostname && date'