文章目录
修改主机名
from ansible.module_utils.basic import *
import commands
module = AnsibleModule(
argument_spec = dict(
hostname=dict(required=True),
ipaddr=dict(required=True),
),
)
name = module.params['hostname']
ipaddr = module.params['ipaddr']
try:
with open("/etc/hosts","r") as f:
lines = f.readlines()
with open("/etc/hosts","w") as f_w:
for line in lines:
line1=line.split()
if name in line1 or ipaddr in line1 :
continue
f_w.write(line)
f_w.write(ipaddr+' '+name+'\n')
result = dict(module='set hosts',changed=True,rc=0)
module.exit_json(**result)
except Exception, e:
result = dict(module='set hosts',changed=False,rc=1)
module.exit_json(**result)
用法
ansible test -m set_hosts -a "hostname='name2' ipaddr='102.0.0.123'"
创建一个新的网卡配置文件
from ansible.module_utils.basic import *
import re
import os
module = AnsibleModule(
argument_spec = dict(
device=dict(required=True),
type=dict(required=True),
ipaddr=dict(default='None'),
netmask=dict(default='None'),
state=dict(default='present'),
),
)
document = '''
device: New network nic name
type: "OVSBridge" or "Ethernet"
ipaddr: default is None
netmask: default is None
state: "present" or "absent" , default is "present"
'''
DEVICE = module.params['device']
TYPE = module.params['type']
IPADDR = module.params['ipaddr']
NETMASK = module.params['netmask']
STATE = module.params['state']
OVS_INFO = '''
DEVICE=
TYPE=OVSBridge
DEVICETYPE=ovs
ONBOOT=yes
BOOTPROTO=none
'''
ETH_INFO='''
TYPE=Ethernet
BOOTPROTO=none
DEFROUTE=yes
PEERDNS=yes
PEERROUTES=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=no
DEVICE=
ONBOOT=yes
'''
def update_nic(TYPE,DEVICE,IPADDR=None,NETMASK=None):
if TYPE == 'OVSBridge':
new_config = OVS_INFO
elif TYPE == 'Ethernet':
new_config = ETH_INFO
with open("/etc/sysconfig/network-scripts/ifcfg-"+DEVICE,"w") as f_W:
f_W.truncate()
for line in new_config.split():
line1 = line.split('=')
if 'DEVICE' in line1:
f_W.write('DEVICE=' + DEVICE + '\n')
continue
elif 'IPADDR' in line1:
f_W.write('IPADDR=' + IPADDR + '\n')
continue
elif 'NETMASK' in line1:
f_W.write('NETMASK=' + NETMASK + '\n')
continue
f_W.write(line + '\n')
if not ( IPADDR is 'None'):
f_W.write('IPADDR=' + IPADDR + '\n')
if not ( NETMASK is 'None'):
f_W.write('NETMASK=' + NETMASK)
try:
if STATE in "present":
update_nic(TYPE,DEVICE,IPADDR,NETMASK)
elif STATE in "absent":
os.remove('/etc/sysconfig/network-scripts/ifcfg-' + DEVICE)
result = dict(module='set new nic',changed=True,rc=0)
module.exit_json(**result)
except Exception, e:
os.remove('/etc/sysconfig/network-scripts/ifcfg-' + DEVICE)
raise e
result = dict(module='set new nic',changed=False,rc=1)
用法
ansible test -m set_new_nic -a "device='br-ex' type='Ethernet' state='present'"
ansible test -m set_new_nic -a "device='br-ex' type='Ethernet' state='present' ipaddr='10.0.0.10' netmask='255.255.255.0"
ansible test -m set_new_nic -a "device='br-ex' type='Ethernet' state='absent'"