Ansible 基础配置
- 主配置文件:
/etc/ansible/ansible.cfg
- ansible配置文件查找顺序
- 首先检测
ANSIBLE_CONFIG
变量定义的配置 - 其次检查当前目录下的
./ansible.cfg
文件(可以在任意目录创建ansible
目录,并参考默认ansible.cfg
文件配置ansible.cfg
文件) - 再次检查当前用户家目录下
~/ansible.cfg
文件 - 最后检查
/etc/ansible/ansible.cfg
文件
- 首先检测
Ansible 配置案例
1、在/root目录下创建ansible目录,并参考/etc/ansible/ansible.cfg配置对应的cfg文件
mkdir -p /root/ansible
cd /root/ansible
vim ansible.cfg
2、ansible.cfg 参数解析
[defaults]
inventory = ~/ansible/hosts
#forks = 5
#ask_pass = True
#remote_port = 22
#host_key_checking = False
inventory:主机清单配置文件
forks:ssh并发数量
ask_pass:使用密钥还是密码远程
host_key_checking:是否校验秘钥
3、配置 ~/ansible/hosts
[root@node01 ansible]# pwd
/root/ansible
[root@node01 ansible]# cat hosts
[master]
node01
[agent]
node02
[webserver]
node0[3:4]
[database]
node05
[cluster:children]
webserver
database
[master]
:中括号可以设置主机组,组名任意
[cluster:children]
:嵌套组,可以在主机组cluster下配置子组(PS:children是关键字)
4、如果没有配置SSH免密可以在hosts文件中进行以下配置
[root@node01 ansible]# cat hosts
[master]
node01
[agent]
node02,node03,node04
[master:vars]
ansible_ssh_user=root
ansible_ssh_pass=123456
ansible_become_pass=123456
[master:vars]:vars是关键字,给主机组master配置对应的参数
ansible_ssh_user:使用ansible mater -m ping时,配置使用的用户是root还是其他用户
ansible_ssh_pass:使用ansible master -m ping时,配置root或其他用户对应的密码
ansible_become_pass:这个参数目前不知道是什么,我配置的也是密码
Ansible 使用场景
1、查看所有主机列表
[root@node01 ansible]# ansible all --list-hosts
hosts (4):
node01
node02
node03
node04
2、测试网络连通情况
# 可以根据主机名进行测ping
[root@node01 ansible]# ansible node01 -m ping
node01 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
# 也可以根据主机组名进行测ping
[root@node01 ansible]# ansible agent -m ping
node02,node03,node04 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname node02,node03,node04: Name or service not known",
"unreachable": true
}
3、执行shell命令,查看seliux的配置
[root@node01 ansible]# ansible master -m shell -a "cat /etc/selinux/config"
node01 | CHANGED | rc=0 >>
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of three values:
# targeted - Targeted processes are protected,
# minimum - Modification of targeted policy. Only selected processes are protected.
# mls - Multi Level Security protection.
SELINUXTYPE=targeted