register
register
用于注冊(cè)一個(gè)變量,保存命令的結(jié)果(shell或command模塊)缰揪,這個(gè)變量可以在后面的task眨业、when語(yǔ)句或模板文件中使用,該指令用在循環(huán)中會(huì)有不同画株,請(qǐng)看ansible學(xué)習(xí)之八:Loops中關(guān)于register的講解
- shell: /bin/pwd
register: pwd_result
此時(shí)變量pwd_result的結(jié)果為:
{
u'changed': True,
u'end': u'2014-02-23 12:02:51.982893',
u'cmd': [u'/bin/pwd'],
u'start': u'2014-02-23 12:02:51.980191',
u'delta': u'0:00:00.002702',
u'stderr': u'',
u'rc': 0, #這個(gè)就是命令返回狀態(tài)辆飘,非0表示執(zhí)行失敗
'invocation': {'module_name': 'command', 'module_args': '/bin/pwd'},
u'stdout': u'/home/sapser', #以一個(gè)字符串保存命令結(jié)果
'stdout_lines': [u'/home/sapser'] #以列表保存命令結(jié)果
}
在隨后的task中使用該變量:
- debug: msg="{{pwd_result}}"
when: pwd_result.rc == 0
循環(huán)處理命令結(jié)果:
- name: registered variable usage as a with_items list
hosts: all
tasks:
- name: retrieve the list of home directories
command: ls /home
register: home_dirs
- name: add home dirs to the backup spooler
file: path=/mnt/bkspool/{{ item }} src=/home/{{ item }} state=link
with_items: home_dirs.stdout_lines #等同于with_items: home_dirs.stdout.split()