1.安装ansible eple源
cat <<eof>>/etc/yum.repos.d/my.repo [epel] name=epel baseurl=http://mirrors.aliyun.com/epel/7Server/x86_64/ enable=1 gpgcheck=0 eof
yum -y install ansible 安装
2.安装ansible 常用帮助
ansible-doc -h #列出相关榜示 [root@4cd65df9495a /]# ansible-doc -l | grep yum#用于列出某个模块 [root@4cd65df9495a /]# ansible-doc -s yum #获取参数 -C #不对远程主机做出一些改变,而是预测某些可能发生的改变 -f #指定并行处理的进程数量,默认为5个 --list-hosts#不会执行任何操作,而是列出匹配到的主机列表 -m#指定要执行的模块名,默认的模块为"command" -k #密码 --syntax-check #检查语法
3.andible.cfg配置参数
Ansible有很多配置参数,以下是几个默认的配置参数:
inventory = /etc/ansible/hosts#inventory的位子 library = /usr/share/my_modules/#模块的目录 forks = 5 sudo_user = root remote_port = 22 host_key_checking = False#设置是否检查SSH主机的密钥 timeout = 20#设置SSH连接的超时间隔,单位是秒 log_path = /var/log/ansible.log
4.设置互信任配置
略
5.inventory 用于定义ansible要管理的主机
cat -n /etc/ansible/hosts 192.168.100.59:22 192.168.100.60 ansible_ssh_pass='123456' ansible_ssh_port=22 [nginx]#分组 192.168.100.5[7:9] [nginx:vars]#vars主机变量 ansible_ssh_pass='123456' [webservers:children]#创建webservers组里面包含nginx组 nginx ansible_ssh_user: ssh登录的用户名。默认为root。 ansible_ssh_pass: ssh登录远程用户时的认证密码。 ansible_ssh_private_key_file: ssh登录远程用户时的认证私钥。(?)
6.ansible 常用模块总结
command和shell
默认ansible使用的模块是command,即可以执行一些shell命令。shell和command的用法基本一样
command不能解析变量(如$HOME)和某些操作符("<", ">", "|", ";"以及"&")
ansible-doc -s shell - name: Execute commands in nodes. action: shell chdir # 在执行命令前,先cd到指定的目录下 creates # 用于判断命令是否要执行。如果指定的文件(可以使用通配符)存在,则不执行。 removes # 用于判断命令是否要执行。如果指定的文件(可以使用通配符)不存在,则不执行。
案例
ansible db -m shell -a "echo '123456' | passwd --stdin alex"#设置alex密码 ansible db -m shell -a "creates=/tmp pwd"#tmp存在所以跳过 ansible db -m shell -a "creates=/tmp2 pwd"#tmp不存在执行 ansible db -m shell -a "removes=/tmp2 pwd"#不存在 不会执行 ansible db -m shell -a "removes=/tmp pwd"#存在执行