1.什么是playbook及playbook的组成
vim test.yml
- name: test playbook
hosts: all
tasks:
- name: show messages
debug:
msg: hello westos- name: user
user:
name: linux
state: absent
ansible-playbook test.yml
为了书写方便,我们可以编辑vim设定技巧
vim ~/.vimrc
autocmd FileType yaml setlocal ai ts = 2 sw = 2 et
setlocal | 设定当前文件 |
ai | 自动退格对齐 auto indent |
ts | tab建长度为2空格 tabstop=2 |
sw | 缩进长度为2 shiftwidth=2 |
et | 把tab键变成空格 expandtab |
name | 可选,建议使用多用于说明 |
hosts | 受控主机列表 |
tasks |
任务
#
用与选择执行部分代码
|
2.playbook创建用户
在受控主机中创建一个用户 名字为westosuser id为6666,组为6666,附加组为21,密码为westos
vim user.yaml
- name: create user
hosts: all
tasks:
- name: create group
group:
gid: 6666
name: westosuser
state: present- name: create user
user:
name: westosuser
uid: 6666
group: 6666
groups: 21
password: "{{ westos | password_hash('sha512') }}"
ansible-playbook user.yaml -e westos=westos
3.列表和字典
例如:刚才的练习可以写为
vim user1.yaml
- name: create user
hosts: all
tasks:
- group: gid=6666 name=westosuser state=present- user: name=westosuser uid=6666 group=6666 groups=21 password="{{ westos | password_hash('sha512') }}"
4.playbook的组成及命令常用参数
ansible - playbook xxx.yml ...
--check|-C | 检测 |
--syntax-check | check language |
--list-hosts | 列出hosts |
--list-tags | 列出tag |
--list-tasks | 列出task |
--limit | 指定执行主机 |
-v -vv | 现实过程 |
ansible-playbook test.yml --check
5.playbook小项目实践之部署ftp服务
给受控主机安装ftp并且使之可以连接
vim vsftpd.yaml
- name: set ftp server
hosts: all
tasks:
- name: install vsftpd
dnf:
name: vsftpd
state: present- name: start vsftpd
service:
name: vsftpd
state: started
enabled: yes- name: config vsftpd.conf
lineinfile:
path: /etc/vsftpd/vsftpd.conf
regexp: "anonymous_enable=NO"
line: "anonymous_enable=YES"- name: restart vsftpd
service:
name: vsftpd
state: restarted- name: config firewalld
firewalld:
service: ftp
state: enabled
permanent: yes
immediate: yes
6.playbook实验小项目之部署apache
安装apache并且在默认发布页面显示www.westos.org
vim apache.yaml
- name: set apache server
hosts: all
tasks:
- name: install apache
dnf:
name: httpd
state: present- name: start apache
service:
name: httpd
state: started
enabled: yes- name: create index.html
copy:
dest: /var/www/html/inndex.html
content: "www.westos.org"- name: config firewalld
firewalld:
service: http
state: enabled
permanent: yes
immediate: yes
7.playbook中的tags
tags设定标签
列出所有标签
ansible-playbook apache.yaml --list-tags
运行指定标签
ansible-playbook apache.yaml --tags="install_apache,create_index.html"
跳过指定标签
ansible-playbook apache.yaml --skip-tags="install_apache,create_index.html"