2023Ansible快速入門技術(shù)原理與實戰(zhàn)_第1頁
2023Ansible快速入門技術(shù)原理與實戰(zhàn)_第2頁
2023Ansible快速入門技術(shù)原理與實戰(zhàn)_第3頁
2023Ansible快速入門技術(shù)原理與實戰(zhàn)_第4頁
2023Ansible快速入門技術(shù)原理與實戰(zhàn)_第5頁
已閱讀5頁,還剩169頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

Ansble22年ne出現(xiàn)后,以其使用簡單、功能實用等特點得到了廣泛關(guān)注,成為自動化運維工具中的冉冉新星。僅三年dnbeAnsibleLinux有最基本的了解就可以輕松讀懂本書。6章,分為以下三個部分:第一部分Ansible基本工具的講解(1章~4章Ansible的相關(guān)知識。43Ansible的基本使用第二部分roleAnsibleGalaxy的介紹(5章roleAnsibleAnsibleGalaxy代碼分享網(wǎng)站。AnsibleTower介紹(6章IV|AnsibleLinuxAnsible的管理節(jié)點來測試本書中的代碼。Ansible目前已RedHatLinuxRedHatLinux7CentOS7。 hosts: hosts:alluser:rootname:echoshell:echo{{ansible_os_family nameinstallntponDebianlinuxapt:name=gitstate=installedwhen:ansible_os_family==nameinstallntponredhatyum:name=git\h第1章Ansible介 Ansible介 Ansible解決了什么運維痛 架 Ansible的架 第2章Ansible入 安裝 Ansible管理哪些主 Ansible用命令管理主 Ansible命令的格 Ansible命令的功 Ansible用腳本管理主 執(zhí)行腳本Playbook的方 Playbook的例 Play和 Ansible模 什么是Ansible模 在Playbook腳本中使用模 Ansible模塊的特 第3章Ansible進 Ansible的配 Ansible配置文件的優(yōu)先 變 Ansible的腳本 Playbook的文件格式 執(zhí)行Playbook的命 Playbook的基本語 變 Playbook也有邏輯控制語 重用 用標(biāo)簽,實現(xiàn)執(zhí)行Playbook中的部分任 更多的Ansible模 Extra模塊的使用方 寫Playbook的原 第4章AnsiblePlaybook雜 再談Ansible變 lookup讀取文 lookup生成隨機密 lookup讀取環(huán)境變 lookup讀取Linux命令的執(zhí)行結(jié) lookup讀取template變量替換后的文 lookup讀取配置文 lookup讀取CSV文件的指定單 lookup讀取DNS解析的 更多的lookup功 過濾 過濾器對JSON的操 測試List的包含關(guān) 第5章role和Ansible role和AnsibleGalaxy的簡要介 Ansible role的放置位 當(dāng)前目錄的roles文件夾 Ansible配置文件中roles_path定義的文件 在Playbook中如何調(diào)用 通過pre_tasks和post_tasks調(diào)整role和任務(wù)的順 與when一起使用 如何寫 role的完整定 role的依 AnsibleGalaxy網(wǎng)站介 從AnsibleGalaxy網(wǎng)站上下載 演示role的創(chuàng)建和分 改造單個的Playbook為 在AnsibleGalaxy中分享 第6章Ansible 為什么要用Ansible 如何使用Ansible 總 附錄 1Ansible1AnsibleAnsible1章Ansible介紹|PAGEPAGE2|AnsibleAnsibleHostSSH登錄的主機,所以它既可以是遠程虛擬機或物理機,也可以是本地主機。Ansible通過SSHAnsible實現(xiàn)批量自動化操作。AnsibleAnsible解決了如何大批量、自動化地實現(xiàn)系統(tǒng)配置、應(yīng)用部署、命令和服務(wù)操作的問題。2章會講到具體的配置方法。連接方式AnsibleSSH連接被管理的主機來AnsibleRedHatLinux、DebianLinux以及Windows主機。Ansible1.1所示。1.1Ansible◎SSHPC主機SSH◎SSH私鑰,或者復(fù)制給別人,那么對于◎◎AnsibleTowerAnsible管理節(jié)點,它向管理員提供網(wǎng)頁AnsiblePlaybook?!颉駻nsiblePlaybook◎此外,AnsibleTowerPlaybook的執(zhí)行狀況,以便于統(tǒng)計AnsibleTower1.21.2AnsibleTower2Ansible2AnsibleAnsibleAnsibleAnsible2章Ansible入門|PAGEPAGE10|AnsibleRedHatLinuxWindowsMacRedAnsible$$Redhat/CentOSLinux上,Ansible目前放在的epel$FedoraAnsible$sudoyuminstallepel-$sudoyuminstallansible-Ansible$$SSH$ssh-$SSHSSH$ssh-copy-id$SSH$ssh-keyscanremote_servers>>SSHSSH命令,既不需要輸入密碼,也不會提醒你存 $ssh SSHPython2.4以上即可,RedHatLinux一般安裝方式都是默認安裝的。主機目錄(HostInventory,又稱主機清單)Ansible需要管理哪些可以修改為其他文件,第3章Ansible進階中將介紹使用其他文件路徑作為主機目錄文HostsHostsAnsibleansibleansible<host-pattern>Ansible命令的語法,介紹完模塊(2.5節(jié))后,就可以理解語法了。先從感觀Ansible命令行的功能。Ansible$ansible$ansibleall-mping-uBash的同名用戶,在遠程主機執(zhí)行“echohello$ansible$ansibleall-a"/bin/echo“Web$$ansibleweb-mcopy-a"src=/etc/hosts$$ansibleweb-myum-a"name=acme$$ansibleall-muser-a"name=foopassword=<cryptedpasswordGit$$ansibleweb-mservice-a"name=httpd10$ansible$ansiblelb-a"/sbin/reboot"-f$$ansibleall-mAnsible為了避免重復(fù)地輸入命令,Ansible提供了腳本功能。AnsiblePlaybook,使YAMLymlyaml為后綴。LanguageYAML不是一種標(biāo)記語言的遞歸縮寫。 $ansible-palybook ◎hostsIPall◎remote_user◎vars◎tasks:PlaybookActionAction? module: ?yum、copy這樣的命令,2.5節(jié)會介紹?!騢anders:PlaybookEventAction觸發(fā)時才會執(zhí)行。但多次◎Apache◎httpd,并保證復(fù)制文件后,Apache◎index.html◎Apache-hosts:webhttp_port:max_clients:200remote_user:root-name:ensureapacheisatthelatestyum:yum:pkg=httpdname:Writetheconfiguration-restartname:Writethedefaultindex.htmltemplate:src=templates/index.html.j2 name:ensureapacheisrunningservice:name=httpdstate=startedname:restartservice:name=httpd如果讀者對YAMLJSONdeploy.yml格式轉(zhuǎn)化為"hosts":"web","vars":{"http_port":"max_clients":"remote_user":"root","tasks":["name":"ensureapacheisatthelatestversion","yum":"pkg=httpdstate=latest""name":"Writetheconfiguration"template":"src=templates/httpd.conf.j2dest=/etc/httpd/conf/"notify":"restart"name":"Writethedefaultindex.html"name":"ensureapacheisrunning","service":"name=httpdstate=started""handlers":"name":"restart"service":"name=httpd\hPlay-hosts:webremote_user:root-name:ensureapacheisatthelatestyum:pkg=httpdPlaybookweb(組)HTTPlb(組)MySQL并放在一個文件中。 hosts:webremote_user:root name:ensureapacheisatthelatestversionyum:pkg=httpdstate=latestMySQLServer的 hosts:lbremote_user:rootname:ensuremysqldisatthelatestyum:pkg=mariadbAnsibleAnsibleAnsibleAnsible模yum、copy、template等。模塊的詳細用法可以查閱下面的文檔,也可以通過命令“ansible-doc<module_name>”查\h◎-m◎-a$$使用模塊copy復(fù)制管理員節(jié)點文件/etc/hosts到所有遠程主機$ansibleall-mcopy-a"src=/etc/hosts$使用模塊yumWebhttpd$ansibleweb-myum-a"name=httpdPlaybook腳本中,tasksActionAction◎◎ name:ensureapacheisatthelatestversionyum:pkg=httpdstate=latestname:writetheapacheconfigtemplate:src=templates/httpd.conf.j2 name:ensureapacheisrunningservice:name=httpdstate=started?Playbook中調(diào)用。??\h?Python。?◎ping:pingAnsiblepong◎debugLinuxecho?◎copy◎template◎file?◎user◎yum:RedHatLinux◎service◎firewalld?◎<>|”和“&<>pingpingSSHPython版本能否滿足pong,表示成功。ansibleservers-mansibleservers-mdebugLinuxecho?-msg:"System{{inventory_hostname}}-msg:"System{{inventory_hostname}}hasgateway{{ansible_default_ipv4.gateway}}"TASKTASK[debug]ok:[localhost]=>"msg":"Systemlocalhosthasgateway?◎--name:Displayallvariables/factsknownforavar:TASKTASK[Displaypartofvariables/factsknownforahost]ok:[localhost]=>{◎shell:shell:register:var:*****changed:*****ok:[localhost]=>{"result":{"changed":true,"cmd":"/usr/bin/uptime","delta":"end":"2017-01-01"rc":"start":"2017-01-01"stderr":"stdout":"21:30:02up12:38,8users,loadaverage:1.13,"stdout_lines":"21:30:02up12:38,8users,loadaverage:1.13,1.31,"warnings":copy從當(dāng)前的機器上復(fù)制靜態(tài)文件到遠程節(jié)點上,并且設(shè)置合理的文件權(quán)限。注意,copy模cheku;hg。?mode設(shè)置權(quán)限可以是數(shù)字,當(dāng)然也可以是符號的形式"u=rw,g=r,o=r"和"u+rw,g-wx,--src:/srv/myfiles/foo.confdest:/etc/foo.confowner:foogroup:mode:?-src:sudoersdest:/tmpbackup:-src:sudoersdest:/tmpbackup:?visudo-cfvalidate參數(shù)接需要驗證的命令。一般需要驗證復(fù)制后的文件,所以%s都可以指代復(fù)制后copyvalidatevisudo-cf--src:/mine/sudoersdest:validate:'visudo-cftemplatetemplate模塊。Apacheindex.html。index.html里面需要顯IPtemplate。PythonJinja2Jinja2?<divclass="block"style="height:<div<h1>#46<divclass="block"style="height:<div<h1>#46<p>Servedby{{ansible_hostname}}({{ansible_default_ipv4.address}}).</p>?-name:Writethedefaultindex.htmltemplate:src=templates/index.html.j2index.html.j2使用的兩個變量-name:Writethedefaultindex.htmltemplate:src=templates/index.html.j2?httpd.conf.j2HTTP端口,這時我們就需要用到ServerRootServerRootListen{{http_port-hosts:http_port:8080remote_user:root-name:Writetheconfiguration-hosts:http_port:8080remote_user:root-name:Writetheconfigurationtemplate:src=templates/httpd.conf.j2?-src:etc/ssh/sshd_config.j2dest:/etc/ssh/sshd_config.j2owner:rootgroup:rootmode:'0600'-src:etc/ssh/sshd_config.j2dest:/etc/ssh/sshd_config.j2owner:rootgroup:rootmode:'0600'validate:/usr/sbin/sshd-tbackup:file?-path:/etc/foo.confowner:foomode參數(shù)既可以直接賦值數(shù)字權(quán)限(0-path:/etc/foo.confowner:foogroup:group:mode:#mode:#mode:"u+rw,g-wx,o-?-src:/file/to/link/todest:/path/to/symlinkowner:foogroup:state:-src:/file/to/link/todest:/path/to/symlinkowner:foogroup:state:?touch--path:/etc/foo.confstate:touchmode:?##createadirectoryifitdoesn't-path:state:mode:user?◎johnduid1040primarygroup--name:johndcomment:name:johndcomment:"JohnDoe"uid:1040group:◎jamesgroup--name:jamesshell:/bin/bashgroups:append:?刪除賬戶。--name:state:absentremove:yes◎jsmith2048SSH密鑰,放在~jsmith/.ssh/id_rsa--name:jsmithgenerate_ssh_key:yesssh_key_bits:2048ssh_key_file:◎--name:james18shell:/bin/zshgroups:developersexpires:yumyum模塊是用來管理RedHat系的Linux上的安裝包的,包括RHEL、CentOSFedora21及以下版本。Fedora從版本22開始就使用dnf,推薦使用dnf模塊來進行安裝包的操作。?◎--name:installthelatestversionofApachename:state:◎--name:installonespecificversionofApachename:httpd-2.2.29-state:◎httpd--name:removetheApachepackagename:state:◎repotesting--name:installthelatestversionofApachefromthetestingreponame:enablerepo:state:? name:installthe'Developmenttools'packagegroupname:"@Developmentstate: name:installthe'Gnomedesktop'environmentgroupname:name:"@gnome-desktop-state:?--name:installnginxrpmfromalocalfilestate:?--name:installthenginxrpmfromaremoterepo\hstate:service?◎--name:state:◎--name:state:◎--name:state:◎--name:state:?--name:enabled:?--name:networkstate:restartedargs:eth0firewalldfirewalldfirewalld規(guī)則。firewalld中有正在運行的規(guī)則和永久的規(guī)則,firewalld模塊都支持。firewalldfirewalld0.2.11?-firewalld:service:https-firewalld:service:httpspermanent:truestate:-firewalld:zone:dmzservice:httppermanent:state:?--port:permanent:permanent:truestate:-port:161-permanent:state:?rich_rule:'ruleservicename="ftp"auditlimitvalue="1/m"accept'permanent:truestate:source:/24zone:internalstate:enabledzone:trustedinterface:eth2permanent:truestate:enabledmasquerade:yesstate:enabledpermanent:truezone:shellbnhupy議不要使用shell或者command這樣通用的命令模塊。因為通用的命令模塊不會根據(jù)具體操作的特點進行狀態(tài)(status)判斷,所以當(dāng)沒有必要再重新執(zhí)行的時候,它還是會重新執(zhí)行一遍。?<>|&◎支持$home -name:test shell:shell:echo"Test1">◎支持“&&--shell:servicejbossstart&&chkconfigjboss◎支持“>>--shell:echofoo>>?◎--shell:somescript.sh>>◎--shell:somescript.sh>>chdir:◎somelog.txt--shell:somescript.sh>>somelog.txtchdir:creates:◎bash--shell:cat</tmp/\*txtexecutable:command$HOM“<>|?◎--command:/sbin/shutdown-t◎都可以在執(zhí)行命令前改變目錄,并僅在某個文件(database)--command:/usr/bin/make_database.sharg1chdir:creates:?◎command -command:/usr/bin/make_database.sharg1arg2◎”和“>>下面的寫法是無法創(chuàng)建/tmp/test3和/tmp/test4--name:testcommand:echo"test3">~/tmp/test3&&echo"test4">3Ansible3AnsibleAnsibleAnsible3章Ansible進階|PAGEPAGE100|AnsibleAnsible =/etc/ansible/hosts =/usr/share/my_modules/ =$HOME/.ansible/tmp =inventorylibrar =/etc/ansible/hosts =/usr/share/my_modules/ =$HOME/.ansible/tmp =accelerate_portaccelerate_portaccelerate_port=accelerate_timeout=accelerate_connect_timeout=Ansible后,通過/etc/ansible/ansible.cfg文件的內(nèi)容和注釋就可以了解到所有可以配ansible.cfg文件。\hANSIBLE_CONFIG(anenvironmentansible.cfg(inANSIBLE_CONFIG(anenvironmentansible.cfg(inthecurrent.ansible.cfg(inthehomeAnsible1.5ansible.cfgansible.cfg(inthecurrentANSIBLE_CONFIG(anenvironment.ansible.cfg(inthehome什么是主機清單(HostInventory)Ansible需要管理哪些主機,以及這些主=?=?◎利用參數(shù)-i$$ansible-playbook-ihosts◎利用參數(shù)--inventory-file$$ansible-playbook--inventory-filehosts單的分組方法,[]southeast組,southeastatlantareleighAnsibleInventoryansible_connection=sshansible_user=rootansible_connection=ssh3.13.1SSHsmart、sshSSHSSHkey的SSHprivatekey通過配置本參數(shù)來指定SFTP、SCP和SSH\hAnsibleNTP服務(wù)器、代理服務(wù)器和數(shù)據(jù)庫地址為例?!騢ost1http_port=80host2http_port=303◎假設(shè)主機清單文件為/etc/ansible/hosts,那么相關(guān)的HostGroup變量可以放在和'.json'YMALJSON/etc/ansible/group_vars/etc/ansible/group_vars/raleigh'.yml'、'.yaml'和ntp_server:database_server:Ansible會讀取這個目錄下面所有文件的內(nèi)容。在下面的例子中,db_settingscluster_settingsAnsible讀取。Ansible的腳本PlaybookAnsibleYAML格式。YAMLJSON類似,是一種數(shù)YAML語言的基本知識。??List-?Directory:key:key:keyvalue#An#Anemployeerecordname:MartinD'vloperjob:Developerskill:--name:MartinD'vloperjob:Developername:TabithaBitumenjob:Developer?foo:foo:"somebodysaidIshouldputacolonhere:soIfoo:foo:"{{variableAnsiblePlaybook呢?Ansible提供了一個單獨的命令:ansible-playbook,ansible-playbook的使用方法如下?!騊laybook$$ansible-playbook◎ansible-playbookansible-playbookplaybook.yml--◎(hostsansible-playbookansible-playbookplaybook.yml--list-◎ansible-playbookansible-playbookplaybook.yml-f-Playbook?◎◎◎?◎?◎hosts:user:http_port:max_clients: name:ensureapacheisatthelatestversionyum:pkg=httpdstate=latestname:writetheapacheconfigtemplate:src=/srv/httpd.j2dest=/etc/httpd.confrestart name:ensureapacheisrunningservice:name=httpdstate=startedname:restartservice:name=httpd3.23.2 yes或者became一起用,指可以為 ansible-playbookdeploy.yml--ask-become- ◎任務(wù)(task)Playbook會中止?!颉騨ame屬性,這是供人讀的,沒有實際的操作。然后會在命令行里?-name:makesureapacheisrunningservice:name=httpd-service:name=httpdnamePlaybookTASK:TASK:[makesureapacheisrunning]changed:[yourhost]TASK:[servicename=httpdstate=running]TASK:[servicename=httpdstate=running]changed:?-name:makesureapacheisrunningservice:name=httpd-name:Copyansibleinventoryfiletocopy:src=/etc/ansible/hostsdest=/etc/ansible/hostsowner=rootgroup=rootmode=0644YML-name:Copyansibleinventoryfiletoclientsrc:/etc/ansible/hostsdest:/etc/ansible/hostsowner:rootgroup:mode:?◎Actionchanged◎Actionokchecksum_src=checksum_destchecksum_src=checksum_dest=ifchecksum_src!=checksum_destorchanged=Truechanged=copy-name:Copythecopy:src=/etc/hosts3.13.1任務(wù)的狀態(tài)是3.23.2任務(wù)的狀態(tài)是3.3?EventhandlerPlaybookEventHandlershandlerhandler與任務(wù)不同,任務(wù)會默?handlerApacheApache用(notify)handler,那么只執(zhí)行一次。Apache hosts:lbremote_user:rootrandom_number1:"{{10000|random}}"random_number2:"{{10000000000|random}}" name:Copythe/etc/hoststo/tmp/hosts.{{random_number1}}copy:src=/etc/hostsdest=/tmp/hosts.{{random_number1}}callinevery name:Copythe/etc/hoststo/tmp/hosts.{{random_number2}}copy:src=/etc/hostsdest=/tmp/hosts.{{random_number2}}callinevery-name:callineverydebug:msg="callineveryaction,butexecuteonlyonechangedhandlerchangednotifyhandler的執(zhí)行。◎◎/ hosts:lbremote_user:rootrandom_number:"{{10000|random}}" name:Copythe/etc/hosts hosts:lbremote_user:rootrandom_number:"{{10000|random}}" name:Copythe/etc/hoststo/tmp/hostscopy:src=/etc/hostsdest=/tmp/hostscallby name:Copythe/etc/hoststo/tmp/hosts.{{random_number}}copy:src=/etc/hostsdest=/tmp/hosts.{{random_number}}callbyname:callbydebug:msg="callfirstname:callbydebug:msg="callby? hosts:lbremote_user:rootgather_facts:norandom_number1:"{{10000|random}}"random_number2:"{{ hosts:lbremote_user:rootgather_facts:norandom_number1:"{{10000|random}}"random_number2:"{{10000000000|random}}" name:Copythe/etc/hoststo/tmp/hosts.{{random_number1}}copy:src=/etc/hostsdest=/tmp/hosts.{{random_number1}}definethe3nd name:Copythe/etc/hoststo/tmp/hosts.{{random_number2}}copy:src=/etc/hostsdest=/tmp/hosts.{{random_number2}}definethe2nddefinethe1nd name:definethe1ndhandlerdebug:msg="definethe1ndhandler" name:definethe2ndhandlerdebug:msg="definethe2ndhandler"name:definethe3nddebug:msg="definethe3nd?????PlaybookPlaybookvars關(guān)鍵字自定義變量,使用時用?-hosts:webhttp_port:80remote_user:root--hosts:webhttp_port:80remote_user:root-name:insertfirewalldruleforfirewalld:port={{http_port}}/tcppermanent=truestate=enabled?-hosts:webremote_user:root-獨的文件中,通過關(guān)鍵字“-hosts:webremote_user:root--name:insertfirewalldruleforfirewalld:port={{http_port}}/tcppermanent=truestate=enabledhttp_port:http_port:?field1:onefield2:field1:onefield2:?YAML的陷阱是指某些時候YAML和AnsiblePlaybook的變量語法不能在一起好好工作了。YAMLYMAL語法錯誤,就可以嘗試加入引號來解決。--hosts:app_serversapp_path:{{base_path"{"--hosts:app_serversapp_path:"{{base_path遠程主機的系統(tǒng)變量PlaybooksetupFacts信息可以直接以變量的形式 $ansibleall-msetup-u PlaybookFacts hosts:alluser:rootname:echoshell:echo{{ansible_os_family nameinstallntponDebianlinuxapt:name=gitstate=installedwhen:ansible_os_family== nameinstallntponredhatlinuxyum:name=gitstate=presentwhen:ansible_os_family==?"ansible_ens3":{"active":true,"device":"ens3","ipv4":{"address":"netmask":"network":"ipv6":"address":"2620:52:0:42c0:5054:ff:fef2:e2a3","prefix":"64","scope":"address":"fe80::5054:ff:fef2:e2a3","prefix":"64","scope":"macaddress":"52:54:00:f2:e2:a3","module":"8139cp","mtu":"promisc":false,"type":"ether"◎{{{{ansible_ens3["ipv4"]["address"]◎{{{{ansible_ens3.ipv4.address?-hosts:gather_facts:-hosts:gather_facts:template文件中使用的變量感到困惑,所以在這里再重新強調(diào)下它?PlaybooktemplateFactstemplateInventoryHostGroupPlaybook中template文件中使用。Playbook hosts:webhttp_port:defined_name:"HelloMynameisJingjng"remote_user:root name:ensureapacheisatthelatestversionyum:pkg=httpdstate=latestname:Writetheconfigurationtemplate:src=templates/httpd.conf.j2dest=/etc/httpd/conf/httpd.confrestartname:Writethedefaultindex.htmltemplate:src=templates/index2.html.j2 name:ensureapacheisrunningservice:name=httpdstate=startedname:restartservice:name=httpd?AnsiblePythontemplateJinja2Jinja2語言的語法有太多的了解,只需要知道{{}}是用來引用變量的就可以了。◎{{ansible_hostname{{ansible_default_ipv4.address◎{{defined_name<divclass="block"style="height:<div<h1>#46Demo{{defined_name<p>Servedby{{ansible_hostname}}({{ansible_default_ipv4.address}}).</p> hosts: hosts:web shell:lsregister:resultignore_errors:Trueshell:echo"{{result.stdoutwhen:when:result.rc==-debug:msg="{{result.stdoutdebug模塊一起使用,這樣可以得到更多的關(guān)于執(zhí)行錯誤的信息,以幫助?-hosts:'{{hostsremote_user:-hosts:'{{hostsremote_user:'{{user-Playbook中的值,未在命令行中的傳入值也不會報錯。-hosts:localhostremote_user:-hosts:localhostremote_user:roottest_name:"Valueinplaybook-debug:msg="{{test_name?JSON1',ansible-playbookansible-playbooke33_var_in_command.yml--extra-vars◎whenif◎loopwhile◎block?when語句實現(xiàn)。DebianLinux-name:"shutdownDebianflavoredsystems"command:/sbin/shutdown-tnowwhen:ansible_os_family== command:/bin/falseregister:resultignore_errors:Truecommand:whenwhen:command:when:command:when:-hosts:web-debug:msg="onlyonRedHat7,derivatives,and>=?epicepicepic:when-shell:echo"Thiscertainlyiswhen:-shell:echo"Thiscertainlyisn'twhen:not-shell:echo"I'vegot'{{foo}}'andamnotafraidtousewhen:foois--fail:msg="Bailingout.thisplayrequireswhen:barisnot-command:echo{{item}}with_items:[0,2,4,6,8,10]when:item>5?--include:when:"'reticulatingsplines'in?--hosts:webservers-{role:debian_stock_config,when:ansible_os_family=='Debian'Loop?name:name:addseveraluser:name={{item}}state=presentgroups=wheelsomelist:["testuser1","testuser2"]-name:addseveraluser:name={{item}}state=presentwith_items:“with_itemslist類型變量,不僅支持簡單的字符串列表,如果你有一個哈希name:name:addseveraluser:name={{}}state=presentgroups={{item.groups{name:'testuser1',groups:'wheel'{name:'testuser2',groups:'root'?name:name:giveusersaccesstomultiplemysql_user:name={{item[0]}}priv={{item[1]}}.*:ALLappend_privs=yes['alice','bob'['clientdb','employeedb',name:name:giveusersaccesstomultiplemysql_user:name={{item.0}}priv={{item.1}}.*:ALLappend_privs=yes['alice','bob'['clientdb','employeedb',?name:AliceAppleworthtelephone:123-456-7890name:BobBananaramatelephone:987-654-3210-name:Printphone ({{item.value.telephone}})"with_dict:?with_fileglob#firstensureourtargetdirectoryfile:dest=/etc/fooapp#copyeachfileoverthatmatchesthegivencopy:src={{item}}dest=/etc/fooapp/owner=root-Block yum:name={{item}}state=installedtemplate:src=templates/src.j2service:name=barstate=startedwhen:ansible_distribution==become:truebecome_user:root-debug:debug:msg='iexecutecommand:debug:msg='ineverexecute,causedebug:msg='Icaughtancommand:debug:msg='Ialsoneverexecute:-debug:msg="thisalwaysPython等編程語言中的包(Package?!騣ncludePlaybook◎rolePlaybookAnsiblePlaybook的方式。includePlaybook過于臃腫,使用戶更關(guān)注于整體的架構(gòu),而不是實現(xiàn)的細節(jié)上。?includeinclude#possiblysavedas-name:insertfirewalldruleforfirewalld:port=80/tcppermanent=truestate=enabledmain.ymlinclude-include:?includeinclude文件中◎includeinclude中,使用portport-name:insertfirewalldrulefor◎includePlaybookinclude:tasks/firewall.ymlinclude:tasks/firewall.ymlinclude:tasks/firewall.ymlYAMLinclude:wp_user:timmy◎JSON-{include:wordpress.yml,wp_user:timmy,ssh_keys:['keys/one.txt','keys/two.txt']}◎Playbook中已經(jīng)定義了的參數(shù),就不需要再顯示傳入值了,可以直接寫成-hosts:port:3206remote_user:root-include:?◎handlerincludehandlerinclude-include:Ansible1.9及之前的版本是不能調(diào)用include里面的handlerAnsibleinclude里面的handlerAnsible hosts:lbuser:rootgather_facts:norandom_number:"{{10000|random}}" name:Copythe/etc/hoststo hosts:lbuser:rootgather_facts:norandom_number:"{{10000|random}}" name:Copythe/etc/hoststo/tmp/hosts.{{random_number}}copy:src=/etc/hostsdest=/tmp/hosts.{{random_number}}restartrestartapacheinincludeinclude:name:restartdebug:msg="Thisisthehandlerrestart◎Ansible允許全局(Plays)include。然而這種使用方式并不推薦,因為它不includePlaybook的參數(shù)也無法使用。--name:thisisaplayatthetoplevelofahosts:remote_user:remote_user:root-name:sayhitags:fooshell:echoinclude:include:include:◎includeincludeAnsible2.0includeYAML,然而這樣的用法有很多的限制,不夠成熟,可能在更Ansible中又被去掉了,學(xué)習(xí)和維護成本很高。所以在需要使用更靈活的重用機制時,role。rolePlaybookPackageApachehttpd.confindex.html的模板文件,以及handler文件實現(xiàn)重啟功能。這些文件都可以放在一個role里面,以供不同的Playbook文件重用。AnsiblePlaybookroleroleAnsible(https://galax.ansible.co/?role的目錄結(jié) site.yml中調(diào)用├──├──│└──├──│└──├──│└──├──│└──├──├──├──├──│└──└──├──└──

hosts:-◎rolesrole/x/tasks/main.ymlPlay◎roles/x/handlers/main.ymlhandlerPlay◎role/x/vars/main.ymlPlay◎role/x/defaults/ain.ymlPlay◎role/x/meta/main.ymlrolePlay◎此外,下面的文件不需要絕對或者是相對路徑,和放在同一個目錄下的文件一樣,直copyscriptroles/x/files/templateroles/x/templatesincluderoles/x/tasksroleAnsible中稍高級的使用方法。role。在后面的章節(jié)中,我們會通過具體的示role所需的知識。?roleroles/myrole/tasks/main.yml中,使用-name:usedebug:msg="{{param?main.yml中可以用myrole hosts:webservers{role:myrole,param:'Callsome_roleforthe1sttime'{role:myrole,param:'Callsome_roleforthe2ndtime'-hosts:webservers-role:paramparam:'Callsome_roleforthe1st-role:param:'Callsome_roleforthe2nd?param:param:"Iamthedefault hosts:webservers{role:myrole,param:'Iamthevaluefromexternal'role6?下面的例子中,myroleRedHat-hosts:webservers-{role:myrole,when:"ansible_os_family=='RedHat'"-hosts:webservers-role:when:"ansible_os_family==?Playbookrole和任務(wù),那么它們的調(diào)用順序是怎樣的呢?pre_tasksroletaskspost_tasks hosts:lbuser:name:shell:echo{role:some_rolename:shell:echo'stillname:shell:echoPLAYPLAY[lb]ok:TASK[pre]changed:ok:[rhel7u3]=>{"msg":"Imsomerole"TASK[task]changed:TASK[post]changed:PLAYRECAP : 解決方案呢?Playbook提供了標(biāo)簽(tags)可以實現(xiàn)部分運行。 yum:name={{item}}state=installedname:copytemplate:src=templates/httpd.conf.j2name:copytemplate:src=templates/index.html.j2ansible-playbookansible-playbookansible-playbookansible-playbookexample.yml--tagsansible-playbookansible-playbookexample.yml--skip-tags?Playbookalwaysalways標(biāo)簽所對應(yīng)的任 debug:msg="Alwaysprintthisdebugmessage"- yum:name=state=installed template:src=templates/httpd.conf.j2dest=/etc/httpd/conf/httpd.confpackagesalwaysansible-playbookansible-playbooktags_always.yml--tags?“tagged debug:msg="Iamnottagged"-debug:msg="Iamnot為“taggedansible-playbooktags_tagged_untagged_all.ymlansible-playbooktags_tagged_untagged_all.yml--tagsansible-playbookansible-playbooktags_tagged_untagged_all.yml--tagsansible-playbookansible-playbooktags_tagged_untagged_all.yml--tagsincluderoleinclude--include:tags:role-{role:webserver,port:5000,tags:['web','foo']Ansible◎介紹兩類模塊:CoreExtra◎Extra◎ModuleModule比如,yumCorearchive就是一個ExtraCore模塊(核心模塊◎Ansible◎◎Extra模塊(額外模塊◎◎◎bugCoreExtraAnsibleCore模塊中,方便用戶的Playbook運行時,如果報錯但沒有相應(yīng)的模塊,那么你只要知道問題可能出ExtraExtraExraPlaybook中使用。配置ExtraCore模塊的使用方法相同。?gitgitclone/ansible/ansible-modules-? 1:修改Ansible默認配置文件/etc/ansible/ansible.cfg。Ansible 2:修改Ansibleansible.cfgAnsiblePlaybookansible.cfglibrarylibrary=library/ansible-modules-$$echo>>~/.bashrcexportANSIBLE_LIBRARY=/project/demo/demoansible/library/ansible-module-$sourceansible-docansible-docCoreyumansible-docansible-docExtraExtraansible-docansible-docAnsiblePlaybookPlaybook◎includerole◎參考別人的Playbook之前,不如先參考一下別人的成果吧。AnsiblePlaybookPlaybookAnsible此外,AnsiblePlaybookAnsible用戶自己上傳44Ansiblelookup4章AnsiblePlaybook雜談|PAGEPAGE74|Ansible太重要了。本章將對所有的Ansible◎GlobalAnsible◎PlayPlay(PlaybookPlay構(gòu)成Playvarsinclude_varsroledefault/main.ymlvars/main.yml◎Host4.1roledynamicinventoryinventoryinventoryinventoryplaybookplaybookhostregisteredplayplayplayrolevariablesandincludeblocktaskextraroledefaults變量外,其他變inventoryPlay中的變量覆蓋,Playbookhost變量覆蓋,hosttask變量覆蓋。變量優(yōu)先級最高的extra變量,又叫命令行變量,只在某一次執(zhí)行時生效的變量優(yōu)先級最高。rolerolexroles/x/defaults/main.yml#file:#ifnotoverriddenininventoryorasaparameter,thisisthevaluethatwillbeusedhttp_port:inventoryinventory#file:#file:host1ansible_port=5555inventorygroup_varsgroup同名的文件中。##file:#file:/etc/ansible/group_vars/all#thisisthesitewidedefaultntp_server:default-#file:ntp_server:boston-group1group1ntp_server變量。因為該變量作用域更精inventoryhost_varsinventoryinventory文件host_varshost同名的文件中定義。##file:host1inventoryhost_varsHost#file:ntp_server:playbook#file:ntp_server:PlaybookPlaybook#file:ntp_server:playbook#file:ntp_server:Playbook文件同級的子目錄Host-vars#file:ntp_server:hostansiblehost1–mAnsibleansiblehost1–mplay--hosts:http_port:defined_name:"HelloMynameisplay hosts:allremote_user:rootgather_facts:notest:name:prompt:"whatisyourname:prompt:"whatisyourfavoritecolor?"debug:msg="Hello{{name}},yourfavoritecolorisplay-hosts:--hosts:-registered shell:lsregister:resultignore_errors:Truedebug:msg="{{result.stdoutset_factsset_factsFacts--one_fact:"something"other_fact:"{{local_var}}"roleandincluderolevars#file:#thiswillabsolutelybeusedinthishttp_port:roleincluderole/x/tasks/main.ymlincludeinclude#file:#thiswillabsolutelybeusedinthishttp_port:#file:-name:Addapachevariablesinclude_vars:"apache.yml"blockPlaybookblockyum:name={{service}}service:name={{status}}state=startedservice: status: task-debug:msg="{{service}}isservice:httpdstatus:runningextra ansible...-e lookup就能解決這類難題,lookupAnsible管理節(jié)點上文件系統(tǒng)的文件內(nèi)Ansible變量中,也可以讀取配置的數(shù)據(jù)庫中的內(nèi)容。-hosts:allremote_user:rootgather_facts:falsecontents:"{{lookup('file','data/plain.txt')lookupAnsible-hosts:allremote_user:rootgather_facts:falsecontents:"{{lookup('file','data/plain.txt')-debug:msg="thevalueofdata/plain.txtis{{contentsTASK[debug]ok:[jshi-test-02.rhev]=>"msg":"thevalueofdata/plain.txtisHello,YouwillmyPLAYRECAP : lookup-hosts:allremote_user:root-hosts:allremote_user:rootpassword:password:"{{lookup('password','/tmp/password/kittylength=5')-debug:[jshi@jjshi[jshi@jjshi10_lookup]$ansible-playbookPLAY[all]ok:[jshi-test-02.rhev]=>{"password":"bsl82"PLAYRECAP : envlookupLinux-hosts:allremote_user:root-debug:msg="{{lookup('env','HOME')}}isanenvironmentTASKTASK[debug]ok:[jshi-test-02.rhev]=>"msg":"/home/jshiisanenvironmentpipelookupLinuxAnsible-hosts:allremote_user:root-debug:msg="{{lookup('pipe','date')}}istherawresultofrunningthiscommand"TASKTASK[debug]ok:[jshi-test-02.rhev]=>"msg":"SatFeb1121:00:58CST2017istherawresultofrunningthis-hosts:allremote_user:rootname:-debug:msg="{{-hosts:allremote_user:rootname:-debug:msg="{{lookup('template','data/some_template.j2')}}isavaluefromevaluationofthistemplate"IIamthetemplatefortestlookuptemplate,andmynameis[jshi@jjshi[jshi@jjshi10_lookup]$ansible-playbookPLAY[all]ok:[jshi-test-ok:[jshi-test-02.rhev]=>"msg":"Iamthetemplatefortestlookuptemplate,andmynameisCrystal\nisavaluefromevaluationofthistemplate"PLAYRECAPjshi-test-02.rhev: lookup支持讀取兩種類型的配置文件:iniJavaproperties·。下面分別介紹這兩種文件#Myproductioninformation#My#Myproductioninformation#Myintegrationlookup hosts:allremote_user:rootmsg:"Userinintegrationis{{lookup('ini','usersection=integrationfile=data/users.ini')}}"msg:"Userinproductionis{{lookup('ini','usersection=productionfile=data/users.ini')}}"TASKTASK[debug]ok:[jshi-test-02.rhev]=>"msg":"Userinintegrationisok:[jshi-test-02.rhev]=>"msg":"UserinproductionisProperties-hosts:remote_user:remote_user:-debug:msg="is{{lookup('ini','file=data/perties')ok:[jshi-test-02.rh

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論