Ansible 學(xué)習(xí)
visudo sudo權(quán)限
useradd -aG wheel sun 保留原來的組史飞,追加sudo
yum源 /etc/yum.repos.d/base.repo
echo export EDITOR=vim >> /etc/profile.d/env.sh
systemctl is-enabled vsftpd
ss -tln|grep 80 查看端口
hostnamectl set-hostname node1
getent group
1峭竣,安裝
yum install -y ansible
2,查看
yum -ql ansible | less
3,舉例
ansible server -m ping -k :走的是ssh協(xié)議
-m 模塊 -k 密碼
服務(wù)器列表放在 /etc/ansible/hosts ,
用all代替全部服務(wù)器
用[]分組
加速SSH的方法
服務(wù)器上 /etc/ssh/sshd_config
UseDNS no
GSSAPIAuthentication no
服務(wù)器和記住的主機(jī) /root/.ssh/known_hosts
/etc/ansible/ansible.cfg中
host_key_checking = False,不用服務(wù)器的hostkey
log_path=/var/log/ansible.log 打開日志
建議建議居于key驗(yàn)證
ssh-keygen
ssh-copy-id 192.168.153.101
4未辆,ansible幫助
ansible-doc -l / -a / -s command
5, ansible 命令
ansible server -m 模塊 -a 參數(shù) -v 查看詳細(xì)過程 --list 查看主機(jī)列表
-u 用戶 -K sudo
ansible 192.168.153.101 -m command -a 'ls -l /root/' -u sun -k -b -K
主機(jī)列表,與&,或:岛啸,非泪酱!alist:blist:&clist:!dlist ,用單引號(hào)
正則表達(dá) 用雙引號(hào) “~(web|db)" 用~開頭
6,常見模塊 ansible-doc 模塊
command 可以不用寫派殷,不支持|,墓阀;,&,$等
shell 可以執(zhí)行 ansible serlist -m shell -a 'echo medu|passwd --stdin test1'
script 運(yùn)行腳本 ansible 192.168.153.101 -m script -a '/root/ansible/host.sh'
copy ansible serlist -m copy -a 'src=/root/ansible/selinux dest=/etc/selinux/config backup=yes'
fetch 和copy相反
file 模塊
hostname
cron
ansible 192.168.153.101 -m cron -a 'minute=* weekday=1,3,5 job="/usr/bin/wall FBI warning" name=warningcron'
ansible 192.168.153.101 -m cron -a 'disabled=true job="/usr/bin/wall FBI warning" name=warningcron'
yum ansible 192.168.153.101 -m yum -a 'name=vsftpd'
service
user ansible webser -m user -a 'name=nginx shell='sbin/nologin system=yes home=/var/nginx groups=root comment="nginx server"'
group
7,galaxy
galaxy.ansible.com查看下載rules (一堆文件的集合)
ansible-galaxy list *****
ansible-galaxy install/remove *****
8.ansible-vault
ansible-vault decrypt *.yml
ansible-vault encrypt *.yml
ansible-vault view *.yml
ansible-vault edit *.yml
ansible-vault reky *.yml
9.ansible-console交互式工具
10,playbook
'''
-
hosts: serlist
remote_user: roottasks:
- name: test1
command: hostname
'''
列表 -
K/V k:v {k1: v1,k2: v2}
- name: test1
ansible-playbook -C file.yml 檢查語法
--check檢查
--list-hosts 列出服務(wù)器
--list-tasks 列出任務(wù)
--list-tages 列出標(biāo)簽
--limit 主機(jī) 只爭對(duì)特定主機(jī)
'''
-
hosts: 192.168.153.101
remote_user: roottasks:
- name: create new file
file: name=/data/newfile state=touch - name: create new user
user: name=test1 system=yes shell=/sbin/nologin - name: install package
yum: name=httpd - name: copy html
copy: src=/var/www/html/index.html dest=/var/www/html/index.html - name: start service
service: name=httpd state=started enabled=yes
'''
如果命令出錯(cuò)還想繼續(xù)
shell: /usr/bin/command || /bin/true
ignore_errors: True
- name: create new file
handlers當(dāng)資源觸發(fā)時(shí)執(zhí)行
nofify通知
’''
-
hosts: 192.168.153.101
remote_user: roottasks:
- name: install httpd package
yum: name=httpd - name: copy conf file
copy: src=files/httpd.conf dest=/etc/httpd/conf/ backup=yes
notify: restart service - name: start service
service: name=httpd state=started enabled=yes
tages: rshttpd
handlers:
- name: restart service
service: name=httpd state=restarted
'''
ansible-playbook -t rshttpd http.yml 指定標(biāo)簽執(zhí)行
ansible 192.168.153.101 -m setup | less 查看服務(wù)器信息
ansible 192.168.153.101 -m setup -a 'filter=ansible_×'
- name: install httpd package
使用變量
ansible-playbook -e 'pkname=vsftpd' app.yml
'''
-
hosts: 192.168.153.101
remote_user: roottasks:
- name: install package
yum: name={{ pkname }} - name: start service
service: name={{ pkname }} state=started enabled=yes
'''
程序里使用變量
- name: install package
-
hosts: 192.168.153.101
remote_user: root
vars:- pkname1: httpd
- pkname2: vsftpd
可以在/etc/ansible/hosts中定義
server1 var=l1
[webserver:vars]
var1=z1
var2=z2
直接文件里寫入變量 eg vars.yml
-
hosts: 192.168.153.101
remote_user: root
vars_files:- vars.yml
使用模板
放到templates目錄 file.j2 - name: create some file
template: src=file2.j2 dest=/data/x.conf
when語句 - name: install package
yum: name={{ pkname }}
when: ansible_os_family == "RedHat"
循環(huán)建文件 - name: create some file
file: name=/data/{{ item }} state=touch
with_items:
-file1:
-file2:
-file3:
嵌套變量 - name: create some users
user: name={{ item.name }} group={{ item.group }} state=present
with_items:
-{name:'user1',group:'g01'}
-{name:'user2',group:'g02'}
-{name:'user3',group:'g03'}
循環(huán)判斷
{% for a in all %} dosomthing {% endfor %}
{% if %} {% endif %}
{{ a.listion | default('80 default_server') }}
- vars.yml
在有的時(shí)候play的結(jié)果依賴于變量毡惜、fact或者是前一個(gè)任務(wù)的執(zhí)行結(jié)果,從而需要使用到條件語句岂津。
一虱黄、when
有的時(shí)候在特定的主機(jī)需要跳過特定的步驟,例如在安裝包的時(shí)候吮成,需要指定主機(jī)的操作系統(tǒng)類型橱乱,或者是當(dāng)操作系統(tǒng)的硬盤滿了之后,需要清空文件等,可以使用when語句來做判斷 粱甫。when關(guān)鍵字后面跟著的是python的表達(dá)式,在表達(dá)式中你能夠使用任何的變量或者fact,當(dāng)表達(dá)式的結(jié)果返回的是false,便會(huì)跳過本次的任務(wù)
1泳叠、基本用法,示例:
-
name: Install VIM
hosts: all tasks:- name:Install VIM via yum
yum: name=vim-enhanced state=installed
when: ansible_os_family =="RedHat" - name:Install VIM via apt
apt: name=vim state=installed
when: ansible_os_family =="Debian" - name: Unexpected OS family
debug: msg="OS Family {{ ansible_os_family }} is not supported" fail=yes
when: not ansible_os_family =="RedHat" or ansible_os_family =="Debian"
條件語句還有一種用法,它還可以讓你當(dāng)達(dá)到一定的條件的時(shí)候暫停下來,等待你的輸入確認(rèn)茶宵。一般情況下,當(dāng)ansible遭遇到error時(shí),它會(huì)直接結(jié)束運(yùn)行危纫。那其實(shí)你可以當(dāng)遭遇到不是預(yù)期的情況的時(shí)候給使用pause模塊,這樣可以讓用戶自己決定是否繼續(xù)運(yùn)行任務(wù):
- name:Install VIM via yum
-
name: pause for unexpected conditions
pause: prompt="Unexpected OS"
when: ansible_os_family !="RedHat"
2、在when中使用jinja2的語法乌庶,示例:
tasks:- command: /bin/false
register: result #將命令執(zhí)行的結(jié)果傳遞給result變量
ignore_errors: True #忽略錯(cuò)誤 - command: /bin/something
when: result|failed #如果注冊(cè)變量的值 是任務(wù)failed則返回true - command: /bin/something_else
when: result|success #如果注冊(cè)變量的值是任務(wù)success則返回true - command: /bin/still/something_else
when: result|skipped #如果注冊(cè)變量的值是任務(wù)skipped則返回true - command: /bin/foo
when: result|changed #如果注冊(cè)變量的值是任務(wù)changed則返回true
- command: /bin/false
-
hosts: all
user: root
vars:
epic: true
tasks: - shell: echo "This certainly is epic!" when: epic- shell: echo "This certainly is not epic!"
when: not epic
4种蝶、如果變量不存在,則可以通過jinja2的'defined'命令跳過瞒大,示例:
tasks: - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined - fail: msg="Bailing out. this play requires 'bar'"
when: bar is not defined
5螃征、when在循環(huán)語句中的使用方法,示例:
tasks: - command: echo {{ item }}
with_items: [ 0, 2, 4, 6, 8, 10 ]
when: item > 56透敌、在include和roles中使用when:
在include中使用的示例:- include: tasks/sometasks.yml
when: "'reticulating splines' in output"
在roles中使用的示例:- hosts: webservers
roles: - { role: debian_stock_config, when: ansible_os_family == 'Debian' }
二盯滚、條件導(dǎo)入
有些時(shí)候,你也許想在一個(gè)Playbook中以不同的方式做事酗电,比如說在debian和centos上安裝apache魄藕,apache的包名不同,除了when語句撵术,還可以使用下面的示例來解決:
- shell: echo "This certainly is not epic!"
- hosts: all
remote_user: root
vars_files:- "vars/common.yml"
- [ "vars/{{ ansible_os_family }}.yml", "vars/os_defaults.yml" ]
tasks: - name: make sure apache is running
service: name={{ apache }} state=running很多不同的yml文件只是包含鍵和值背率,如下:
for vars/CentOS.yml
apache: httpd
somethingelse: 42
如果操作系統(tǒng)是’CentOS’, Ansible導(dǎo)入的第一個(gè)文件將是’vars/CentOS.yml’,緊接著 是’/var/os_defaults.yml’,如果這個(gè)文件不存在。而且在列表中沒有找到,就會(huì)報(bào)錯(cuò)退渗。 在Debian系統(tǒng)中移稳,最先查看的將是’vars/Debian.yml’而不是’vars/CentOS.yml’, 如果沒找到会油,則尋找默認(rèn)文件’vars/os_defaults.yml’个粱。
三、with_first_found
有些時(shí)候翻翩,我們想基于不同的操作系統(tǒng)都许,選擇不同的配置文件,及配置文件的存放路徑嫂冻,可以借助with_first_found來解決:
-
name: template a file
template: src={{ item }} dest=/etc/myapp/foo.conf
with_first_found:- files:
- {{ ansible_distribution }}.conf
- default.conf
paths: - search_location_one/somedir/
- /opt/other_location/somedir/
四胶征、failed_when
failed_when其實(shí)是ansible的一種錯(cuò)誤處理機(jī)制,是由fail模塊使用了when條件語句的組合效果桨仿。示例如下:
- files:
name: this command prints FAILED when it fails
command: /usr/bin/example-command -x -y -z
register: command_result
failed_when: "'FAILED' in command_result.stderr"我們也可以直接通過fail模塊和when條件語句睛低,寫成如下:name: this command prints FAILED when it fails
command: /usr/bin/example-command -x -y -z
register: command_result
ignore_errors: True-
name: fail the play if the previous command did not succeed
fail: msg="the command failed"
when: "'FAILED' in command_result.stderr"五、changed_when
當(dāng)我們控制一些遠(yuǎn)程主機(jī)執(zhí)行某些任務(wù)時(shí)服傍,當(dāng)任務(wù)在遠(yuǎn)程主機(jī)上成功執(zhí)行钱雷,狀態(tài)發(fā)生更改時(shí),會(huì)返回changed狀態(tài)響應(yīng)吹零,狀態(tài)未發(fā)生更改時(shí)罩抗,會(huì)返回OK狀態(tài)響應(yīng),當(dāng)任務(wù)被跳過時(shí)灿椅,會(huì)返回skipped狀態(tài)響應(yīng)套蒂。我們可以通過changed_when來手動(dòng)更改changed響應(yīng)狀態(tài)。示例如下:- shell: /usr/bin/billybass --mode="take me to the river"
register: bass_result
changed_when: "bass_result.rc != 2" #只有該條task執(zhí)行以后茫蛹,bass_result.rc的值不為2時(shí)操刀,才會(huì)返回changed狀態(tài)
this will never report 'changed' status
- shell: wall 'beep'
changed_when: False #當(dāng)changed_when為false時(shí),該條task在執(zhí)行以后婴洼,永遠(yuǎn)不會(huì)返回changed狀態(tài)
- shell: /usr/bin/billybass --mode="take me to the river"