安装ansible
# yum -y install epel-release# yum list all *ansible*# yum info ansible# yum -y install ansibleansible配置文件/etc/ansible/ansible.cfg 主配置文件/etc/ansible/hosts Inventory/usr/bin/ansible-doc 帮助文件/usr/bin/ansible-playbook 指定运行任务文件定义Inventory# cd /etc/ansible/# cp hosts{,.bak}# > hosts# cat hosts[webserver]127.0.0.1192.168.10.149[dbserver]192.168.10.113使用秘钥方式连接# ssh-keygen -t rsa# ssh-copy-id -i /root/.ssh/id_rsa.pub # ssh-copy-id -i /root/.ssh/id_rsa.pub # ssh-copy-id -i /root/.ssh/id_rsa.pub 使用帮助# ansible-doc -l 列出ansible所有的模块# ansible-doc -s MODULE_NAME 查看指定模块具体适用ansible命令应用基础语法:ansible <host-pattern> [-f forks] [-m module_name] [-a args]<host-pattern> 这次命令对那些主机生效的inventory group nameipall-f forks 一次处理多少个主机-m module_name 要使用的模块-a args 模块特有的参数# ansible 192.168.10.113 -m command -a 'date'# ansible webserver -m command -a 'date'# ansible all -m command -a 'date'常见模块command 命令模块(默认模块)用于在远程主机执行命令;不能使用变量,管道等# ansible all -a 'date'cron 计划任务month 指定月份minute 指定分钟job 指定任务day 表示那一天hour 指定小时weekday 表示周几state 表示是添加还是删除present:安装absent:移除# ansible webserver -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job"' #不写默认都是*,每个任务都必须有一个名字# ansible webserver -a 'crontab -l'# ansible webserver -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state=absent' #移除任务user 用户账号管理name 用户名uid uidstate 状态group 属于哪个组groups 附加组home 家目录createhome 是否创建家目录comment 注释信息system 是否是系统用户# ansible all -m user -a 'name="user1"'# ansible all -m user -a 'name="user1" state=absent'group 组管理gid gidname 组名state 状态system 是否是系统组# ansible webserver -m group -a 'name=mysql gid=306 system=yes'# ansible webserver -m user -a 'name=mysql uid=306 system=yes group=mysql'copy 复制文件(复制本地文件到远程主机的指定位置)src 定义本地源文件路径dest 定义远程目录文件路径(绝对路径)owner 属主group 属组mode 权限content 取代src=,表示直接用此处的信息生成为文件内容# yum -y install libselinux-python# ansible all -m copy -a 'src=/etc/fstab dest=/tmp/fstab.ansible owner=root mode=640'# ansible all -m copy -a 'content="hello ansible\nHi ansible" dest=/tmp/test.ansible'file 设置文件的属性path|dest|name 对那个文件做设定创建文件的符号链接:src: 指定源文件path: 指明符号链接文件路径# ansible all -m file -a 'owner=mysql group=mysql mode=644 path=/tmp/fstab.ansible'# ansible all -m file -a 'path=/tmp/fstab.link src=/tmp/fstab.ansible state=link'ping 测试指定主机是否能连接# ansible all -m pingservice 管理服务运行状态enabled 是否开机自动启动name 指定服务名state 指定服务状态started 启动服务stoped 停止服务restarted 重启服务arguments 服务的参数# ansible webserver -m service -a 'enabled=true name=httpd state=started'shell 在远程主机上运行命令尤其是用到管道变量等功能的复杂命令# ansible all -m shell -a 'echo magedu | passwd --stdin user1'script 将本地脚本复制到远程主机并运行之# ansible all -m script -a '/tmp/test.sh'yum 安装程序包name 程序包名称(不指定版本就安装最新的版本latest)state present,latest表示安装,absent表示卸载# ansible webserver -m yum -a 'name=httpd'# ansible all -m yum -a 'name=ntpdate' #默认就是安装# ansible all -m yum -a 'name=ntpdate state=absent'setup 收集远程主机的facts每个被管理节点在接受并运行管理命令之前,会将自己主机相关信息,如操作系统版本,IP地址等报告给远程的ansible主机# ansible all -m setupansible playbook组成结构:inventory #以下操作应用的主机modules #调用哪些模块做什么样的操作ad hoc commands #在这些主机上运行哪些命令playbookstasks #任务,即调用模块完成的某操作variable #变量templates #模板handlers #处理器,由某事件触发执行的操作roles #角色四、YAML4.1 YAML介绍YAML是一个可读性高的用来表达资料序列的格式。YAML参考了其它多种语言,包括:XML、C语言、Python、Perl以及电子邮件格式RFC2822等。ClarkEvans在2001年首次发表了这种语言,另外Ingy dot Net与Oren Ben-Kiki也是这语言的共同设计者。YAML Ain't Markup Language,即YAML不是XML,不过,在开发这种语言时,YAML的意思其实是:"Yet Another Markup Language"(仍是一种标记语言),其特性:YAML的可读性好YAML和脚本语言的交互性好YAML使用实现语言的数据类型YAML有一个一致的信息模型YAML易于实现YAML可以基于流来处理YAML表达能力强,扩展性好更多的内容及规范参见4.2 YAML语法YAML的语法和其他高阶语言类似,并且可以简单表达清单、散列表、标量等数据结构,其结构(structure)通过空格来展示,序列(sequence)里的项用"-"来表示,Map里面的键值对用":"分割,下面是一个示例。name:john smithage: 41gender: malespouse:name:jane smithage:37gender: femalechildren:- name:jimmy smithage:17gender: male- name:jenny smithage: 13gender: femaleYAML文件扩展名通常为.yaml,如example.yaml4.2.1 list列表的所有元素均使用"-"打头,例如:# A list of testy fruits- Apple- Orange- Strawberry- Mango4.2.2 dictionary字典通过key与value进行标识,例如:---# An employee recordname: Example Developerjob: Developerskill: Elite也可以将key:value放置于{}中进行表示,例如:---#An exmloyee record{name: Example Developer, job: Developer, skill: Elite}五、Ansible基础元素5.1 变量5.1.1 变量命名变量名仅能由字母、数字和下划线组成,且只能以字母开头。5.1.2 factsfacts是由正在通信的远程目标主机发回的信息,这些信息被保存在ansible变量中。要获取指定的远程主机所支持的所有facts,可使用如下命令进行:#ansible hostname -m setup5.1.3 register把任务的输出定义为变量,然后用于其他任务,实例如下:tasks:- shell: /usr/bin/fooregister: foo_resultignore_errors: True5.1.4 通过命令行传递变量在运行playbook的时候也可以传递一些变量供playbook使用,示例如下:#ansible-playbook test.yml --extra-vars "hosts=www user=mageedu"5.1.5 通过roles传递变量当给一个主机应用角色的时候可以传递变量,然后在角色内使用这些变量,示例如下:- hosts: webserverroles:- common- {role: foo_app_instance, dir: '/web/htdocs/a.com', port: 8080}5.2 Inventoryansible的主要功用在于批量主机操作,为了便捷的使用其中的部分主机,可以在inventory file中将其分组命名,默认的inventory file为/etc/ansible/hostsinventory file可以有多个,且也可以通过Dynamic Inventory来动态生成。5.2.1 inventory文件格式inventory文件遵循INI文件风格,中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中;此外,当如若目标主机使用非默认的SSH端口,还可以在主机名称之后使用冒号加端口号来表明。ntp.magedu.com[webserver]www1.magedu.com:2222www2.magedu.com[dbserver]db1.magedu.comdb2.magedu.comdb3.magedu.com如果主机名遵循相似的命名模式,还可使用列表的方式标识个主机,例如:[webserver]www[01:50].example.com[databases]db-[a:f].example.com5.2.2 主机变量可以在inventory中定义主机时为其添加主机变量以便于在playbook中使用,例如:[webserver]www1.magedu.com http_port=80 maxRequestsPerChild=808www2.magedu.com http_port=8080 maxRequestsPerChild=9095.2.3 组变量组变量是指赋予给指定组内所有主机上的在playbook中可用的变量。例如:[webserver]www1.magedu.comwww2.magedu.com[webserver:vars]ntp_server=ntp.magedu.comnfs_server=nfs.magedu.com5.2.4 组嵌套inventory中,组还可以包含其它的组,并且也可以向组中的主机指定变量。不过,这些变量只能在ansible-playbook中使用,而ansible不支持。例如:[apache]httpd1.magedu.comhttpd2.magedu.com[nginx]ngx1.magedu.comngx2.magedu.com[webserver:children] #固定格式apachenginx[webserver:vars]ntp_server=ntp.magedu.com5.2.5 inventory参数ansible基于ssh连接inventory中指定的远程主机时,还可以通过参数指定其交互方式,这些参数如下所示:ansible_ssh_hostansible_ssh_portansible_ssh_useransible_ssh_passansible_sudo_passansible_connectionansible_ssh_private_key_fileansible_shell_typeansible_python_interpreter5.3 条件测试如果需要根据变量、facts或此前任务的执行结果来做为某task执行与否的前提时要用到条件测试。5.3.1 when语句在task后添加when字句即可使用条件测试;when语句支持jinja2表达式语句,例如:tasks:- name: 'shutdown debian flavored system"command: /sbin/shutdown -h nowwhen: ansible_os_family == "Debian"when语句中还可以使用jinja2的大多"filter",例如果忽略此前某语句的错误并基于其结果(failed或success)运行后面指定的语句,可使用类似如下形式;tasks:- command:/bin/falseregister: resultignore_errors: True- command: /bin/somethingwhen: result|failed- command: /bin/something_elsewhen: result|success- command: /bin/still/something_elsewhen: result|skipped此外,when语句中还可以使用facts或playbook中定义的变量# cat cond.yml- hosts: allremote_user: rootvars:- username: user10tasks:- name: create ` username ` useruser: name=` username `when: ansible_fqdn == "node1.exercise.com"5.4 迭代当有需要重复性执行的任务时,可以使用迭代机制。其使用格式为将需要迭代的内容定义为item变量引用,并通过with_items语句来指明迭代的元素列表即可。例如:- name: add server useruser: name=` item ` state=persent groups=wheelwith_items:- testuser1- testuser2上面语句的功能等同于下面的语句:- name: add user testuser1user: name=testuser1 state=present group=wheel- name: add user testuser2user: name=testuser2 state=present group=wheel事实上,with_items中可以使用元素还可为hashes,例如:- name: add several usersuser: name=` item`.`name` state=present groups=` item`.`groups `with_items:- { name: 'testuser1', groups: 'wheel'}- { name: 'testuser2', groups: 'root'}ansible的循环机制还有更多的高级功能,具体请参考官方文档模板示例:# grep '{ {' conf/httpd.confMaxClients ` maxClients `Listen ` httpd_port `# cat /etc/ansible/hosts[webserver]127.0.0.1 httpd_port=80 maxClients=100192.168.10.149 httpd_port=8080 maxClients=200# cat apache.yml- hosts: webserverremote_user: rootvars:- package: httpd- service: httpdtasks:- name: install httpd packageyum: name=` package ` state=latest- name: install configuration file for httpdtemplate: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.confnotify:- restart httpd- name: start httpd serviceservice: enabled=true name=` service ` state=startedhandlers:- name: restart httpdservice: name=httpd state=restarted七、ansible playbooksplaybook是由一个或多个"play"组成的列表。play的主要功能在于将事先归并为一组的主机装扮成事先通过ansible中的task定义好的角色。从根本上来讲,所有task无非是调用ansible的一个module。将多个play组织在一个playbook中,即可以让他们连同起来按事先编排的机制同唱一台大戏。下面是一个简单示例。- hosts: webservervars:http_port: 80max_clients: 256remote_user: roottasks:- name: ensure apache is at the latest versionyum: name=httpd state=latest- name: ensure apache is runningservice: name=httpd state=startedhandlers:- name: restart apacheservice: name=httpd state=restarted7.1 playbook基础组件7.1.1 Hosts和Usersplaybook中的每一个play的目的都是为了让某个或某些主机以某个指定的用户身份执行任务。hosts用于指定要执行指定任务的主机,其可以使一个或多个由冒号分隔主机组;remote_user则用于指定远程主机的执行任务的用户,如上面的实例中的- hosts: webserverremote_user: root不过,remote_user也可用于各task中,也可以通过指定其通过sudo的方式在远程主机上执行任务,其可用于play全局或其任务;此外,甚至可以在sudo时使用sudo_user指定sudo时切换的用户。- hosts: webserverremote_user: magedutasks:- name: test connectionping:remote_user: magedusudo: yes7.1.2 任务列表和actionplay的主题部分是task list。task list中的各任务按次序逐个在hosts中指定的所有主机上执行,即在所有主机上完成第一个任务后再开始第二个。在运行自上而下某playbook时,如果中途发生错误,所有已执行任务都可能回滚,在更正playbook后重新执行一次即可。taks的目的是使用指定的参数执行模块,而在模块参数中可以使用变量。模块执行是幂等的。这意味着多次执行是安全的,因为其结果均一致。每个task都应该有其name,用于playbook的执行结果输出,建议其内容尽可能清晰地描述任务执行步骤,如果为提供name,则action的结果将用于输出。定义task的可以使用"action: module options"或”module:options“的格式推荐使用后者以实现向后兼容。如果action一行的内容过多,也中使用在行首使用几个空白字符进行换行。tasks:- name:make sure apache is runningservice: name=httpd state=started在众多的模块中,只有command和shell模块仅需要给定一个列表而无需使用"key=value"格式,例如:tasks:- name: disable selinuxcommand: /sbin/setenforce 0如果命令或脚本的退出码不为零,可以使用如下方式替代:tasks:- name: run this command and ignore the resultshell: /usr/bin/somecommand || /bin/true或者使用ignore_errors来忽略错误信息:tasks:- name: run this command and ignore the resultshell: /usr/bin/somecommandignore_errors: True7.1.3handlers用于当关注的资源发生变化时采取一定的操作。"notify"这个action可用于在每个play的最后被触发,这样可以避免多次有改变发生时每次都执行执行的操作,取而代之,仅在所有的变化发生完成后一次性地执行指定操作,在notify中列出的操作称为handlers,也即notify中调用handlers中定义的操作。- name: template configuration filetemplate: src=template.j2 dest=/etc/foo.confnotify:- restart memcached- restart apachehandlers是task列表,这些task与前述的task并没有本质上的不同。handlers:- name: restart memcachedservice: name=memcached state=restarted- name: restart apacheservice: name=apache state=restarted简单示例1:# cat nginx.yml- hosts: webserverremote_user: roottasks:- name: create nginxn groupgroup: name=nginx system=yes gid=208- name: create nginx useruser: name=nginx uid=208 group=nginx system=yes- hosts: dbserverremote_user: roottasks:- name: copy file to dbservercopy: src=/etc/inittab dest=/tmp/inittab.ans# ansible-playbook nginx.yml简单示例2:# cat apache.yml- hosts: webserverremote_user: roottasks:- name: install httpd packageyum: name=httpd state=latest- name: install configuration file for httpdcopy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf- name: start httpd serviceservice: enabled=true name=httpd state=started# ansible-playbook apache.ymlhandlers 示例:# cat apache.yml- hosts: webserverremote_user: roottasks:- name: install httpd packageyum: name=httpd state=latest- name: install configuration file for httpdcopy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.confnotify:- restart httpd- name: start httpd serviceservice: enabled=true name=httpd state=startedhandlers:- name: restart httpdservice: name=httpd state=restarted# ansible-playbook apache.ymlvariable 示例1:# cat apache.yml- hosts: webserverremote_user: rootvars:- package: httpd- service: httpdtasks:- name: install httpd packageyum: name=` package ` state=latest- name: install configuration file for httpdcopy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.confnotify:- restart httpd- name: start httpd serviceservice: enabled=true name=` service ` state=startedhandlers:- name: restart httpdservice: name=httpd state=restartedvariable 示例2:(在playbook中可以使用所有的变量)# cat facts.yml- hosts: webserverremote_user: roottasks:- name: copy filecopy: content="` ansible_all_ipv4_addresses ` " dest=/tmp/vars.ans八、rolesansible自1.2版本引入的新特性,用于层次性、结构化地组织playbook。roles能够根据层次型结构自动转载变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。简单来讲,roles就是通过分别将变量、文件、任务、模板以及处理器放置于单独的目录中,并可以便捷地include他们的一种机制。角色一般用于基于主机构建服务的场景中,但也可以使用于构建守护进程的场景中一个roles的案例如下所示:site.ymlwebserver.ymlfooserver.ymlroles/common/files/templates/tasks/handlers/vars/meta/webserver/files/templates/tasks/handlers/vars/meta/而在playbook中,可以这样使用roles---- hosts: webserverroles:- common- webserver也可以向roles传递参数,例如:---- hosts: webserverroles:- common- { role: foo_app_instance, dir:'/opt/a',port:5000}- { role: foo_app_instance, dir:'/opt/b',port:5001}甚至也可以条件式地使用roles,例如:---- hosts:webserverroles:- { role:some_role, when: "ansible_so_family == 'RedHat" }8.1 创建role的步骤(1) 创建以roles命名的目录:(2) 在roles目录中分别穿件以各角色命名的目录,如webserver等(3) 在每个角色命名的目录中分别创建files、handlers、meta、tasks、template和vars目录;用不到的目录可以创建为空目录,也可以不创建(4) 在playbook文件中,调用各角色8.2 role内各目录中可应用的文件task目录:至少应该包含一个为main.yml的文件,其定义了此角色的任务列表;此文件可以使用include包含其它的位于此目录中的task文件;file目录:存放由copy或script等模板块调用的文件;template目录:template模块会自动在此目录中寻找jinja2模板文件;handlers目录:此目录中应当包含一个main.yml文件,用于定义此角色用到的各handlers,在handler中使用inclnude包含的其它的handlers文件也应该位于此目录中;vars目录:应当包含一个main.yml文件,用于定义此角色用到的变量meta目录:应当包含一个main.yml文件,用于定义此角色的特殊设定及其依赖关系;ansible1.3及其以后的版本才支持;default目录:为当前角色设定默认变量时使用此目录;应当包含一个main.yml文件;# mkdir -pv ansible_playbooks/roles/{webserver,dbserver}/{tasks,files,templates,meta,handlers,vars}# cp /etc/httpd/conf/httpd.conf files/# pwd/root/ansible_playbooks/roles/webserver# cat tasks/main.yml- name: install httpd packageyum: name=httpd state=present- name: install configuretion filecopy: src=httpd.conf dest=/etc/httpd/conf/httpd.conftags:- confnotify:- restart httpd- name: start httpdservice: name=httpd state=started# cat handlers/main.yml- name: restart httpdservice: name=httpd state=restarted# pwd;ls/root/ansible_playbooksroles site.yml# cat site.yml- hosts: webserverremote_user: rootroles:- webserver# ansible-playbook site.yml九、Tagstags用于让用户选择运行或路过playbook中的部分代码。ansible具有幂等性,因此会自动跳过没有变化的部分,即便如此,有些代码为测试其确实没有发生变化的时间依然会非常的长。此时,如果确信其没有变化,就可以通过tags跳过此些代码片段。tags:在playbook可以为某个或某些任务定义一个"标签",在执行此playbook时,通过为ansible-playbook命令使用--tags选项能耐实现仅运行指定的tasks而非所有的;# cat apache.yml- hosts: webserverremote_user: rootvars:- package: httpd- service: httpdtasks:- name: install httpd packageyum: name=` package ` state=latest- name: install configuration file for httpdtemplate: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conftags:- confnotify:- restart httpd- name: start httpd serviceservice: enabled=true name=` service ` state=startedhandlers:- name: restart httpdservice: name=httpd state=restarted# ansible-playbook apache.yml --tags='conf'特殊tags:always #无论如何都会运行