这个 ansible 脚本有效。
---
- name: Create Swap
hosts: serverName
gather_facts: yes
become: true
become_user: root
become_method: sudo
tasks:
- name: Create swap
shell:
'dd if=/dev/zero of=/tmp/swapfile bs=1024 count=563200 && mkswap /tmp/swapfile && swapon /tmp/swapfile && swapon -s'
when:
ansible_facts['memory_mb']['swap']['total'] == 0
notify: Disable swap
- name: Collect selected facts
setup:
handlers:
- name: Disable swap
shell:
'swapoff /tmp/swapfile && rm -rf /tmp/swapfile'
when:
ansible_facts['memory_mb']['swap']['total'] > 500
但是当我在多个单元中破坏脚本时。
tree
.
├── main.yml
├── roles
│ └── swap_creater_560mb.yml
main.yml ==>
---
- name: Create Swap
hosts: serverName
gather_facts: yes
become: true
become_user: root
become_method: sudo
tasks:
- name: Create swap
include_tasks: roles/swap_creater_560mb.yml
并且 swap_creater_560mb.yml ==>
---
- name: Create swap
shell:
'dd if=/dev/zero of=/tmp/swapfile bs=1024 count=563200 && mkswap /tmp/swapfile && swapon /tmp/swapfile && swapon -s'
when:
ansible_facts['memory_mb']['swap']['total'] == 0
notify: Disable swap
- name: Collect selected facts
setup:
handlers:
- name: Disable swap
shell:
'swapoff /tmp/swapfile && rm -rf /tmp/swapfile'
when:
ansible_facts['memory_mb']['swap']['total'] > 500
每当我创建交换时,我都想通知处理程序禁用交换。但是当我包括任务:角色/swap_creater_560mb.yml 我收到以下错误。
任务 [创建交换] *****************************************************************************************************************致命:[服务器名称]:失败! => {“原因”:“我们无法读取 JSON 或 YAML,这些是我们从每个中获得的错误:\nJSON:无法解码 JSON 对象\n\n加载 YAML 时出现语法错误。\n未找到预期\n\n错误似乎在'/home/USER/testing_scripts/swap_creator/roles/swap_creater_560mb.yml':第 15 行,第 3 列,但可能\n在文件的其他位置,具体取决于确切的语法问题。\n\n有问题的行似乎是:\n\n\n处理程序:\n ^ 这里\n“}
有人能帮助我或告诉我我做错了什么吗?我是 ansible 新手,我可能会遗漏一些东西。
答案1
handlers
只能在剧本中设置(或handlers
角色目录中)。无法在随附的任务列表中设置include_tasks
。如果您想将这些任务和处理程序分解到单独的文件中,请创建一个实际的 ansible 角色。
布局如下:
main.yml
roles/
swap_creater_560mb/
tasks/
main.yml
handlers/
main.yml
其中tasks/main.yml
有:
- name: Create swap
shell:
'dd if=/dev/zero of=/tmp/swapfile bs=1024 count=563200 && mkswap /tmp/swapfile && swapon /tmp/swapfile && swapon -s'
when:
ansible_facts['memory_mb']['swap']['total'] == 0
notify: Disable swap
- name: Collect selected facts
setup:
并且handlers/main.yml
有:
- name: Disable swap
shell:
'swapoff /tmp/swapfile && rm -rf /tmp/swapfile'
when:
ansible_facts['memory_mb']['swap']['total'] > 500
然后在你的主剧本中:
- name: Create Swap
hosts: serverName
gather_facts: yes
become: true
become_user: root
become_method: sudo
tasks:
- name: Create swap
include_role:
name: swap_creater_560mb
答案2
您可以将处理程序保存在同一个文件中,并且仅包含任务
---
- name: Create Swap
hosts: serverName
gather_facts: yes
become: true
become_user: root
become_method: sudo
tasks:
- name: Create swap
include_tasks: roles/swap_creater_560mb.yml
handlers:
- name: Disable swap
shell:
'swapoff /tmp/swapfile && rm -rf /tmp/swapfile'
when:
ansible_facts['memory_mb']['swap']['total'] > 500