ansible 不同环境指定不同变量 (变量写入文件)

简介:

参考https://segmentfault.com/a/1190000008459574


group_vars

mkdir -p group_vars/dev group_vars/prod

touch group_vars/dev/nginx.yml group_vars/prod/nginx.yml

├── nginx.yml

├── named.conf.j1

├── named.conf.j2

└── nginx

       └── tasks

             └── main.yml


cat group_vars/dev/nginx.yml

nginx: 172.1.1.1

ip:

  api: ['172.1.1.126:8080']


vim nginx.yml

- hosts: "` nginx `"

  remote_user: root

  gather_facts: no

  vars_files:

    - foo.yml

  tasks:

  - name: copy

    template: dest=/tmp/`item`.`key`.conf src=/etc/ansible/test1/named.conf.j2 force=yes

    with_dict: "` ip `"

  - name: copy

    template: dest=/tmp/`item`.`key`.conf src=/etc/ansible/test1/named.conf.j1 force=yes

    with_dict: "` ip `"



├── named.conf.j1

├── named.conf.j2

(./set

upstream ` item`.`key ` {

    {% for key in item.value  %}

    ` key ` weight=1;

    {% endfor %}

      

    check interval=2000 rise=2 fall=2 timeout=1000 type=http;

    check_http_send "GET /  HTTP/1.0\r\n\r\n";

    check_http_expect_alive http_2xx http_3xx;

}

 

---

 

./conf

server {

        listen  80;

        server_name     `item`.`key`.com;

       location / {

      proxy_next_upstream http_500 http_502 http_503 http_504 error timeout invalid_header;

      proxy_pass http://`item`.`key`;

}

}

)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
cat  / etc / ansible / test.py
 
import  sys
 
try :
     import  json
except  ImportError:
     import  simplejson as json
 
def  grouplist():
     inventory  =  {}
     sfile = '/etc/ansible/books.txt'
     with  open (sfile, 'rb' ) as f:
         for  in  f.readlines():
             group = i.strip().split()[ 0 ]
             name = i.strip().split()[ 1 ]
             if  not  group  in  inventory:
                 inventory[group]  =  {
                     'hosts' : []
                 }
             inventory[group][ 'hosts' ].append(name)
 
         print  json.dumps(inventory, indent = 4 )
 
     
def  hostinfo(name):
     vars  =  {}
     vars  =  {
         'admin' 'Jane Jolie' ,
         'datacenter' 1
     }
     print  json.dumps( vars , indent = 4 )
 
if  __name__  = =  '__main__' :
     if  len (sys.argv)  = =  2  and  (sys.argv[ 1 = =  '--list' ):
         grouplist()
     elif  len (sys.argv)  = =  3  and  (sys.argv[ 1 = =  '--host' ):
         hostinfo(sys.argv[ 2 ])
     else :
         print  "Usage: %s --list or --host <hostname>"  %  sys.argv[ 0 ]
         sys.exit( 1 )


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
cat  / etc / ansible / foo.py
 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import  ConfigParser
import  string, os, sys,json
import  yaml
 
'''
vim books.txt
api 172.1.1.126 dev 8005 8080 api  bj5
pf 172.1.1.127 prod 8006 8081 pf bj02
'''
'''
生成的foo.yml
ip:
   api: ['172.1.1.126:8080']
'''
 
 
def  ynameconf():
     sfile  =  'books.txt'
     stagedict  =  {}
     with  open (sfile,  'rb' ) as f:
         for  in  f.readlines():
             inventory  =  {}
             ip  =  i.strip().split()[ 1 ]
             yname  =  i.strip().split()[ 5 ]   # 域名
             stage  =  i.strip().split()[ 2 ]
             if  stage  not  in  stagedict:
                 if  not  yname  in  inventory:
                     inventory[yname]  =  []
                 port  =  i.strip().split()[ 4 ]
                 ipport  =  ip  +  ":"  +  port
                 inventory[yname].append(ipport)
                 stagedict[stage]  =  inventory
                 print  stagedict
             elif  stage  in  stagedict:
                 dict1  =  stagedict[stage]
                 if  not  yname  in  inventory:
                     inventory[yname]  =  []
                 port  =  i.strip().split()[ 4 ]
                 ipport  =  ip  +  ":"  +  port
                 inventory[yname].append(ipport)
                 dict2  =  inventory
                 newdict  =  dict (dict1.items() + dict2.items())
                 stagedict[stage]  =  newdict
     f.close()
     return  stagedict
 
def  ynameParser(stage, file ):
     # cf = ConfigParser.ConfigParser()
     ynameyname = ynameconf()
 
     # print ynameyname
     # devstage = ynameyname[stage]
     # jsObj = json.dumps(devstage)
     # fileObject = open(file, 'w')
     # fileObject.write(jsObj)
     # fileObject.close()
 
     print  type (jsObj)
     fileObject  =  open ( file 'w' )
     dataMap  =  { "ip" : jsObj}
     yaml.dump(dataMap, fileObject)
 
 
     '''
     for k,v in ynameyname.iteritems():
         general=k
         cf.add_section(general)
         cf.set(general, "pro_dir", k)
         for i in range(len(v)):
             ips="ip"+str(i+1)
             cf.set(general,ips, v[i])
         # cf.set(k, ','.join(v))
         cf.write(open("vhost.fact", "w"))
     '''
 
if  __name__  = =  '__main__' :
     list2 = [ "foo.yml" , "foo2.yml" ]
     list1 = [ "dev" , "prod" ]
     for  (stage,  file in  zip (list1, list2):
         ynameParser(stage,  file )


使用

python foo.py

ansible-playbook -i /etc/ansible/test.py nginx.yml


后者


- hosts: nginx

  remote_user: root

  gather_facts: no

  vars:

    ipall: {'api':['172.1.1.2'],'api3':['172.1.1.1']}

  tasks:

  - name: get

    set_fact: 

      iplist: "{{ lookup('file', '/etc/ansible/foo.txt') }}"

  - name: copy

    template: dest=/usr/local/tengine/conf/SET/`item`.`key`.conf src=/etc/ansible/named.conf.j2 force=yes

    with_dict: iplist

  - name: copy

    template: dest=/usr/local/tengine/conf/conf.d/`item`.`key`.conf src=/etc/ansible/named.conf.j1 force=yes

    with_dict: iplist



本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/1966824,如需转载请自行联系原作者
相关文章
ansible的环境部署及简单使用
ansible的环境部署及简单使用
197 0
|
2月前
|
Kubernetes 安全 Linux
ansible-install-k8s 之 1 初始化环境
ansible-install-k8s 之 1 初始化环境
|
4月前
|
jenkins Linux 持续交付
在Linux中,如何使用Jenkins和Ansible进行虚拟化环境的自动化和持续集成/持续部署(CI/CD)?
在Linux中,如何使用Jenkins和Ansible进行虚拟化环境的自动化和持续集成/持续部署(CI/CD)?
|
5月前
|
JSON 数据格式 索引
Ansible fact变量与魔法变量
Ansible fact变量与魔法变量
70 6
|
5月前
|
存储 网络安全 数据安全/隐私保护
Ansible的变量
Ansible的变量
50 6
|
运维 安全 持续交付
利用ansible的角色快速批量一键部署基础docker环境
利用ansible的角色快速批量一键部署基础docker环境
453 0
利用ansible的角色快速批量一键部署基础docker环境
|
缓存 运维 监控
【运维知识进阶篇】Ansible变量详解(变量定义+变量优先级+变量注册+层级定义变量+facts缓存变量)
【运维知识进阶篇】Ansible变量详解(变量定义+变量优先级+变量注册+层级定义变量+facts缓存变量)
407 0
|
存储 JSON 数据安全/隐私保护
ansible定义变量和管理事实
ansible定义变量和管理事实
157 0
|
存储 缓存 监控
【2023】ansible-variables变量详解
【2023】ansible-variables变量详解
136 0
Ansible 自定义变量与 role 默认变量的合并方法
如果你遇到 failed to combine variables, expected dicts but got a &#39;NoneType&#39; and a &#39;dict&#39; 这样的报错,你可以看看本文。
328 0