首页 > 解决方案 > 如何使用 bash 将我的 shell 模块命令转换为我自己的模块?

问题描述

这是我的 yml 文件:

- hosts: webservers
  vars:
    www_port: 80
  become: yes
  tasks:
   - name: install lsof if it's redhat
     yum:
       name: lsof
       state: latest
     when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux'
   - name: install lsof if  it's debian
     apt:
       name: lsof
       state: latest
     when: ansible_distribution == 'Ubuntu' or ansible_distribution == 'Debian'

   - name: Finding out what web server it uses
     shell: "lsof -i :{{ www_port }} | grep LISTEN | cut -d ' ' -f 1"
     register: result
   - name: output the result of what web server it uses
     debug: msg="{{ result.stdout_lines|first }}"

   - name: list all vhosts if it uses httpd
     shell: cd /etc/httpd/sites-enabled; ls | while read file; do awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++)$
     register: rezult
     when: result.stdout_lines|first == "httpd"
   - name: output vhosts rezult if it uses httpd
     debug: msg="{{ rezult.stdout_lines }}"
     when: result.stdout_lines|first == "httpd"

   - name: list all vhosts if it uses nginx
     shell: cd /etc/nginx/sites-enabled; ls | while read file; do awk '/^server_name/ {f=1} f {for(i=1;i<=NF;i++$
     register: recult
     when: result.stdout_lines|first == "nginx"
   - name: output vhosts recult (results) if it uses nginx
     debug: msg="{{ recult.stdout_lines }}"
     when: result.stdout_lines|first == "nginx"

我想使用 bash 脚本将这些“shell:”模块命令转换为我自己的模块,因为我不知道 python。本质上,这个剧本输出主机使用的网络服务器的名称,并输出网络服务器配置文件中的所有虚拟主机。我想将这些 shell: module 命令组合成一个模块来完成所有这些事情。

ansible.cfg 文件指出我自己的模块库位于 /usr/share/my_modules 中,因此我创建了该目录并创建了一个 vhosts.bash 脚本,该脚本基本上是 yml 文件中的第二个 shell 命令。我用唯一的“vhosts:”替换了该行(“shell:....”),但这没有用。这是 /usr/share/my_modules 中的 vhosts.bash 文件

#!/bin/bash
cd /etc/httpd/sites-enabled;
ls | while read file;
do awk '/^ServerName/ {f=1} f {for(i=1;i<=NF;i++) if ($i~/\./) print $i; else if($i!="ServerName") exit}' $file;
done;

当我运行剧本时,我得到:

  - name: list all vhosts if it uses httpd
     ^ here

但它与名称无关,这是 yml 中的行:

- name: list all vhosts if it uses httpd
     vhosts:
     register: rezult

我不知道我是否完全错过了重点,但这就是这个人在这段视频中的表现:https ://www.youtube.com/watch?time_continue=1&v=aY7lmtW8ROM

标签: bashshellmoduleansible

解决方案


不确定您的缩进是否正确,名称后的行应如下所示:

- name: list all vhosts if it uses httpd vhosts:


推荐阅读