首页 > 解决方案 > Ansible:遍历捕获的命令输出

问题描述

我正在尝试将现有的 Perl 脚本转换为 Ansible 角色。我在迭代捕获的命令输出时遇到了麻烦。

这是 Perl 脚本:

# Description: This script will adjust the oom score of all the important system processes to a negative value so that OOM killer does not touch these processes ############


chomp(my $OS = `uname`);

if($OS eq "Linux")
{
  my @file = `ps -ef|egrep 'sssd|wdmd|portreserve|autofs|automount|ypbind|rpcbind|rpc.statd|rpc.mountd|rpc.idampd|ntpd|lmgrd|Xvnc|vncconfig|irqblance|rpc.rquotad|metric|nscd|crond|snpslmd|getpwname.pl|mysqld|rsyslogd|xinetd|sendmail|lsf|tigervnc|tightvnc|cfadm' |egrep -ve 'ps|egrep' |awk '{print \$8,\$2}'`;
  chomp(@file);

  foreach my $element (@file)
  {
    chomp($element);
    (my $process, my $pid) = (split(/\s/,$element))[0,1];
    print "($process)($pid)\n";
    system("echo -17 > /proc/$pid/oom_adj");
    system("cat /proc/$pid/oom_adj");
  }
}

else
{
  print "The host is a $OS system, so no action taken\n";
}

这是我迄今为止在 Ansible 中尝试过的:

---
  - name: Capture uname ouput
    shell: "uname"
    register: os_type

  - name: Adjust OOM to negative so that OOM killer does not kill below processes
    shell: 'ps -ef|egrep "sssd|wdmd|portreserve|autofs|automount|ypbind|rpcbind|rpc.statd|rpc.mountd|rpc.idampd|ntpd|lmgrd|Xvnc|vncconfig|irqblance|rpc.rquotad|metric|nscd|crond|snpslmd|getpwname.pl|mysqld|rsyslogd|xinetd|sendmail|lsf|tigervnc|tightvnc|cfadm" |egrep -ve "ps|egrep" |awk "{print \$8,\$2}"'
    register: oom
    when: os_type.stdout == 'Linux'

  - debug:  var=oom.stdout_lines

现在,我想遍历 var 并在 Ansible 中实现这部分:

foreach my $element (@file)
  {
    chomp($element);
    (my $process, my $pid) = (split(/\s/,$element))[0,1];
    print "($process)($pid)\n";
    system("echo -17 > /proc/$pid/oom_adj");
    system("cat /proc/$pid/oom_adj");
  }

请帮忙。

标签: perlansible

解决方案


我在下面尝试过,但没有运气,我做错了什么?任何人都是正确的方向

- hosts: temp
  gather_facts: yes
  become: yes
  remote_user: root
  tasks:
   - name: Capture uname ouput
     shell: "uname"
     register: os_type
   - name: Adjust OOM to negative so that OOM killer does not kill below processes
     shell: 'ps -ef|egrep "sssd|wdmd|portreserve|autofs|automount|ypbind|rpcbind|rpc.statd|rpc.mountd|rpc.idampd|ntpd|lmgrd|Xvnc|vncconfig|irqblance|rpc.rquotad|metric|nscd|crond|snpslmd|getpwname.pl|mysqld|rsyslogd|xinetd|sendmail|lsf|tigervnc|tightvnc|cfadm" |egrep -ve "ps|egrep" |awk "{print \$2}"'
     register: oom
     when: os_type.stdout == 'Linux'
   - debug:  var=oom.stdout
   - name: update the pid 
     raw: echo -17 > /proc/{{ item.pid }}/oom_adj
     with_items:
       - "{{ var=oom.stdout }}"

推荐阅读