Ansible常见特殊模块用法记录
Ansible常见特殊模块用法记录
1、delegate_to:将某一个任务委托给指定主机
- name: "get inventory_hostname"
shell: echo {{ inventory_hostname }} $HOSTNAME >>/tmp/test.txt
delegate_to: "172.18.1.100"
2、connection: local:在本地服务器上运行命令,而不是SSH,可以针对playbook全局使用
- name: "get inventory_hostname"
# inventory_hostname为ansible内置变量获取清单中的主机名
shell: echo {{ inventory_hostname }} $HOSTNAME >>/tmp/test.txt
connection: local
3、run_once:当前host group中第一个可用host上执行task,可以和delegate_to结合使用
- name: "hello world"
shell: /bin/sh /root/hello_world.sh
run_once: true
delegate_to: "172.18.1.100"
4、ignore_errors:任务失败继续完成剩余的任务
- name: "Delete logs"
shell: rm -f /var/log/nginx/errors.log
ignore_errors: true
5、register:保留中间结果,常用于debug
- name: "get host port info"
shell: netstat -lntp
register: host_port
- name: "print host port"
debug: msg: "{{ host_port['stdout_lines'] }}"
6、until:重试任务直到满足条件
- name: "wait kube-apiserver up"
shell: "systemctl status kube-apiserver.service |grep Active"
register: api_status
until: '"running" in api_status.stdout'
# 间隔3秒,重试10次
retries: 10
delay: 3
tags: upgrade_k8s, restart_master
---
- name: "wait consul service up"
uri:
url: "http://172.18.1.100:8500/ui/"
method: GET
register: consul_status
until: consul_status.status == 200
retries: 30
delay: 6
7、when:只在符合when条件的host上执行task
- import_tasks: centos.yml
when: 'ansible_distribution in ["CentOS","RedHat","Amazon","Aliyun"]'
8、handlers、notify:触发器
- hosts: all
tasks:
- name: "install apache"
yum: name=httpd state=installed
- name: "install configure file for httpd"
copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
notify:
- restart httpd
- check httpd
- name: "start httpd service"
service: enabled=true name=httpd state=started
handlers:
- name: "restart httpd"
service: name=httpd state=restart
- name: "check httpd"
shell: netstat -ntulp |grep 80
9、fail、failed_when、changed_when:中断/改变playbook执行状态
- hosts: all
tasks:
- shell: echo '---error'
register: return_value
- fail:
msg: 'running fail'
when: "'error' in return_value.stdout"
- debug:
msg: 'I never execute, Because the playbook has stopped'
---
- hosts: all
tasks:
- debug:
msg: "I execute normally"
- shell: "echo 'This is a string for testing error'"
register: return_value
failed_when: ' "error" in return_value.stdout'
- debug:
msg: "I never execute,Because the playbook has stopped"
---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "test message"
# 可以结合触发器使用
changed_when: true
10、set_fact:自定义fact变量,可以跨playbook使用
- hosts: all
tasks:
- name: "set_fact"
set_fact:
test_fact_1: "{{ ansible_all_ipv6_addresses }}"
test_fact_2: "{{ ansible_memtotal_mb * 2}}"
- name: "debug message"
debug:
msg:
- '{{ test_fact_1 }}'
- '{{ ansible_memtotal_mb }}'
- '{{ test_fact_2 }}'
- "{{ vars_1 * 2}}"
---
- hosts: all
tasks:
- name: "info message"
debug:
msg:
- "{{ test_fact_2 }}"
作者:wanghongwei
版权声明:本作品遵循<CC BY-NC-ND 4.0>版权协议,商业转载请联系作者获得授权,非商业转载请附上原文出处链接及本声明。