運維工具:
OS provisioning(PXE(dhcp,tftp,ftp|http);cobbler(repository,distribution,profile));
OS config(puppet;saltstack;func);
task execute(fabric;func;saltstack);
deployment(fabric);
注:
dnsmasq替代dhcp,dnsmasq(可用于嵌入式環境,提供dhcp、dns服務);
cobbler若配置自身管理dhcp則會啟動dnsmasq服務;
<a href="https://s5.51cto.com/wyfs02/M01/00/09/wKiom1mVNJSwP9hpAABJoMDCGqI904.jpg" target="_blank"></a>
分類:
agent(puppet,saltstack,func);
agentless(ansible,fabric;基于ssh service);
www.ansible.com
Ansible, an open source community project sponsored by Red Hat, is the simplest way to
automate IT. Ansible is the only automation language that can be used across entire IT teams– from systems and network administrators to developers and managers. Ansible by Red Hat provides enterprise-ready solutions to automate your entire application lifecycle – from servers to clouds to containers and everything inbetween. Ansible Tower by Red Hat is a commercial offering that helps teams manage complex multi-tier deployments by adding control, knowledge,and delegation to Ansible-powered environments.
http://docs.ansible.com/ansible/latest/intro_installation.html
properties:
minimal learning curve,auditability;
no bootstrapping;
no DAG ordering,fails fast;
no agents(other than sshd),0 resourceconsumption when not in use;
no server;
no additinal PKI;
modules in any lanaguage;
YAML,not code;
SSH by default;
strong multi-tier solution;
特性:
基于python實作(paramiko,PyYAML,jinja2三個子產品);
部署簡單,agentless;
預設使用ssh協定(基于密鑰認證(ansible預設);也可在inventory檔案(/etc/ansible/hosts)中指定,如172.17.101.31 ansible_ssh_user=ane ansible_ssh_pass=ane123);
主從模式(master(ansible,ssh client),slave(ssh server));
支援自定義子產品(支援各種程式設計語言);
playbook;
基于“子產品”來完成各種“任務”;
ansible architecture:
<a href="https://s3.51cto.com/wyfs02/M02/9E/B9/wKioL1mVNS6Q4VScAACokD7z0UM476.jpg" target="_blank"></a>
ansible核心元件:
ansible core;
host inventory;
core modules;
custom modules;
playbook(YAML,jinja2);
connect plugin;
YAML是一個可讀性高的用來表達資料序列的格式,YAML參考了其它多種語言(C、XML、python、perl、電子郵件格式的RFC2822等),clark evans在2001年首次發表了這種語言,另ingy dot net與oren ben-kiki也是這種語言的共同設計者;
YAML Ain't Markup Language,即YAML不是XML;
在開發這種語言時,YAML其實意思是:Yet Another Markup Language,仍是一種标記語言;
YAML的文法和其它語言類似,并可簡單表達清單、散清單、标量等資料結構,其結構structure通過空格來展示,list清單(也稱序列sequence)裡的項用-,dictionary字典(也稱map)裡的鍵值對用:分隔,擴充名通常為*.yml;
可讀性好,易于實作;
和腳本語言的互動性好;
使用實作語言的資料模型,有一個一緻的資料模型;
可基于流來處理;
表達能力強;
擴充性好;
key-value對和縮進來表式;
例:
name: John Smith
age: 41
gender: Male
spouse:
name: Jane Smith
age: 37
gender: Female
children:
- name: Jimmy Smith
age: 17
gender: Male
- name: Jenny Smith
age: 13
gender: Female
例(list中的所有元素用-開頭):
- apple
- orange
- strawberry
- mango
例(dictionary通過key: value進行辨別):
name: Example Developer
job: Developer
skill: Elite
也可将key: value放置于{}中:
{name: Example Developer,job: Developer,skill: Elite}
ansible中YAML基礎元素:
變量variable;
inventory;
條件測試;
疊代;
操作:
]# uname -rm
2.6.32-431.el6.x86_64 x86_64
]# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.5(Santiago)
]# yum list all *ansible* #準備epel源;
ansible.noarch 2.3.1.0-1.el6 epel
ansible-doc.noarch 2.3.1.0-1.el6 epel
ansible-inventory-grapher.noarch 1.0.1-2.el6 epel
ansible-lint.noarch 3.4.12-1.el6 epel
]# yum -y install ansible
Installed:
ansible.noarch 0:2.3.1.0-1.el6
Dependency Installed:
PyYAML.x86_64 0:3.10-3.1.el6 libyaml.x86_640:0.1.3-4.el6_6
python-babel.noarch 0:0.9.4-5.1.el6 python-crypto2.6.x86_640:2.6.1-2.el6
python-httplib2.noarch 0:0.7.7-1.el6 python-jinja2-26.noarch0:2.6-3.el6
python-keyczar.noarch 0:0.71c-1.el6 python-markupsafe.x86_640:0.9.2-4.el6
python-pyasn1.noarch 0:0.0.12a-1.el6 python-six.noarch0:1.9.0-2.el6
sshpass.x86_64 0:1.06-1.el6
]# ansible --version
ansible 2.3.1.0
config file = /etc/ansible/ansible.cfg
configured module search path = Default w/o overrides
python version = 2.6.6 (r266:84292, Sep 4 2013, 07:46:00) [GCC 4.4.7 20120313 (Red Hat 4.4.7-3)]
]# ll /etc/ansible/
total 28
-rw-r--r-- 1 root root 18066 Jun 2 05:49 ansible.cfg
-rw-r--r-- 1 root root 1077 Aug 16 10:41 hosts
drwxr-xr-x 2 root root 4096 Jun 2 05:49 roles
]# vim /etc/ansible/hosts # ansible預設
[websrvs]
172.17.101.31 ansible_ssh_user=ane ansible_ssh_pass=ane123
172.17.101.75 ansible_ssh_user=ane ansible_ssh_pass=ane123
[dbsrvs]
172.17.101.70 ansible_ssh_user=ane ansible_ssh_pass=ane123
注:若有如下操作,/etc/ansible/hosts檔案中的主機後不需跟anesible_ssh_user和anesible_ssh_pass變量
]# ssh-keygen -t rsa -f ~/.ssh/id_rsa -P ''
]# ssh-copy-id 172.17.101.31
]# ssh-copy-id 172.17.101.75
]# ssh-copy-id 172.17.101.70
]# man ansible-doc # show documentation on Ansible modules
-l,--list List available modules
-s,--snippet Show playbook snippetfor specified module(s)
]# ansible-doc -l #列出所有子產品;
]# ansible-doc -s MODULE_NAME #檢視子產品幫助;
]# man ansible #run a task on a target host(s)
Usage: ansible <host-pattern>[options]
-i INVENTORY, --inventory-file=INVENTORY
specify inventory hostpath
(default=/etc/ansible/hosts) or comma separated host
list.
-f FORKS, --forks=FORKS
specify number ofparallel processes to use
(default=5)
-m MODULE_NAME, --module-name=MODULE_NAME
module name to execute(default=command)
-a MODULE_ARGS, --args=MODULE_ARGS
module arguments
-C,--check don't make any changes;instead, try to predict some
of the changes thatmay occur
用法:
#ansible <host-pattern> [-f FORKS] [-m MODULE_NAME] [-a MODULES_ARGS]
]# man ansible-playbook #run an ansible playbook
Usage: ansible-playbook playbook.yml
常用子產品:
1、command
]# ansible-doc -s command #指令子產品,用于遠端執行指令,使用ansible指令時不指子產品名(-m MODULE_NAME),預設使用此子產品;
- name: Executes a command on a remote node
]# ansible 172.17.101.31 -m command -a 'date'
……
]# ansible websrvs -a 'date'
]# ansible all -a 'date' #all指inventory中定義的所有主機;
172.17.101.31 | SUCCESS | rc=0 >>
Wed Aug 16 11:18:54 CST 2017
172.17.101.75 | SUCCESS | rc=0 >>
172.17.101.70 | SUCCESS | rc=0 >>
2、cron
]# ansible-doc -s cron
- name: Manage cron.d and crontab entries.
job # The command to execute or, ifenv is set, the value of environment
variable.Required if state=present.
state # Whetherto ensure the job or environment variable is present or absent.
user # The specific user whosecrontab should be modified.
]# ansible websrvs -m cron -a 'minute="*/2" job="/bin/echo hello" user=anename="test cron job"' #state=present預設即是此項,若要删除要加state=absent;
在101.{31,75}上用ane驗證:
]# crontab -u ane -l
#Ansible: test cron job
*/2 * * * * /bin/echo hello
]# ansible websrvs -m cron -a 'minute="*/2" job="/bin/echo hello" user=anename="test cron job" state=absent'
]# ansible websrvs -m command -a 'crontab-l'
3、user
]# ansible-doc -s user
- name: Manage user accounts
name= # Name ofthe user to create, remove or modify.
#ansible all -m user -a 'name="user1"'
4、group
]# ansible-doc -s group
- name: Add or remove groups
gid # Optional`GID' to set for the group.
name= # Name ofthe group to manage.
state # Whetherthe group should be present or not on the remote host.
system # If `yes', indicates that thegroup created is a system group.
#ansible websrvs -m group -a 'name=mysql gid=306 system=yes'
#ansible websrvs -m user -a 'name=mysql uid=306 group=mysql system=yes'
5、copy,複制檔案;
]# ansible-doc -s copy
- name: Copies files to remote locations.
src # Localpath to a file to copy to the remote server; can be absolute or relative. Ifpath is a directory, it is copied recursively. In this case, if path ends with"/", only inside contents of that directory are copied todestination.Otherwise, if it does not end with "/", the directoryitself with all contents is copied. This behavior is similar to Rsync.本地源檔案,此處若指定目錄,則複制該目錄下的所有檔案;
dest= # Remoteabsolute path where the file should be copied to. If src is a directory, thismust be a directory too.遠端目标檔案路徑;
content # When usedinstead of 'src', sets the contents of a file directly to the specified value.This is for simple values, for anything complex or with formatting pleaseswitch to the template module.取代src,用此處指定的資訊生成目标檔案内容;
owner # Name ofthe user that should own the file/directory, as would be fed to `chown'.
group # Name of the group thatshould own the file/directory, as would be fed to `chown'.
mode # Mode thefile or directory should be. For those used to `/usr/bin/chmod' remember thatmodes are actually octal numbers (like 0644). Leaving off the leading zero willlikely have unexpected results. As of version 1.8, the mode may be specified asa symbolic mode (for example, `u+rwx' or `u=rw,g=r,o=r').
]# ansible websrvs -m copy -a 'src=/etc/fstab dest=/tmp/fstab.ansible owner=ane group=ane mode=640'
]# ansible websrvs -m copy -a 'content="hello ansible\nhi i am jowin\n" dest=/tmp/test.an
sible'
6、file,設定檔案屬性;
]# ansible-doc -s file
- name: Sets attributes of files
path= # path tothe file being managed. Aliases: `dest',`name'
owner
group
mode
state # ……If `link', the symbolic linkwill be created or changed. Use `hard' for hardlinks. If `absent', directorieswill be recursively deleted, and files or symlinks will be unlinked.……state=link可建立符号連結檔案;
#ansible websrvs -m file -a 'path=/tmp/fstab.ansible owner=zabbix group=zabbix mode=644'
]# ansible websrvs -m file -a 'src=/tmp/fstab.ansible path=/tmp/fstab.link state=link'
7、ping,測試遠端主機的連通性;
]# ansible-doc -s ping
- name: Try to connect to host, verify ausable python and return `pong' on success.
]# ansible all -m ping
8、service
]# ansible-doc -s service
- name: Manage services.
enabled # Whetherthe service should start on boot. *At least one of state and enabled arerequired.*開機自啟,true|false;
name= # Name ofthe service.服務名稱;
state #`started'/`stopped' are idempotent actions that will not run commands unless necessary. `restarted' will alwaysbounce the service. `reloaded' willalways reload. *At least one of state and enabled are required.* Note that reloaded will start the service if it is not already started, even if your chosen init system wouldn't normally.狀态有started|stopped|restarted;
#ansible websrvs -a 'service httpd status'
#ansible websrvs -a 'chkconfig --listhttpd'
#ansible websrvs -m service -a 'enabled=true name=httpd state=started'
9、shell,在遠端主機上運作指令,尤其是要用到管道等功能的指令時用-m shell;
]# ansible-doc -s shell
- name: Execute commands in nodes.
chdir # cd intothis directory before running the command
#ansible websrvs -m user -a 'name=user10'
#ansible websrvs -m shell -a 'echo user10123| passwd --stdin user10'
10、script,将本地腳本複制到遠端并執行,要使用相對路徑指定腳本;
#ansible websrvs -m script -a 'test.sh' #test.sh在本地的目前路徑下;
11、yum,安裝程式包;
]# ansible-doc -s yum
- name: Manages packages with the `yum'package manager
name= # Packagename, or package specifier with version, like `name-1.0'. When usingstate=latest, this can be '*' which means run: yum -y update. You can also passa url or a local path to a rpm file (using state=present). To operate on several packages this canaccept a comma separated list of packages or (as of 2.0) a list of packages.指明要安裝的程式包,可帶上版本号;
state # Whether to install (`present' or `installed', `latest'), or remove (`absent' or`removed') a package.安裝用present|installed|latest,解除安裝用absent|removed;
#ansible websrvs -m yum -a 'name=zsh'
12、setup,收集遠端主機的facts,每個被管理節點在接收并運作管理指令之前,會将自己主機的相關資訊,如os version、ip等資訊報告給遠端的ansible主機;
]# ansible-doc -s setup
- name: Gathers facts about remote hosts
]# ansible 172.17.101.31 -m setup
172.17.101.31 | SUCCESS => {
"ansible_facts": {
"ansible_all_ipv4_addresses": [
"172.17.101.31"
],
"ansible_all_ipv6_addresses": [
"fe80::250:56ff:feb2:775a"
"ansible_apparmor": {
"status": "disabled"
},
]#ansible 10.113.128.42 -m setup -a 'filter=ansible_fqdn' #僅顯示過濾的結果;
10.113.128.42| SUCCESS => {
"ansible_facts": {
"ansible_fqdn":"yitian_web01"
},
"changed": false
}
13、unarchive,解壓,src=壓縮包在本地,dest=被管理主機目錄:
]#ansible-doc -s unarchive
-name: Unpacks an archive after (optionally) copying it from the local machine.
src= # If remote_src=no(default), local path to archive file to copy to the target server; can beabsolute or relative. If remote_src=yes, path on the target server to existingarchive file to unpack. If remote_src=yes and src contains ://, the remotemachine will download the file from the url first. (version_added 2.0). This isonly for simple cases, for full download support look at the [get_url] module.
dest= # Remote absolute path wherethe archive should be unpacked
copy # If true, the file iscopied from local 'master' to the target machine, otherwise, the plugin willlook for src archive at the target machine. This option has been deprecated infavor of `remote_src' This option is mutually exclusive with `remote_src'.
remote_src # Set to `yes' to indicate thearchived file is already on the remote system and not local to the Ansiblecontroller.This option is mutually exclusive with `copy'.在解壓檔案檔案之前,是否先将檔案複制到被管理主機,預設yes,若為no,則被管理主機上該壓縮封包件必須存在;
#ansiblewebsrvs -m unarchive -a 'src=nginx-1.8.0.tar.gz dest=/ane/ remote_src=no' #将本地壓縮包複制到被管理端解壓後并删除,經測試該子產品不能解壓war包;
#ansible websrvs -m unarchive -a 'src=/ane/nginx-1.8.0.tar.gz dest=/ane/remote_src=yes' #在被管理主機上直接解壓檔案;
14、mysql_db:
]#ansible-doc -s mysql_db
-name: Add or remove MySQL databases from a remote host.
login_user # The username used toauthenticate with.
login_password # The password used to authenticatewith.
login_unix_socket # The path to a Unix domain socket forlocal connections.
name= # name of the database to addor remove name=all May only be provided if `state' is `dump' or `import'. ifname=all Works like --all-databases option for mysqldump (Added in 2.0)
state # The database state
target # Location, on the remotehost, of the dump file to read from or write to. Uncompressed SQL files(`.sql') as well as bzip2 (`.bz2'), gzip (`.gz') and xz (Added in 2.0)compressed files are supported.
#ansible10.113.128.42 -m mysql_db -a 'login_user=ane login_password=ane123login_unix_socket=/mydata/data/mysql.sock name=student state=present' #建立庫;
#ansible 10.113.128.42 -m mysql_db -a 'login_user=ane login_password=ane123login_unix_socket=/mydata/data/mysql.sock name=student target=/tmp/student.sqlstate=import' #導入sql語句(建立表);
15、pause:
在playbook執行過程中暫停一段時間或提示使用者進行某些操作;
]#ansible-doc -s pause
-name: Pause playbook execution
action: pause
minutes # A positive number of minutesto pause for.
prompt # Optional text to use for theprompt message.
seconds # A positive number of secondsto pause for.
- name: wait on user input
pause: prompt="Warning! Detectedslight issue. ENTER to continue CTRL-C a to quit"
- name: timed wait
pause: seconds=30
16、wait_for:
在playbook執行過程中,等待某些操作完成以後再進行後續操作;
]#ansible-doc -s wait_for
-name: Waits for a condition before continuing.
port # port number to poll
state # either `present',`started', or `stopped', `absent', or `drained' When checking a port `started'will ensure the port is open, `stopped' will check that it is closed, `drained'will check for active connections When checking for a file or a search string`present' or `started' will ensure that the file or string is present beforecontinuing, `absent' will check that file is absent or removed等待的狀态,即等待的檔案或端口或者連接配接狀态達到指定的狀态時,下一個任務開始執行,當等的對象為端口時,狀态有started,stoped,即端口已經監聽或者端口已經關閉;當等待的對象為檔案時,狀态有present或者started,absent,即檔案已建立或者删除;當等待的對象為一個連接配接時,狀态有drained,即連接配接已建立,預設為started;
delay # number of seconds to waitbefore starting to poll等待一個端口或者檔案或者連接配接到指定的狀态時,預設逾時時間為300秒,在這等待的300s的時間裡,wait_for子產品會一直輪詢指定的對象是否到達指定的狀态,delay即為多長時間輪詢一次狀态;
host # A resolvable hostname orIP address to,wait_for子產品等待的主機的位址,預設為127.0.0.1;
timeout # maximum number of seconds towait for,wait_for子產品等待的逾時時間,預設為300秒
-wait_for: port=8080 state=started #等待8080端口已正常監聽,才開始下一個任務,直到逾時
-wait_for: port=8000 delay=10 #等待8000端口正常監聽,每隔10s檢查一次,直至等待逾時
-wait_for: host=0.0.0.0 port=8000 delay=10 state=drained #等待8000端口直至有連接配接建立
-wait_for: host=0.0.0.0 port=8000 state=drainedexclude_hosts=10.2.1.2,10.2.1.3 #等待8000端口有連接配接建立,如果連接配接來自10.2.1.2或者10.2.1.3,則忽略。
-wait_for: path=/tmp/foo #等待/tmp/foo檔案已建立
-wait_for: path=/tmp/foo search_regex=completed #等待/tmp/foo檔案已建立,而且該檔案中需要包含completed字元串
-wait_for: path=/var/lock/file.lock state=absent #等待/var/lock/file.lock被删除
-wait_for: path=/proc/3466/status state=absent #等待指定的程序被銷毀
-local_action: wait_for port=22 host="{{ ansible_ssh_host |default(inventory_hostname) }}" search_regex=OpenSSH delay=10 #等待openssh啟動,10s檢查一次
ansible playbook:
playbook是由一個或多個play組成的清單,play的主要功能在于将事先歸并為一組的主機裝扮成事先通過ansible中的task定義好的角色,從根本上講,task無非是調用ansible的module将多個play組織在一個playbook中,即可讓它們聯同起來按事先編排的機制同唱一台大戲;
為滿足子產品執行幂等性,不是每次#ansible-playbook apache.yml都執行,隻有滿足一定的條件才執行,如配置檔案改變;
playbook的組成結構:
inventory;
modules;
Ad Hoc command;
playbooks(tasks(調用module完成某操作);variables;templates;handlers(處理器,由某事件觸發執行的操作);roles);
playbook中每一個play的目的都是為了讓某個或某些主機以某個指定的使用者身份執行任務;
- hosts: websrvs
vars:
- http_port:80
- max_clients:256
remote_user: root
tasks:
- name: install httpd package
yum: name=httpd state=latest
- name: install configuration file for httpd
copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
notify:
- restart httpd
- name: start httpd service
service: name=httpd state=started
handlers:
- name: restart httpd
service: name=httpd state=restarted
hosts,用于指定要執行指定任務的主機,其可以是一個或多個由冒号分隔的主機組;
remote_user,用于指定遠端主機上的執行任務的使用者,remote_user可用于各task中,也可通過sudo方式在遠端主機上執行任務,用于play全局或某任務,此外可在sudo時使用sudo_user指定sudo時切換的使用者;
task任務清單和action,play的主體部分是task list,task list中的各任務被次序逐個在hosts中指定的所有主機上執行,即在所有主機上完成第一個任務後再開始第二個,自上而下運作各任務,如果中途發生錯誤,所有已執行任務都可能復原,在更正playbook後重新執行一次即可;
task的目的是使用指定的參數執行子產品,而在子產品參數中可使用變量,子產品執行是幂等的,意味着多次執行是安全的,因為其結果一緻;
每個task都應該有name,用于playbook的執行結果輸出,建議其内容盡可能清晰的描述任務執行步驟,如果未提供name,則action的結果将用于輸出;
定義task可使用"action: module options"或"module: options",建議使用後者,可實作向後相容,如果action一行的内容過多,在行首使用空格換行;
在衆多子產品中,隻能command和shell隻需給定一個list,而無需使用-a 'key=value'格式,例如:
tasks:
- name: disable selinux
command: /sbin/setenforce 0
若指令和腳本的退出不為0,可使用如下方式替代(或使用ignore_errors來忽略錯誤資訊),例如:
- name: run this command and ignore the result
shell: /usr/bin/somcommand || /bin/true
或
shell: /usr/bin/somecommand
ignore_errors: Ture
handlers,用于當關注的資源發生變化時采取一定的操作;
notify這個action可用于在每個play最後被觸發,這樣可避免多次有改變發生時每次都執行指定的操作,取而代之,僅在所有的變化發生完成後一次性的執行指定操作,在notify中列出的操作稱為handler,即notify中調用handler中定義的操作;
playbook中使用變量:
1、 自定義變量:
- package: httpd
- service: httpd
yum: name=` httpd ` state=latest
2、直接使用ansible内置變量:
- name: copy file
copy: content="` ansible_all_ipv4_address `" dest=/tmp/vars.ansible
3、在inventory中定義(主機變量|組變量):
例(自定義主機變量):
172.17.101.31 testvar="test"
例(自定義組變量):
[websrvs:vars]
ntp_server=ntp.example.com
nfs_server=nfs.example.com
4、若未作ssh密鑰認證(ansible主機-->被管理client主機),可在/etc/ansible/hosts中直接用内置變量定義:
playbook中使用條件測試:
如果需要根據變量、facts或此前任務執行結果來作為某task執行與否的前提時,要用到條件測試;
when語句:在task後添加when子句,when語句支援jinja2表達式文法;
- username: user10
- name: create ` username ` user
user: name=` username `
when: ansible_fqdn == "node2.example.com"
playbook中疊代:
當有需要重複性執行的任務時,可使用疊代機制;
使用格式為将需要疊代的内容定義為item變量(item是特殊變量),并通過with_items語句來指明疊代的元素清單;
調用用item,定義task循環清單用with_items,with_items中的清單值可以是字典,但引用時要用item.KEY;
- name: add several users
user: name=` item ` state=present groups=wheel
with_items:
- testuser1
- testuser2
user: name= ` item`.`name ` groups=`item`.`groups ` state=present
with_items:
- {name: 'testuser1',groups: 'wheel' }
- {name: 'testuser2',groups: 'root' }
playbook中template:
#vim template/httpd.conf.j2
Listen ` http_port `
MaxClients ` maxClients `
ServerName ` ansible_fqdn `
#vim /etc/ansible/hosts
172.17.101.31 http_port=80 maxClients=100
172.17.101.75 http_port=8080 maxClients=200
#vim apache.yml
yum: name:` package ` state=latest
template: src=/root/template/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
service: enabled=true name=` service ` state=started
#ansible-playbook apache.yml
playbook中tags:
為某個任務定義标簽,在執行playbook時,通過為ansible-playbook指令使用--tags選項能實作僅運作指定的task而非所有的;
特殊tags:
- always
tags:
- always
template: src=/root/template/httpd.conf.j2dest=/etc/httpd/conf/httpd.conf
- conf
- service
#ansible-playbook apache.yml --tags="conf"
playbook中roles:
1.2version引入的新特性,用于層次性、結構化的組織playbook,roles能根據層次型結構自動裝載變量檔案、tasks、handlerst等;
要使用roles隻需在playbook中使用include指令即可,簡單講,roles就是通過分别将變量、檔案、任務、子產品、處理器放置于單獨的目錄中,并可便捷的include它們的一種機制;;
roles一般用于基于主機建構服務的場景中,也可用于建構守護程序等場景中;
建立roles的步驟:
1、建立以roles命名的目錄;
2、在roles目錄中分别建立以各角色名稱命名的目錄,如websrvs等;
3、在每個角色命名的目錄中分别建立tasks、files、templates、handlers、vars、meta、default目錄,用不到的目錄可為空目錄,也可不建立;
4、在playbook檔案中調用各角色;
roles各目錄:
tasks/,至少應包含一個名為main.yml的檔案,其定義了此角色的任務清單,此檔案可使用include包含其它的位于此目錄中的task檔案;
files/,存放由copy或script等子產品調用的檔案,靜态檔案;
templates/,template子產品會自動在此目錄中尋找jinja2模闆檔案;
handlers/,應包含一個main.yml檔案,用于定義此角色用到的各handler,在handler中使用include包含的其它handler檔案也應位于此目錄中;
vars/,應包含一個main.yml檔案,用于定義此角色用到的變量;
meta/,應包含一個main.yml檔案,用于定義此角色的特殊設定及依賴關系,1.3以上version才支援;
default/,應用包含一個main.yml為目前角色設定預設變量時使用此目錄;
目錄名同角色名;
目錄結構有固定格式;
site.yml中定義playbook,也可有其它的yml檔案;
roles間可定義依賴關系;
#mkdir -pv /etc/ansible/roles/{websrvs,dbsrvs}/{tasks,files,templates,handlers,vars,meta}
#cd /etc/ansible/roles/websrvs
#cp /etc/httpd/conf/httpd.conf files/
#vim tasks/main.yml
- name: install httpd package
yum:name=httpd
- name: install configuration file
copy: src=httpd.confdest=/etc/httpd/conf/httpd.conf
- name: start httpd
service: name=httpd state=started
#vim handlers/main.yml
- name: restart httpd
service: name=httpd state=restarted
#vim vars/main.yml
- httpd_port: 80
- maxClients: 200
#vim /etc/ansible/roles/site.yml #和roles在同級路徑下;
roles:
- websrvs
- hosts: dbsrvs
remote_user:root
- dbsrvs
- hosts: 172.17.101.1
#ansbile-playbook site.yml --limit websrvs
本文轉自 chaijowin 51CTO部落格,原文連結:http://blog.51cto.com/jowin/1957071,如需轉載請自行聯系原作者