ansible学习笔记


ssh认证:
ssh-keygen -t rsa
ssh-copy-id -i /root/.ssh/id_rsa.pub root@172.16.90.19

虚拟化环境:
[root@izbp1a7wyzv7b3ujsfphj2z ansibleui]# virtualenv demo
New python executable in /app/ansibleui/demo/bin/python2
Also creating executable in /app/ansibleui/demo/bin/python
Please make sure you remove any previous custom paths from your /root/.pydistutils.cfg file.
Installing setuptools, pip, wheel...done.
[root@izbp1a7wyzv7b3ujsfphj2z ansibleui]# source demo/bin/activate
(demo) [root@izbp1a7wyzv7b3ujsfphj2z ansibleui]# pip install ansible==1.9.4 Django==1.8 django-filter djangorestframework==3.2.3 MYSQL-python


注册变量 register
把任务的执行结果当成一个变量的值,待后面的任务使用
注册变量经常和debug一起使用
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible# cat f3.yml
---
- hosts: 172.16.90.20
remote_user: root
vars:
touch_file: imoocc2.file
tasks:
- name: get date
shell: uptime
register: date_output
- name: touch file
shell: "touch /tmp/{{touch_file}}"
- name: echo date_output
shell: echo {{date_output.stdout}}>>/tmp/{{touch_file}}

root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat register.yml
---
- hosts: 172.16.90.20
remote_user: root
vars:
touch_file: zhailiang
tasks:
- name: get ls
shell: ls
register: ls_output
- name: echo output
shell: echo "{{ ls_output.stdout }}">>/tmp/{{ touch_file }}
- debug: msg=" {{ ls_output.stdout }}"


root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# ansible-playbook ./register.yml

PLAY [172.16.90.20] ****************************************************************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************************************************************************
ok: [172.16.90.20]

TASK [get ls] **********************************************************************************************************************************************************************************
changed: [172.16.90.20]

TASK [echo output] *****************************************************************************************************************************************************************************
changed: [172.16.90.20]

TASK [debug] ***********************************************************************************************************************************************************************************
ok: [172.16.90.20] => {
"msg": " anaconda3\nAnaconda3-4.1.0-Linux-x86_64.sh\nDesktop\nDocuments\nDownloads\nMusic\nPictures\nPublic\nTemplates\nVideos"
}

PLAY RECAP *************************************************************************************************************************************************************************************
172.16.90.20 : ok=4 changed=2 unreachable=0 failed=0


远程主机的系统变量 Facts
anible会通过setup来搜集主机的系统信息,这些搜集到的系统信息叫Facts
比如:ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"
如果要关闭Fact,可设置gather_facts: no
如果是访问复杂的,可用:
{{ ansible_date_time.date}}
{{ ansible_date_time["time"] }}

when:
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible# cat f4.yml
---
- hosts: 172.16.90.19,172.16.90.20
remote_user: root
vars:
touch_file: imoocc.file
tasks:
- name: "touch flag file"
command: touch /tmp/this_is_{{ansible_distribution}}_system
when: ansible_distribution == "CentOS" and ansible_distribution_major_version == "7"

with_items
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible# cat f5.yml
---
- hosts: 172.16.90.19,172.16.90.20
remote_user: root
tasks:
- name: add serverl users
user: name={{ item.name }} state=present groups={{ item.groups }}
with_items:
- { name: 'testuser1', groups: 'wheel'}
- { name: 'testuser2', groups: 'root'}
当item大于5时,将with_items的数据输出显示到/tmp/kingleoric.txt上
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat with_items.yml
---
- hosts: 172.16.90.20
remote_user: root
tasks:
- name: withitems
shell: echo {{ item }} >> /tmp/kingleoric.txt
with_items: [ 0, 2, 4, 6, 8, 10]
when: item > 5
vars还支持列表:
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat loop1.yml
---
- hosts: 172.16.90.20
vars:
somelist: ["test1", "test2"]
tasks:
- name: add serverl users
user: name={{ item }} state=present groups=testuser1
with_items: "{{ somelist }}"
结果为:
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# ansible-playbook ./loop1.yml

PLAY [172.16.90.20] ****************************************************************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************************************************************************
ok: [172.16.90.20]

TASK [add serverl users] ***********************************************************************************************************************************************************************
changed: [172.16.90.20] => (item=test1)
changed: [172.16.90.20] => (item=test2)

PLAY RECAP *************************************************************************************************************************************************************************************
172.16.90.20 : ok=2 changed=1 unreachable=0 failed=0
with_items支持用于迭代的list类型变量

root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# ansible-playbook ./with_items.yml

PLAY [172.16.90.20] ****************************************************************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************************************************************************
ok: [172.16.90.20]

TASK [withitems] *******************************************************************************************************************************************************************************
skipping: [172.16.90.20] => (item=0)
skipping: [172.16.90.20] => (item=2)
skipping: [172.16.90.20] => (item=4)
changed: [172.16.90.20] => (item=6)
changed: [172.16.90.20] => (item=8)
changed: [172.16.90.20] => (item=10)

PLAY RECAP *************************************************************************************************************************************************************************************
172.16.90.20 : ok=2 changed=1 unreachable=0 failed=0


字典循环
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible# cat f6.yml
---
- hosts: 172.16.90.19,172.16.90.20
remote_user: root
tasks:
- name: add serverl users
user: name={{ item.key }} state=present groups={{ item.value}}
with_dict:
{ 'testuser3': 'wheel', 'testuser4': 'root'}

循环目录:当前目录
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat f7.yml
---
- hosts: 172.16.90.19,172.16.90.20
remote_user: root
tasks:
- file: dest=/tmp/aa state=directory
- copy: src={{ item }} dest=/tmp/bb owner=root mode=600
with_fileglob:
- aa/*


条件+循环
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat f8.yml
---

- hosts: 172.16.90.19,172.16.90.19
remote_user: root
tasks:
- debug: msg= {{item.key}} is the winnter
with_dict: {'kingleoric':{'english': 50, 'chinese': 30}, 'tom': {'english': 80, 'chinese': 30}}
when: item.value.english >= 60
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# ansible-playbook ./f8.yml

PLAY [172.16.90.19,172.16.90.19] ****************************************************************************************************************************************************************

TASK [Gathering Facts] **************************************************************************************************************************************************************************
ok: [172.16.90.19]

TASK [debug] ************************************************************************************************************************************************************************************
skipping: [172.16.90.19] => (item={'key': u'kingleoric', 'value': {u'chinese': 30, u'english': 50}})
ok: [172.16.90.19] => (item={'key': u'tom', 'value': {u'chinese': 30, u'english': 80}}) => {
"item": {
"key": "tom",
"value": {
"chinese": 30,
"english": 80
}
},
"msg": ""
}

PLAY RECAP **************************************************************************************************************************************************************************************
172.16.90.19 : ok=2 changed=0 unreachable=0 failed=0


异常处理:
1.忽略错误
ignore_errors: yes
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat f9.yml
---
- hosts: 172.16.90.19,172.16.90.20
remote_user: root
tasks:
- name: ignore false
command: /bin/false
ignore_errors: yes
- name: touch a file
file: path=/tmp/test2 state=touch mode=0700 owner=root group=root


2.failed_when
当小于3才会执行后面的脚本
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat f10.yml
---
- hosts: 172.16.90.19,172.16.90.20
remote_user: root
tasks:
- name: get process
shell: ps -ef|wc -l
register: process_count
failed_when: process_count < 3
- name: touch a file
file: path=/tmp/test2 state=touch mode=0700 owner=testuser1 group=wheel
当修改为process_count > 3后再执行:
[root@izbp1j17ifxfecekzxs2lyz tmp]# ls -l test2
-rwx------ 1 testuser1 wheel 0 3月 18 19:05 test2

3.
changed_when: false 对应 changed=0 有文件发生变化
#changed_when: false 对应 changed=1 有文件发生变化
当我们控制一些远程主机执行某些任务时,当任务在远程主机上成功执行,状态发生更改时,会返回changed状态响应,状态未发生更改时,会返回OK状态响应。
当任务被跳过时,会返回skipped状态响应。我们可以通过changed_when来手动更改changed响应状态。示例如下:


tags:
1.打标签,可以对一个对象打一个或多个标签
2.标签使用
通过tags和任务对象进行捆绑,控制部分或指定的task执行
打标签对象包括单个task include roles
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat f12_tags.yml
---
- hosts: 172.16.90.19,172.16.90.20
remote_user: root
tasks:
- name: create file 1
shell: touch /tmp/file1.txt
tags:
- cfile1
- cfile3
- name: create file 2
shell: touch /tmp/file2.txt
tags:
- cfile2

只对cfile1处理
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# ansible-playbook ./f12_tags.yml -t cfile1

跳过cfile1
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# ansible-playbook ./f12_tags.yml --skip-tags cfile1

roles


handler
按照定义的顺序执行的,而不是按照任务中的顺序执行:
定义顺序是1>2>3,调用的顺序:3>2>1 执行顺序是1>2>3
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat handler.yml
---
- hosts: 172.16.90.20
remote_user: root
vars:
random_number1: "kingleoric"
random_number2: "leon"

tasks:
- name: copy the /etc/hosts to /tmp/hosts. {{ random_number1 }}
copy: src=/etc/hosts dest=/tmp/hosts.{{ random_number1 }}
notify:
- define the 3nd handler
- name: copy the /etc/hosts to /tmp/hosts. {{ random_number2 }}
copy: src=/etc/hosts dest=/tmp/hosts.{{ random_number2 }}
notify:
- define the 2nd handler
- define the 1st handler
handlers:
- name: define the 1st handler
debug: msg="define the 1st"
- name: define the 2nd handler
debug: msg="define the 2nd"
- name: define the 3nd handler
debug: msg="define the 3nd"


root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# ansible-playbook ./handler.yml

PLAY [172.16.90.20] ****************************************************************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************************************************************************
ok: [172.16.90.20]

TASK [copy the /etc/hosts to /tmp/hosts. kingleoric] *******************************************************************************************************************************************
changed: [172.16.90.20]

TASK [copy the /etc/hosts to /tmp/hosts. leon] *************************************************************************************************************************************************
changed: [172.16.90.20]

RUNNING HANDLER [define the 1st handler] *******************************************************************************************************************************************************
ok: [172.16.90.20] => {
"msg": "define the 1st"
}

RUNNING HANDLER [define the 2nd handler] *******************************************************************************************************************************************************
ok: [172.16.90.20] => {
"msg": "define the 2nd"
}

RUNNING HANDLER [define the 3nd handler] *******************************************************************************************************************************************************
ok: [172.16.90.20] => {
"msg": "define the 3nd"
}

PLAY RECAP *************************************************************************************************************************************************************************************
172.16.90.20 : ok=6 changed=2 unreachable=0 failed=0


include
include_tasks/include :动态包含tasks的任务列表
f12_include.yml包含touchf1.yml和touchf2.yml 2个yml文件
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat f12_include.yml
---
- hosts: 172.16.90.19,172.16.90.20
remote_user: root
tasks:
- include_tasks: touchf1.yml
- include_tasks: touchf2.yml

root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat touchf1.yml
---
- name: create file 1
shell: touch /tmp/file1.txt
tags:
- cfile1
- cfile3

root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat touchf2.yml
---
- name: create file 2
shell: touch /tmp/file2.txt
tags:
- cfile2

模板 template
playbook中定义的变量,inventory中的Host Group 都可以在template使用
这个例子使用template模块复制index.html.j2并替换为index.html
其中index.html.j2为:
<html>
<title>#46 Demo</title>

<!--
http://stackoverflow.com/questions/22223270/vertically-and-horizontally-center-a-div-with-css
http://css-tricks.com/centering-in-the-unknown/
http://jsfiddle.net/6PaXB/
-->

<style>.block {text-align: center;margin-bottom:10px;}.block:before {content: '';display: inline-block;height: 100%;vertical-align: middle;margin-right: -0.25em;}.centered {display: inline-block;vertical-align: middle;width: 300px;}</style>

<body>
<div class="block" style="height: 99%;">
<div class="centered">
<h1>#46 Demo {{ defined_name }}</h1>
<p>Served by {{ ansible_hostname }} ({{ ansible_default_ipv4.address }}).</p>
</div>
</div>
</body>
</html>

root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# cat template.yml
---
- hosts: 172.16.90.20
remote_user: root
vars:
http_port: 80
defined_name: "hello my name is kingleoric"
tasks:
- name: write configuration file
template: src=/etc/ansible/templates/index.html.j2 dest=/tmp/index.html
notify:
- restart apache
handlers:
- name: restart apache
service: name=httpd state=restarted
结果为:
root@iZbp133fmo5z205fno4gkiZ:/etc/ansible/playbooks# ansible-playbook ./template.yml

PLAY [172.16.90.20] ****************************************************************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************************************************************************
ok: [172.16.90.20]

TASK [write configuration file] ****************************************************************************************************************************************************************
changed: [172.16.90.20]

RUNNING HANDLER [restart apache] ***************************************************************************************************************************************************************
changed: [172.16.90.20]

PLAY RECAP *************************************************************************************************************************************************************************************
172.16.90.20 : ok=3 changed=2 unreachable=0 failed=0
目标服务器出现index.html的文件

posted @ 2018-04-18 11:30  kingleoric  阅读(1143)  评论(0编辑  收藏  举报