前置要求
为了保证我们正常学习和测试,需要至少两台服务器。
- 一台作为控制端
- 另一台作为被控制服务器
安装
只有控制节点需要安装。被控节点不用。
yum install -y ansible
配置文件位置,只要有一个就可以
- ANSIBLE_CONFIG 环境变量
- ansible.cfg 当前文件夹
- ~/.ansible.cfg
- /etc/ansible/ansible.cfg
[defaults]
#主机列表配置文件
inventory = /home/ansible/hosts
#禁用ssh密钥检查
host_key_checking = False
#不收集远程主机信息
gathering = explicit
#gathering = smart
#启用管道
Pipelining =True
#默认并发数
forks=100
#远程主机临时py文件目录
remote_tmp=/tmp
callback_whitelist = profile_tasks
#ansible日志
log_path=/var/log/ansible/ansible.log
# 定义缓存插件的连接或路径信息
facts_caching_timeout = 86400
fact_caching = jsonfile
fact_caching_connection = /home/ansible/ansible_fact_cache
deprecation_warnings=False
[privilege_escalation]
become = True
become_user = root
become_method = sudo
become_ask_pass = False
基本使用
帮助命令
ansible -h
ansible -l
ansible-doc -s ping
mkdir -p /home/ansible/
cd /home/ansible/
创建自己的hosts文件,注意替换下面的变量:
cat > hosts << EOF
[local]
自己的ip
EOF
测试配置
ansible --list-hosts local
连接测试:
$ ansible local -m ping
我的ip | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
如果报错说明没有加密码,有两种方式加公钥和直接设置密码的方式。
免密
方式一、基于密钥对连接
#主机:
ssh-keygen
#敲三次回车
#复制给从机
ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.7
#[赋值给从机
ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.8
方式二、设置连接密码
编辑 /etc/ansible/hosts
文件
[web]
web-01 ansible_ssh_host=192.168.175.182 ansible_ssh_pass=123456
web-02 ansible_ssh_host=192.168.175.183 ansible_ssh_pass=123456
ad-hoc
按ppt指引,测试shell、file、copy、fetch、script、yum、service、setup、模块
一键安装脚本
在 /tmp
目录下新建 install.sh
文件,内容如下:
#!/bin/bash
yum install -y ansible
mkdir /etc/ansible/
cat > /etc/ansible/ansible.cfg << EOF
[defaults]
#主机列表配置文件
inventory = /home/ansible/hosts
#禁用ssh密钥检查
host_key_checking = False
#不收集远程主机信息
gathering = explicit
#gathering = smart
#启用管道
Pipelining =True
#默认并发数
forks=100
#远程主机临时py文件目录
remote_tmp=/tmp
callback_whitelist = profile_tasks
#ansible日志
log_path=/var/log/ansible/ansible.log
# 定义缓存插件的连接或路径信息
facts_caching_timeout = 86400
fact_caching = jsonfile
fact_caching_connection = /home/ansible/ansible_fact_cache
deprecation_warnings=False
[privilege_escalation]
become = True
become_user = root
become_method = sudo
become_ask_pass = False
EOF
mkdir -p /home/ansible/

公众号
扫码订阅最新深度技术文,回复【资源】获取技术大礼包
评论