Python和Ansible IP范围到hostvars

问题描述 投票:0回答:1

我正在尝试将以下ip格式解析为ansible的清单文件。我正在寻找自定义python或可用的ansible解决方案。

用户输入[在某些情况下可能会长得多:]

10.9.1.1-10.9.1.12, 10.9.1.15

所需的输出:

10.9.1.1
10.9.1.2
10.9.1.3
10.9.1.4
10.9.1.5
10.9.1.6
10.9.1.7
10.9.1.8
10.9.1.9
10.9.1.10
10.9.1.11
10.9.1.12
10.9.1.15

如果ansible可以接受10.9.1.1-10.9.1.12格式的hostvars ip范围,那是理想的选择,但是似乎我需要制作一个自定义模块才能将其放入10.9.1。[ 1:12]格式,或如上所述全部打印出来。

我使用相同的格式通过用户输入进行API调用,这就是为什么我不希望用户以其他格式输入。调用API之后,我将在每个这些ip上运行脚本以安装一些软件。

进展[虽然需要更动态]:

def ipRange(start_ip, end_ip):
   start = list(map(int, start_ip.split(".")))
   end = list(map(int, end_ip.split(".")))
   temp = start
   ip_range = []

   ip_range.append(start_ip)
   while temp != end:
      start[3] += 1
      for i in (3, 2, 1):
         if temp[i] == 256:
            temp[i] = 0
            temp[i-1] += 1
      ip_range.append(".".join(map(str, temp)))    

   return ip_range


# sample usage 
ip_input = ("10.9.1.1-10.9.1.12")
ip_input_start = ip_input.split("-")[0]
ip_input_end = ip_input.split("-")[1]
ip_range = ipRange(ip_input_start, ip_input_end)
for ip in ip_range:
   print(ip)
python ansible ip
1个回答
0
投票

这里是其他人遇到此问题时可以使用的代码。这将打印出arraylist中的所有ip。现在应该可以轻松在Ansible中使用。

def ipRange(start_ip, end_ip):
   start = list(map(int, start_ip.split(".")))
   end = list(map(int, end_ip.split(".")))
   temp = start
   ip_range = []

   ip_range.append(start_ip)
   while temp != end:
      start[3] += 1
      for i in (3, 2, 1):
         if temp[i] == 256:
            temp[i] = 0
            temp[i-1] += 1
      ip_range.append(".".join(map(str, temp)))    

   return ip_range


# sample usage 
ip_input = ['10.9.1.1-10.9.1.12', '10.9.1.21-10.9.1.28', '10.9.1.15', '10.9.1.18']
for i in range(len(ip_input)):
    if(ip_input[i].count('-')==0):
        print(ip_input[i])
    if(ip_input[i].count('-')==1):
      ip_input_start = ip_input[i].split('-')[0]
      ip_input_end = ip_input[i].split('-')[1]
      ip_range = ipRange(ip_input_start, ip_input_end)
      for ip in ip_range:
          print(ip)

输出:

10.9.1.1
10.9.1.2
10.9.1.3
10.9.1.4
10.9.1.5
10.9.1.6
10.9.1.7
10.9.1.8
10.9.1.9
10.9.1.10
10.9.1.11
10.9.1.12
10.9.1.1
10.9.1.2
10.9.1.3
10.9.1.4
10.9.1.5
10.9.1.6
10.9.1.7
10.9.1.8
10.9.1.9
10.9.1.10
10.9.1.11
10.9.1.12
10.9.1.15
10.9.1.18
© www.soinside.com 2019 - 2024. All rights reserved.