您的位置:首页 > 其它

ansible循环,判断

2015-12-25 10:51 274 查看
背景:关于ansible的常规使用,我上一篇关于ansible中文手册中已经提到过了。ansible中文手册也已经覆盖了基本的使用需求。我这边就补充一些,可能中文手册中没有细讲的东西和一些使用实例。

++++注册变量、when使用++++
---
- hosts: 172.17.92.167
tasks:
- name: shell return result
shell: ps -ef |grep -v grep | grep server | wc -l
register: resulet
- shell: touch /tmp/55555{{resulet.stdout}}s-SA
when: resulet.stdout == "3"
注:这里需要注意点是,register: var_name 这个是将我们运行这条shell的最红ansible的结果注册成为var_name。而实际上这个var_name的内容是什么样的。我让大家看一下。一下的红色部分其实就是我们register的var_name的内容了。 那大家会疑问怎么拿到我们真真想要的这个wc -l后的结果呢? 那大家再看红色部分加粗的部分,这就是我们想要的内容。并且大家注意这里的 3是一个unicode类型。也就是你不能够在when中直接和数字去进行比较,这就变量和when的一个使用技巧。
***
TASK: [shell touch /tmp/55555{{resulet}}] *************************************
failed: [172.17.92.167] => {"changed": true, "cmd": "touch /tmp/55555{u'changed': True, u'end': u'2015-12-24 17:48:38.384595', u'stdout': u'3', u'cmd': u'cat /tmp/tmpfile', u'rc': 0, u'start': u'2015-12-24 17:48:38.382569', u'stderr': u'', u'delta': u'0:00:00.002026', 'invocation': {'module_name': u'shell', 'module_complex_args': {}, 'module_args': u'cat /tmp/tmpfile'}, 'stdout_lines': [u'3'], u'warnings': []}", "delta": "0:00:00.004073", "end": "2015-12-24 17:48:38.520033", "rc": 1, "start": "2015-12-24 17:48:38.515960", "warnings": ["Consider using file module with state=touch rather than running touch"]}
stderr: touch: cannot touch `ucat /tmp/tmpfile,': No such file or directory

touch: cannot touch `ucat /tmp/tmpfile},': No such file or directory
***

++++++ 循环 +++++
先给大家上一个范例
root@docker-host-01:/app# more m4-deploey.yml
---
- hosts: server
tasks:
- name: mkdir project direction
shell: mkdir -p {{ project_path }}
- name: create a virtual host file for
copy: src=/app/test.app.m4.tar.gz dest={{ project_path }}/test.app.m4.tar.gz
- name: apt install daemontools
apt: name=daemontools state=present
- name: tar file
shell: cd {{ project_path }} && tar -zxf test.app.m4.tar.gz

- name: copy file
template: src=/app/app/config/{{ item }} dest={{ project_path }}/config/{{ item }}
with_items:
- "dblc.conf"
- "libdbapi.conf"

- name: Get number of project_path/server svscan process
shell: ps -ef |grep -v grep | grep {{project_path}}/server | wc -l
register: number

- shell: touch {{ project_path }}/server/runfile
when: number < 1
..
以上的红色部分就是循环的使用,当然with_items还有几种不同的参数方式。并且ansible的循环功能不仅仅是可以循环变量,还能够循环获取文件。我这边不累述,附上官网的地址方便大家查看:http://docs.ansible.com/ansible/playbooks_loops.html
另外再附上when的链接:http://docs.ansible.com/ansible/playbooks_conditionals.html

本文出自 “从头开始” 博客,请务必保留此出处http://atong.blog.51cto.com/2393905/1728153
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: