Ansible练习第一篇。
使用playbook安装nginx,方法简便,安装配置全自动化,较为方便。安装环境为CentOS6.5,安装使用的是epel库中的nginx,示例安装中配置了一个https的server,http的server为默认自带的server。nginx使用的证书可以自签。
playbook目录结构如下:
-nginx_install_playbook
-nginx_install.yml
-files
-nginx.crt
-nginx.key
-templates
-nginx.conf.j2
-index.html.j2
nginx_install.yml:
---
- name : Configure webserver with nginx and tls
user : root
hosts : testservers
gather_facts : false
vars :
key_file: /etc/nginx/ssl/nginx.key
cert_file: /etc/nginx/ssl/nginx.crt
conf_file: /etc/nginx/conf.d/server.conf
index_file: /usr/share/nginx/html/index.html
server_name: anstest.example.com
tasks:
- name: Install nginx
yum: name=nginx
- name: create directories for ssl certificates
file: path=/etc/nginx/ssl state=directory
- name: copy TLS key
copy: src=files/nginx.key dest={{ key_file }} owner=root mode=0600
notify: restart nginx
- name: copy TLS certificate
copy: src=files/nginx.crt dest={{ cert_file }}
notify: restart nginx
- name: copy nginx config file
template: src=templates/nginx.conf.j2 dest={{ conf_file }}
notify: restart nginx
- name: copy index.html
template: src=templates/index.html.j2 dest={{ index_file }}
notify: restart nginx
handlers:
- name: restart nginx
service: name=nginx state=restarted
nginx.conf.j2:
server{
listen 443 ssl;
root /usr/share/nginx/html;
index index.html index.htm;
server_name {{ server_name }};
ssl_certificate {{ cert_file }};
ssl_certificate_key {{ key_file }};
location /{
try_files $uri $uri/ =404;
}
}
index.html.j2:
<html>
<head>
<title>Welcome to ansible nginx.</title>
</head>
<body>
<h1>Nginx, configured by ansible.</h1>
<p>lalala</p>
<p>{{ ansible_managed }}</p>
</body>
</html>
安装完成后,配置host,直接访问https://anstest.example.com即可。
一些关于playbook的知识点:
playbook是一个yml文件,其结构等同于json。也就是说可以将playbook视为一个json文件,playbook是一个列表,playbook包含了若干个字典——play,即play可以视为字典;play这个字典中又包含了数个属性,比如name, hosts, user, tasks等,其中tasks是需要执行的任务列表,包含若干个任务,每个任务又是一个字典,字典项的格式即为module : command。
playbook的json格式:
[#playbook
{#play1
"name" : "I am play 1."
"hosts" : "hostnames"
"tasks" : [
{#task1
"name" : "I am task 1."
"module":"command"
}
{#task2
"name" : "I am task 1."
"module":"command"
}
...
]
}
{#play2
"name" : "I am play 2."
"hosts" : "hostnames"
"tasks" : [
{#task1
"name" : "I am task 1."
"module":"command"
}
{#task2
"name" : "I am task 1."
"module":"command"
}
...
]
}
...
]
每个play是由host的无序集合和task的有序列表组成的。也就是说,在执行一个play时,所有play中配置好的host是并行执行的,即同时开始执行第一个任务task1;ansible在确认所有host都执行完task1之后,再开始让所有host并行执行task2。
关于ansible的幂等性:每个task执行完成后,ansible会返回执行状态,是changed还是ok,changed表示这个host发生了改变,ok则是目标host已经和playbook中想要达成的状态是一致的了,不用再执行任何操作。这也可以反映出ansible执行命令只关心最后的结果是否与命令的意图一致,而不关心过程中是否执行了某一个步骤。这样就保证了ansible的playbook无论执行多少次(不出错的情况下),其结果都是相同的。
如果playbook执行出错,playbook立即退出,出错task之后的task不再执行。下次执行如果不想重复执行上一个已经执行过的task,可以使用--start-from-task <taskname>,指定从哪个task开始执行。