Ⅰ. Ansible配置
# mkdir /etc/ansible # touch /etc/ansible/hosts # cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.137.6 client 192.168.137.5 server 192.168.137.7 web1 192.168.137.8 web2 # cat /etc/ansible/hosts [local] server client [web] web1 web2
我这里就添加了两个主机组:local、web,每个主机组两台主机。
这里你可以把同一类主机或者是想统一管理的主机放在一个主机组里。
Ⅱ. Ansible命令
1> 执行第一条ansible命令
# ansible local -m ping #使用ping模块 server | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n", } client | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n", }
由于ansible是基于ssh,这里我们先要配置公钥。
# ssh-keygen -t rsa # ssh-copy-id -i [email protected]192.168.137.6 #为ansible管理的主机安装server的公钥
再次运行上一条命令:
# ansible local -m ping server | SUCCESS => { "changed": false, "ping": "pong" } client | SUCCESS => { "changed": false, "ping": "pong" }
2> 其他命令简介
查看local组主机内存使用情况:
# ansible local -a "free -m" server | SUCCESS | rc=0 >> total used free shared buff/cache available Mem: 1496 540 325 10 630 751 Swap: 2047 0 2047 client | SUCCESS | rc=0 >> total used free shared buff/cache available Mem: 1496 453 91 6 951 844 Swap: 2047 3 2044
若要执行带有管道的命令,可使用shell模块:
# ansible local -m shell -a "df -h | grep /home" server | SUCCESS | rc=0 >> /dev/mapper/cl-home 16G 187M 16G 2% /home client | SUCCESS | rc=0 >> /dev/mapper/cl-home 16G 187M 16G 2% /home
限定命令只在一台client主机生效:
# ansible -a "df -h" --limit "client"
其他ansible参数可使用ansible -h查看。
3> 常用模块命令举例
①file模块
创建文件符链接:
# ansible local -m file -a "src=/etc/resolv.conf dest=/tmp/resolv.conf state=link"
更改文件权限为755,属组为root:root:
ansible local -m file -a "dest=/tmp/resolv.conf mode=755 owner=root group=root"
②service模块
启动NTP服务:
# ansible local -m service -a "name=ntpd state=started enabled=yes"
③copy模块
将本地文件拷贝到远程服务器:
# ansible local -m copy -a "src=/etc/ansible/ansible.cfg dest=/tmp/ansible.cfg owner=root group=root mode=0644"
更多模块请参考命令ansible-doc -l
模块官网http://docs.ansible.com/ansible/latest/list_of_all_modules.html
时间: 2024-10-06 22:10:58