palybook 使用
##### 定义 / etc/ansible/hosts
两种方式:
基于 SSH 密码登录
不配置免密码登录, 需要在 hosts 文件中配置
第一种: 基于 SSH 密码登录
参数一: inventory
ansible 的主要功能用于批量管理主机操作, 便捷的使用部分主机, 可以在 inventory file 中分组
默认的 inventory file 为 / etc/ansible/hosts
1.inventory 文件格式
同一主机归并到一个或者多个组中, 主机使用非默认的 22 端口, 也可以在主机名称后加冒号端口标明
- www.ab.com
- [webservers]
- www.abc.com:222
- www.abcd.com
- [dbservers]
- db1.abc.com
- db2.abc.com
- db3.abc.com
如果主机遵循相似的命名模式, 可以使用列表标记各个主机
- [webserver]
- www[01:30].example.com
- [dbserver]
- db-[a:f].example.com
2. 主机变量
可以在定义主机时添加远程主机变量便于在 playbook 中使用 {http 中的变量, 在 j2 中配置}
- [webserver]
- www.ab.com http_port=80 maxRequestsPerChild=808
- www.abc.com http_port=8080 maxRequestsPerChild=909
3. 组变量
赋予指定组内的所有主机在 playbook 中用的变量 (vars)
可以调用组里面的变量.
- [webserver]
- www.ab.com
- www.bc.com
- [webserver:vars]
- host_port=80
- maxRequestsPerChild=890
4. 组嵌套
组还包括其他组, 可以在其他组中指定变量, 只能在 ansible-playbook 中使用, ansible 不支持
children 中包括 apache,nginx 的主机., 共四台主机
- [apache]
- http1.abc.com
- http2.abc.com
- [nginx]
- nginx1.abc.com
- nginx2.abc.com
- [webservers:children]
- apache
- nginx
- [webservers:vars]
- host_port=80
ansible 基于 SSH 连接 inventory 可以指定远程主机, 通过参数指定交互式, 参数如下:
- ansible_ssh_host
- ansible_ssh_port
- ansible_ssh_user
- ansible_ssh_pass
- ansible_sudo_pass
- ansible_connection
- ansible_ssh_private_key_file
- ansible_shell_type
- ansible_python_interpreter
第二种: 不基于 SSH 免密码登录
即便是我们没有做关于秘钥的认证, 我们也会自动使用账户和密码来登录该主机.
- [webservers]
- 192.168.133.2 ansible_ssh_user=root ansible_ssh_pass=123456
- 192.168.133.3 testvar="2.100
- #### 基本结构
module_name: module_args 模块名和模块参数
- - host: webserver
- remote_user:
- task:
- - task1
- module_name: module_args
- - name: test connection
- ping:
- remote_user; www
- sudo: yes
- command: /sbin/setenforce 0
- shell: /usr/bin/somecommand || /bin/true
- ignore_errors: True
- - task2
- module_name: module_args
- - host:dbservers
在运行 playbook 是中途发生错误, 可能会回滚, 更正后, 重新执行一次.
可以指定使用 sudo 的方式远程执行任务, 用 sudo 到 root 用户执行命令.
众多模块中, 只有 command 和 shell 模块仅使用给定一个列表而无需使用 "key=value"
命令或脚本的退出码不为 0, 可以使用如上替代, 命令不成功强行成功.
使用 ignore_errors 忽略错误信息
handlers:
在 notify 中列出的操作为 handler, 比如之前配置了 apache 的配置文件, http.conf 端口发生变化后, 重新执行 ansible-playbook 后, 查看远程的端口, 并未发生变化. 需要用到 notify
引入变量:
vars: 在后面添加变量名, 然后再引入变量, 必须加 {{}}, 用变量名替换.
- - host: webservers
- remote_user: root
- vars:
- - packages: httpd
- tasks:
- - name: install httpd packages
- yum: name={{ packages }} state=lastest
- - name: install configuration file for httpd
- copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
- notify:
- - restart httpd
- - name: start httpd service
- service: enabled=true name={{ packages }} state=started
- handlers:
- - name: restart httpd
- service: name={{ packages }} state=restarted
来源: http://www.bubuko.com/infodetail-2919748.html