文章目录
一、注册变量
register 把模块输出注册到指定字符串中,如下所示:
---
- name: test register
hosts: 172.25.0.254
tasks:
- name: hostname command
shell:
hostname
register: info
- name: show messages
shell:
echo "{{info['stdout']}}"
二、事实变量
事实变量是ansible在受控主机中自动检测出的变量
事实变量中还有与主机相关的信息
当需要使用主机相关信息时不需要采集赋值,直接调用即可
因为变量信息为系统信息所以不能随意设定仅为采集信息,故被成为事实变量
---
- name: test register
hosts: 172.25.0.254
tasks:
- name: show messages
debug:
msg: "{{ansible_facts['architecture']}}"
三、魔术变量
这些变量不能由用户直接设置;Ansible 将始终覆盖它们以反映内部状态。
hostvars: %ansible软件的内部信息
group_names: %当前受管主机所在组
groups: %列出清单中所有的组和主机
inventory_hostname: %包含清单中配置的当前授管主机的名称
四、触发器
notify: 触发器当遇到更改时触发handlers
handlers: 触发器触发后执行的动作
五、处理失败任务
1.ignore_errors
作用:
当play遇到任务失败是会终止
ignore_errors: yes 将会忽略任务失败使下面的任务继续运行
实例:
- name: test
dnf:
name: westos
state: latest
ignore_errors: yes
- name: create file
file:
path: /mnt/westos
state: touch
2.force_handlers
作用:
当任务失败后play被终止也会调用触发器进程
example:
---
- name: apache change port
hosts: 172.25.0.254
force_handlers: yes
vars:
http_port: 80
tasks:
- name: configure apache conf file
lineinfile:
path: /etc/httpd/conf/httpd.conf
regexp: "^Listen"
line: "Listen {{ http_port }}"
notify: restart apache
- name: install error
dnf:
name: westos
state: latest
handlers:
- name: restart apache
service:
name: httpd
state: restarted
enabled: yes
3.changed_when
作用:
控制任务在何时报告它已进行更改
---
- name: apache change port
hosts: 172.25.0.254
force_handlers: yes
vars:
http_port: 8080
tasks:
- name: configure apache conf file
lineinfile:
path: /etc/httpd/conf/httpd.conf
regexp: "^Listen"
line: "Listen {{ http_port }}"
changed_when: true
notify: restart apache
handlers:
- name: restart apache
service:
name: httpd
state: restarted
enabled: yes
4.failed_when
当符合条件时强制任务失败
---
- name: test
hosts: 172.25.0.254
tasks:
- name: shell
shell: echo hello
register: westos
failed_when: "'hello' in westos.stdout"
六、block
block块实际上是对task任务的分组
block: %定义要运行的任务
rescue: %定义当block句子中出现失败任务后运行的任务
always: %定义最终独立运行的任务
举例如下:
---
- hosts: webserver
tasks:
- name: deploy apache
block:
- name: install httpd
dnf:
name: httpd
state: present
- name: create index.html
copy:
content: "{{ ansible_hostname }}\n"
dest: /var/www/html/index.html
- name: config httpd
template:
src: httpd.conf.j2
dest: /etc/httpd/conf/httpd.conf
notify: restart httpd
- name: start httpd
service:
name: httpd
state: started
enabled: yes
- name: accept httpd
firewalld:
service: http
permanent: yes
immediate: yes
state: enabled
- name: accept 8080
firewalld:
port: 8080/tcp
permanent: yes
immediate: yes
state: enabled
when: ansible_default_ipv4.address in groups['webserver'] %其中书写方式要根据ansible版本来定
查看ansible版本:
[root@test2 ansible]# rpm -q ansible
ansible-2.9.16-1.el8.noarch
查看ansible中ip相关书写格式问题:
ansible test -m setup | less %其中test是hosts文件中所写的一个组