有没有一种方法可以对ansible主机文件中的组进行排序而不对组内的主机进行排序?

时间:2019-05-08 06:05:01

标签: python linux bash ansible

在一个无障碍主机(或清单)文件中,您可以使用方括号将主机分组。我想使用linux中的sort函数对这些组进行排序,但是它将对各个主机进行排序,并且我希望正确的主机仍在正确的组中。例如,

[webservers]
examplehostserver
hostname3

[database]
db_server_1
local_db_server

[ExampleGroup]
Server05
Myserver01

我正在寻找一种按组排序的方法,同时将主机保持在正确的组下

我感觉这在终端命令或bash中是不可能的

2 个答案:

答案 0 :(得分:0)

简单的bash脚本

#!/bin/bash
hosts_file=$1
sections=$(cat $hosts_file | grep "\[" | tr -d "[]" | sort)
for i in $sections; do
    sed -n -e "/\[$i\]/,/\[/p" $hosts_file | sed '${/\[.*/d}'
done

有larsks输入的

[database]
db_server_1
local_db_server

[ExampleGroup]
Server05
Myserver01

[webservers]
examplehostserver ansible_host=10.0.0.1
hostname3

[webservers:vars]
apache_package_name=httpd

Native Ansible解决方案仅限于组和主机。下面的游戏带有问题中的示例广告资源

tasks:
  - debug:
      msg: "{{ item }}:{{ groups[item] }}"
    loop: "{{ groups.keys()|difference(['all', 'ungrouped'])|sort }}"

给予(节略):

"msg": "database:[u'db_server_1', u'local_db_server']"
"msg": "ExampleGroup:[u'Server05', u'Myserver01']"
"msg": "webservers:[u'examplehostserver', u'hostname3']"

blockinfile

的相同循环
tasks:
  - blockinfile:
      create: yes
      path: "{{ playbook_dir }}/my_hosts"
      block: |
             [{{ item }}]
             {% for host in groups[item] %}
             {{ host }}
             {% endfor %}
      marker: "# {mark} group:{{ item }}"
    loop: "{{ groups.keys()|difference(['all', 'ungrouped'])|sort }}"

创建文件:

> cat my_hosts
# BEGIN group:database
[database]
db_server_1
local_db_server
# END group:database
# BEGIN group:ExampleGroup
[ExampleGroup]
Server05
Myserver01
# END group:ExampleGroup
# BEGIN group:webservers
[webservers]
examplehostserver
hostname3
# END group:webservers

从包含变量声明的Ansible变量重建库存不会是明确的。

答案 1 :(得分:0)

您可以使用简单的Python脚本来做到这一点:

#!/usr/bin/python

import sys


groups = {}
group = None
for line in sys.stdin:
    line = line.rstrip()

    if line.startswith('['):          # look for inventory groups
        group = line[1:-1].lower()    # extract the group name
        groups[group] = []

    if group and line:                # gather up non-blank lines
        groups[group].append(line)

for group in sorted(groups):          # sort groups by name
    print('\n'.join(groups[group]))   # print out the group
    print()

假设我们在文件hosts中有您的示例清单,并且在sortinv.py中有以上脚本,则以下命令:

python sortinv.py < hosts

产生:

[database]
db_server_1
local_db_server

[ExampleGroup]
Server05
Myserver01

[webservers]
examplehostserver
hostname3

此机制的优点是它将保留主机变量和组变量之类的内容。例如,输入以下内容:

[webservers]
examplehostserver ansible_host=10.0.0.1
hostname3

[database]
db_server_1
local_db_server

[ExampleGroup]
Server05
Myserver01

[webservers:vars]
apache_package_name=httpd

我们得到:

[database]
db_server_1
local_db_server

[ExampleGroup]
Server05
Myserver01

[webservers]
examplehostserver ansible_host=10.0.0.1
hostname3

[webservers:vars]
apache_package_name=httpd

弗拉基米尔的解决方案会丢失很多其他数据。