ansible自動化部署之場景應用

ansible自動化配置管理


  • 1、安裝 配置 啓動 (ansible由紅帽收購)
    • (1)什麼是ansible ansible是IT自動化配置管理工具,模塊豐富,組件豐富,能夠經過一個命令完成一系列的操做。減小了維護成本和複雜性的工做,提升工做效率。 假設完成100臺nginx服務的安裝: ssh-->登陸-->輸入密碼-->安裝nginx-->啓動nginx-->退出登陸(重複10次) 引入-->ansible一鍵部署 (2)ansible能夠完成哪些功能 一、批量執行遠程命令:能夠對n多臺主機同時進行命令的執行 二、批量配置軟件服務:能夠進行自動化的配置和管理服務 三、實現軟件開發功能:jumpserver 四、編排高級IT任務:ansible的playbook是一門編程語言,能夠用來描繪一整套IT架構。 (3)ansible的特色: 容易學習,無代理模式、操做靈活、簡單易用、安全可靠、移植性高。 (4)inventory(主機清單)可以對不一樣的主機或不一樣的主機組作AD-Hoc和playbook藉助module(模塊-->python開發)依託於ssh進行分組批量部署。 (5)ansible配置文件(優先級)
[root@manager ~]# cd /etc/ansible/
[root@manager ansible]# vim ansible.cfg #查看配置文件
其中
ANSIBLE_CONFIG
ansible.cfg		#當前項目目錄中
.ansible.cfg	#當前執行用戶的家目錄
[root@manager ~]# mkdir /project1
[root@manager ~]# cp /etc/ansible/ansible.cfg /project1
[root@manager ~]# cd /project1/
  • ansible inventory 主機清單php

    一、#基於IP地址+密碼的方式
    [root@manager project1]# vim hosts 
    [root@manager project1]# cat hosts
    [webservers]
    172.16.1.7 ansible_ssh_user='root' ansible_ssh_pass='1'
    172.16.1.8 ansible_ssh_user='root' ansible_ssh_pass='1'
    
    
    二、基於祕鑰鏈接,須要首先建立公鑰和私鑰,並下發公鑰至被控端
    [root@manager project1]# ssh-keygen -C manager@qq.com #一路回車
    [root@manager project1]# vim ansible.cfg 
    # inject_facts_as_vars = True
    # additional paths to search for roles in, colon separated
    #roles_path    = /etc/ansible/roles
    # uncomment this to disable SSH key host checking
    host_key_checking = False   #祕鑰免密碼登陸
    ......
    [root@manager ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.7
    [root@manager ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.1.8
    [root@manager project1]# cat hosts 
    [webservers]
    172.16.1.7 
    172.16.1.8 
    #測試
    [root@manager project1]# ansible webservers -m ping -i hosts
    [root@manager project1]# ansible webservers --list-hosts -i hosts
      hosts (2):
        172.16.1.7
        172.16.1.8
    
    三、主機組使用方式
    [root@manager project1]# cat hosts 
    [lbservers]		#定義lbservers組
    172.16.1.7 
    172.16.1.8 
    [root@manager project1]# cat hosts 
    [webservers]	#定義webservers組
    172.16.1.7 
    172.16.1.8
  • ansible AD-Hochtml

    • 1570628215786
command		#執行命令
shell		#執行命令
yum_reposity #yum倉庫配置
yum  		#yum安裝軟件
get_url		#和linux的wget一致

一、command前端

[root@manager project1]# ansible webservers -a "ps aux |grep nginx" -i hosts		#不支持管道(會報錯(red))

二、shellpython

[root@manager project1]# ansible webservers -m shell -a "ps aux |grep nginx" -i hosts	#支持管道

三、yumlinux

state:
	present 安裝
	absent	卸載
	latest	最新
enablerepo	#指定使用哪一個倉庫
disablerepo	#排除使用哪一個倉庫

#一、安裝最新的httpd服務nginx

[root@manager project1]# ansible webservers -m yum -a "name=httpd state=latest disablerepo=webtatic-php" -i hosts

#2移除httpd服務web

[root@manager project1]# ansible webservers -m yum -a "name=httpd state=absent disablerepo=webtatic-php" -i hosts

#三、安裝httpd指定那個倉庫安裝shell

[root@manager project1]#ansible webservers -m yum -a "name=httpd state=latest enablerepo=mirrors.aliyun.com" -i hosts

#四、經過url的方式安裝編程

[root@manager project1]# ansible webservers -m yum -a "name=/root/zabbix-agent-4.0.0-2.el7.x86_64.rpm  state=present disablerepo=webtatic-php" -i hosts

四、copyjson

src		#本地路徑,能夠是相對,也能夠是絕對
dest	#目標位置
owner	#屬主
group	#屬組
mode	#權限
backup	#備份

[root@manager project1]# vim /etc/nginx/conf.d/ansible.oldxu.com.conf  
server {
        listen 80;
        root /code/ansible;
        location / {
        index index.html;
}
}

[root@manager project1]# ansible webservers -m copy -a "src=/etc/nginx/conf.d/ansible.oldxu.com.conf dest=/etc/nginx/conf.d/ansible.oldxu.com.conf owner=root group=root mode=644 backup=yes" -i hosts
#backup=yes  #表示在目標機上面是否備份
#訪問測試

五、service/systemd

state
	started		#啓動
	stopped		#中止
	restarted	#重啓
	reloaded	#重載
enabled
	yes			#是
	no			#否

[root@manager project1]# ansible webservers -m systemd -a "name=nginx state=restarted enabled=yes" -i hosts

六、file

#建立/code/ansible
path #路徑
state
	touch	#建立文件
	directory	#建立目錄
owner	#屬主
group	#屬組
mode	#權限
#準備站點
[root@manager project1]# mkdir /code/ansible
[root@manager project1]# ansible webservers -m file -a "path=/code/ansible state=directory mode=755 owner=www group=www" -i hosts
#準備站點代碼
[root@manager project1]# echo "test01" > /code/ansible/index.html
[root@manager project1]# ansible webservers -m copy -a "src=/code/ansible/index.html dest=/code/ansible/index.html owner=www group=www mode=644" -i hosts

七、user group

#group   整數int   小數 flot  dasdsa str    真|假   bool 
[root@manager project1]# ansible webservers -m group -a  "name=www gid=666 state=present" -i hosts
#user name            #名稱 uid             #uid group           #組名或gid create_home     #是否建立家目錄 system          #是否做爲系統組 shell           #指定登陸shell state    present    absent remove groups append password
#--------------------------------------------------------------> # 程序使用    www    666 666 /sbin/nologin    /home  -->無 
[root@manager project1]# ansible webservers -m user -a "name=www uid=666 group=666 create_home=no shell=/sbin/nologin state=present" -i hosts
# 正經常使用戶    oldxu  1000 1000 /bin/bash   /home/oldxu [root@manager project1]# ansible webservers -m user -a "name=oldxu" -i hosts
# 移除oldxu用戶,並刪除家目錄全部內容. 
[root@manager project1]# ansible webservers -m user -a "name=oldxu state=absent remove=yes" -i hosts
# 建立 other用戶.有兩個附加組root bin,建立家目錄,指定登陸 shell,設定密碼123
#生成一個密碼 ansible all -i localhost, -m debug -a "msg={{ '123' | password_hash('sha512', 'mysecretsalt') }}"
[root@manager project1]# ansible webservers -m user -a 'name=other groups='root,bin' create_home=yes shell=/bin/bash password="$6$mysecretsalt$gIIYs0Xgc7sSQkH.zKaz8/Afa MomYzR1QZYtccwmJcUt8VpLq4D055UCCX4MlwgePOP80ZRwhppv BF72RIAVi/"' -i hosts

八、mount

#提早準備好nfs服務端 [root@web01 ~]# showmount -e 172.16.1.31 
Export list for 172.16.1.31: 
/data/zrlog 172.16.1.0/24
/data/zh    172.16.1.0/24
/data/edu   172.16.1.0/24
/data/blog  172.16.1.0/24
#用管理端操做被控端,讓被控端掛載nfs存儲數據 present     
#寫入/etc/fstab absent      
#卸載/etc/fstab
mounted     #臨時掛載 unmounted   #卸載當前掛載
#掛載過程當中,若是目錄不存在,則會建立該目錄 
[root@manager project1]# ansible webservers -m mount -a "src=172.16.1.31:/data/zrlog path=/test_zrlog fstype=nfs opts=defaults state=mounted" -i hosts
[root@manager project1]# ansible webservers -m mount -a "src=172.16.1.31:/data/zrlog path=/test_zrlog fstype=nfs opts=defaults state=unmounted" -i hosts

九、cron

minute      #分
hour        #時 
day         #日 
month       #月 
week        #周 
job         #
[root@manager project1]# ansible webservers -m cron -a 'name=test_job minute=00 hour=02 job="/bin/bash /server/scripts/client_to_data_server.sh &>/dev/null"' -i hosts
[root@manager project1]# ansible webservers -m cron -a 'name=test  job="/bin/bash /server/scripts/test.sh &>/dev/null"' -i hosts
[root@manager project1]#  ansible webservers -m cron -a 'name=test  job="/bin/bash /server/scripts/test.sh &>/dev/null" state=absent' -i hosts

十、firewalld

[root@manager project1]# ansible webservers -m systemd -a "name=firewalld state=started" -i hosts
#針對服務 
[root@manager project1]# ansible webservers -m firewalld -a "service=http state=enabled" -i hosts
#針對端口 
[root@manager project1]# ansible webservers -m firewalld -a "port=9999/tcp state=enabled" -i hosts

#針對source來源


#針對rule

十一、selinux

[root@manager project1]# ansible webservers -m selinux -a "state=disabled" -i hosts

12.get_url 13.yum_repositry

1.安裝http服務 yum 2.編寫簡單網頁測試內容 copy 3.啓動服務並加入開機自啓 service/systemd 4.放行對應的端口 firewalld

Ansible playbook

一、什麼是playbook

  • playbook 劇本

    • play #找誰
    • task #作什麼
      • 找多個明星,作多件事情
      • 找一個明星,作多個事情

    1570668657408

二、playbook和Asd-Hoc的區別

1570668794340

三、playbook三板斧,縮進、冒號、短橫線(語法格式)

1570669070952


模塊地址:

https://docs.ansible.com/ansible/latest/modules/list_of_all_modules.html


#語法示例
[root@manager project1]# vim f1.yml
[root@manager project1]# cat f1.yml 
- hosts: webservers
  tasks:

    - name: Create New File
      file: path=/tmp/123.txt state=touch owner=root group=root mode=0600

    - name: Create New File2
      file:    
        path: /tmp/456.txt
        state: touch
        owner: root
        group: root
        mode: 0666
[root@manager project1]# ansible-playbook f1.yml -i hosts

PLAY [webservers] **************************************************************

TASK [Gathering Facts] *********************************************************
ok: [172.16.1.8]
ok: [172.16.1.7]

TASK [Create New File] *********************************************************
changed: [172.16.1.7]
changed: [172.16.1.8]

TASK [Create New File2] ********************************************************
changed: [172.16.1.7]
changed: [172.16.1.8]

PLAY RECAP *********************************************************************
172.16.1.7                 : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
172.16.1.8                 : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
案例1、使用ansible安裝並配置nfs
一、將10.0.0.7上的文件推一份至ansible控制端
[root@web01 ~]# scp -rp /etc/nginx/nginx.conf root@172.16.1.61:/project1/file/nginx.conf.j2
二、在ansible控制端書寫nfs_servers.yml腳本
[root@manager project1]# cat nfs_servers.yml #編輯nfs前端文件
- hosts: nfsservers
  tasks:
    - name: Installed NFS Server
      yum:
        name: nfs-utils
        state: present

    - name: Configure NFS Server
      copy:
        src: ./file/exports.j2
        dest: /etc/exports
        owner: root
        group: root
        mode: 0644
        backup: yes
    - name: Create NFS Group www
      group:
        name: www
        gid: 666
    - name: Create NFS User www
      user:
        name: www
        group: www
        uid: 666
        create_home: no
        shell: /sbin/nologin

    - name: Create NFS Share Directory
      file:
        path: /ansible_data
        state: directory
        owner: www
        group: www
        mode: 0755
        recurse: yes
    - name: Systemd NFS Server
      systemd:
        name: nfs
        state: restarted
        enabled: yes

#語法檢測:[root@manager project1]# ansible-playbook --syntax nfs_servers.yml -i hosts

playbook: nfs_servers.yml


三、在nfs(10.0.0.31)上編輯配置文件
[root@nfs ~]# cat /etc/exports
/ansible_data 172.16.1.0/24(rw,sync,all_squash,anonuid=666,anongid=666)
四、在ansible控制端書寫nfs_client.yml腳本
[root@manager project1]# vim nfs_client.yml 
- hosts: webservers
  tasks:

    - name: Mount NFS Server share directory
      mount:
        src: 172.16.1.31:/ansible_data
        path: /mnt
        fstype: nfs
        opts: defaults
        state: mounted


#語法檢測:[root@manager project1]# ansible-playbook --syntax nfs_client.yml -i hosts

playbook: nfs_client.yml

五、在10.0.0.7和10.0.0.8查看是否掛載成功
[root@web01 ~]# df -h
172.16.1.31:/ansible_data   38G  1.8G   37G   5% /mnt

案例二:ansible安裝nginx服務

步驟詳解#1.建立一對公鑰和私鑰
[root@manager-61 project1]#ssh-keygen -C manager@qq.com    #一路回車
[root@manager-61 project1]#ssh-copy-id -i ~/.ssh/id_rsa root@172.16.1.7
[root@manager-61 project1]#ssh-copy-id -i ~/.ssh/id_rsa root@172.16.1.8
[root@manager-61 project1]# ansible all -m ping -i hosts #測試全部主機是否能ping通
#2.配置hosts文件,添加webservers主機組
[root@manager-61 project1]# vim hosts
[webservers]
172.16.1.7 
172.16.1.8 

#3.編寫一個安裝nginx的.yml文件(統一將.yml的文件同一個目錄下)
    #編寫思路:
	         #1.安裝nginx		yum 
	         #2.配置nginx		copy
	         #3.初始化環境
	         	用戶			group user
	         	目錄			file
	        	受權			file
	#4.啓動服務  
	
[root@manager-61 project1]# vim nginx.yml 
- hosts: webservers
  tasks:
    - name: install nginx
      yum:
        name: nginx
        state: present
    - name: configure nginx
      copy:
        src: ./file/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: 0644
        backup: yes
      notify: Restart Nginx
    - name: systemd nginx
      systemd:
        name: nginx
        state: started
        enabled: yes
  handlers:
    - name: Restart Nginx
      systemd: 
        name: nginx
        state: restarted
#4.準備好配置文件中所須要的文件
[root@manager-61 project1]# rsync -avz root@172.16.1.7:/etc/nginx/nginx.conf ./file/nginx.conf.j2
#5.檢測語法,並執行.yml文件
[root@manager-61 project1]# ansible-playbook --syntax  nginx.yml -i hosts
[root@manager-61 project1]# ansible-playbook -i hosts nginx.yml

案例3、使用ansible-playbook編寫LAMP服務

#1.建立一對公鑰和私鑰
[root@manager-61 project1]#ssh-keygen -C manager@qq.com
[root@manager-61 project1]#ssh-copy-id -i ~/.ssh/id_rsa root@172.16.1.31
[root@manager-61 project1]#ssh-copy-id -i ~/.ssh/id_rsa root@172.16.1.41
[root@manager-61 project1]# ansible all -m ping -i hosts #測試全部主機是否能ping通
#2.配置hosts文件,添加web主機組
[root@manager-61 project1]# vim hosts
[nfsservers]
172.16.1.31
[backupservers]
172.16.1.41
[web:children]
nfsservers
backupservers
#3.編寫一個lam.yml 文件
[root@manager-61 project1]# vim lam.yml
- hosts: web
  tasks:
    - name: Installed Httpd Server
      yum: 
        name: httpd
        state: present

    - name: Installed PHP Server
      yum: 
        name: php
        state: present

    - name: Configure Httpd WebSite
      get_url:
        url: http://fj.xuliangwei.com/public/index.php
        dest: /var/www/html/index.php
        mode: 0644

    - name: Systemd Httpd Server
      systemd:
        name: httpd
        state: started

    - name: Systemd Firewalld Server
      systemd:
        name: firewalld
        state: started


    - name: Configure Firewalld Rule
      firewalld:
        service: http
        state: enabled
#4.檢測語法,並執行.yml文件
[root@manager-61 project1]# ansible-playbook --syntax  lamp.yml -i hosts 
[root@manager-61 project1]# ansible-playbook -i hosts lamp.yml

案例4:ansilble-playbook編寫kodclold網盤服務--Apache版本

#1.建立一對公鑰和私鑰
[root@manager-61 project1]#ssh-keygen -C manager@qq.com
[root@manager-61 project1]#ssh-copy-id -i ~/.ssh/id_rsa root@172.16.1.31
[root@manager-61 project1]#ssh-copy-id -i ~/.ssh/id_rsa root@172.16.1.41
[root@manager-61 project1]# ansible all -m ping -i hosts #測試全部主機是否能ping通
#2.配置hosts文件,添加web主機組
[root@manager-61 project1]# vim hosts
[nfsservers]
172.16.1.31
[backupservers]
172.16.1.41
[web:children]
nfsservers
backupservers
#3.編寫一個kod.yml 文件
[root@manager-61 project1]# vim kod.yml
- hosts: web
  tasks:
    - name: Installed Httpd Server
      yum:
        name: httpd
        state: present

    - name: Installed PHP Server
      yum:
        name: php
        state: present

    - name: Get kodcloud Code
      synchronize:              #同步
        src: ./file/kod
        dest: /var/www/html/kodcloud

    - name: Chomod kodcloud
      file:
        path: /var/www/html/
        owner: root
        group: root
        mode: 0777
        recurse: yes

    - name: Systemd Httpd Server
      systemd:
        name: httpd
        state: restarted
#4.準備文件中的文件
[root@manager-61 project1]# mkdir ./file/kod
[root@manager-61 project1]# rz 
[root@manager-61 project1]# unzip kodexplorer4.40.zip -d ./file/kod
#5.檢測語法,並執行.yml文件
[root@manager-61 project1]# ansible-playbook --syntax  kod.yml -i hosts 
[root@manager-61 project1]# ansible-playbook  kod.yml -i hosts

案例五:Ansible-Playbook-編寫KodCloud服務-Nginx版

#1.建立一對公鑰和私鑰
[root@manager-61 project1]#ssh-keygen -C manager@qq.com
[root@manager-61 project1]#ssh-copy-id -i ~/.ssh/id_rsa root@172.16.1.31
[root@manager-61 project1]#ssh-copy-id -i ~/.ssh/id_rsa root@172.16.1.41
[root@manager-61 project1]# ansible all -m ping -i hosts #測試全部主機是否能ping通
#2.配置hosts文件,添加web主機組
[root@manager-61 project1]# vim hosts
[nfsservers]
172.16.1.31
[backupservers]
172.16.1.41
[web:children]
nfsservers
backupservers
#3.編寫一個lnp.yml 文件
[root@manager-61 project1]# cat lnp.yml 
- hosts: web
  tasks:
    #1.配置yum源倉庫 nginx PHP
    - name: install nginx php repo
      yum_repository:
        name: nginx
        description: nginx repos
        baseurl: http://nginx.org/packages/centos/$releasever/$basearch/
        gpgcheck: no
    #2.配置yum源 PHP repo
    - name: install php repo
      yum_repository:
        name: webtatic-php
        description: php repos
        baseurl: http://us-east.repo.webtatic.com/yum/el7/x86_64/
        gpgcheck: no
    #3.安裝nginx和PHP
    - name: install nginx and php packages
      yum:
        name: "{{ packages }}"
      vars:
        packages:
          - nginx
          - php71w
          - php71w-cli
          - php71w-common
          - php71w-devel
          - php71w-gd
          - php71w-fpm
          - php71w-opcache
          - mod_php71w
    #4.建立程序啓動的用戶身份
    - name: create group www
      group:
        name: www
        gid: 666
    - name: create user www
      user:
        name: www
        uid: 666
        group: www
        create_home: no
        shell: /sbin/nologin
    #5.管理nginx配置文件
    - name: configure nginx.conf
      copy:
        src: ./file/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: resatrt nginx
    #6.管理php-fpm配置文件
    - name: configure php-fpm.conf
      copy:
        src: ./file/www.conf.j2
        dest: /etc/php-fpm.d/www.conf
      notify: restart php-fpm 
    #7.添加虛擬主機
    - name: add nginx kod.ltc.com
      copy:
        src: ./file/kod.ltc.com.conf.j2
        dest: /etc/nginx/conf.d/kod.ltc.com.conf
      notify: restart nginx
    - name: Init Nginx BseEnv
      file:
        path: /code
        state: directory
        owner: www
        group: www
        recurse: yes
    - name: push kod code
      synchronize:
        src: ./file/kod
        dest: /code/
    - name: chmod kod
      file:
        path: /code
        owner: www
        group: www
        mode: 0777
        recurse: yes
    - name: systemd nginx
      systemd:
        name: nginx
        state: started
        enabled: yes
    - name: systemd php
      systemd:
        name: php-fpm
        state: started
        enabled: yes
 #當nginx或PHP配置文件發生改變時觸發重啓
  handlers:
    - name: restart nginx
      systemd:
        name: nginx
        state: restarted
    - name: restart php-fpm
      systemd:
        name: php-fpm
        state: restarted

#4.準備playbook中須要的文件
[root@manager-61 project1]# rsync -avz root@172.16.1.7:/etc/nginx/nginx.conf ./file/nginx.conf.j2
[root@manager-61 project1]# rsync -avz root@172.16.1.7:/etc/php-fpm.d/www.conf ./file/www.conf.j2
#5.檢測語法,並執行.yml文件
[root@manager-61 project1]# ansible-playbook --syntax  lnp.yml -i hosts
[root@manager-61 project1]# ansible-playbook lnp.yml -i hosts



Ansible varialbes

一、什麼是變量?

​ *** 定義:一個固定的字符串表示一個不固定的值。

​ *** 場景還原:三個地方、三個目錄位置,當有一天目錄發生變動,難道咱們要去逐一 改正?

​ ** ----------->引出-------->設定變量

1.在playbook中定義變量
vars  關鍵字
[root@manager project1]# cat f2.yml 
- hosts: webservers
  vars:
    - file_name: playbook_vars

  tasks:
    - name: Create New File
      file:
        path: /tmp/{{ file_name }}
        state: touch
  • vars_file 屬於一種共享的方式
[root@manager project1]# cat vars_file.yml 
web_packages: httpd
ftp_packages: vsftpd

[root@manager project1]# cat f2.yml 
- hosts: webservers
  vars:
    - file_name: playbook_vars

 #調用共享vars_file文件,只不過恰好文件名叫vars_file
  vars_files: ./vars_file.yml

  tasks:
    - name: Create New File
      file:
        path: /tmp/{{ file_name }}
        state: touch

    - name: Installed Packages {{ web_packages }}
      yum:
        name: "{{ web_packages }}"
        state: present
  • 二、在inventory主機清單中定義變量
一、清單文件中直接定義hosts文件定義
[webservers]
172.16.1.7
172.16.1.8 
[webservers:vars]
file_name=hostsfile_group_vars


二、建立hosts_vars  group_vars 目錄
[root@manager project1]# mkdir host_vars	#單個主機
[root@manager project1]# mkdir group_vars	#主機組
#1.單個主機定義和使用方式 (host_vars能分別對不一樣的主機定義變量)
[root@manager project1]# cat host_vars/172.16.1.7 
host_vars_name: 172.16.1.7

[root@manager project1]# cat host_vars/172.16.1.8 
host_vars_name: 172.16.1.8

[root@manager project1]# cat f4.yml 
- hosts: webservers

  tasks:
    - name: Create New File
      file:
        path: /opt/{{ host_vars_name }}
        state: touch

#二、針對主機組定義的方式
#給指定的主機webserver組設定變量,其餘組主機沒法使用該變量。

[root@manager project1]# vim group_vars/webservers 
group_host_vars: webservers

[root@manager project1]# vim f5.yml 
- hosts: webservers
  tasks:
    - name: Create New File {{ group_host_vars }}
      file:
        path:  /opt/{{ group_host_vars }}
        state: touch

#三、針對主機組定義的方式  (給全部的主機和主機組設定變量)
[root@manager project1]# vim group_vars/all 
group_host_vars: all

[root@manager project1]# vim f5.yml 
- hosts: webservers
  tasks:
    - name: Create New File {{ group_host_vars }}
      file:
        path:  /opt/{{ group_host_vars }}
        state: touch
  • 三、經過外置傳參數定義變量 -e
[root@manager project1]# ansible-playbook -i hosts f6.yml  -e "web_vars=123"
  • ##若是變量衝突???優先級解決。。。
6.定義相同的變量不一樣的值,測試變量的優先級。操做步驟以下   file_name:
  1)在plabook中定義vars變量
  2)在playbook中定義vars_files變量
  3)在inventory主機定義變量
  4)在inventory主機組定義變量
  5)在host_vars中定義變量
  6)在group_vars中定義變量  組      all組
  7)經過執行命令傳遞變量
  
優先級測試:
外置傳入參數優先級最高 ---> playbook ( vars_files(共享)--->vars(私有) )  
---> host_vars  --> group_vars/group_name ---> group_vars/all

四、變量註冊

[root@manager project1]# cat f8.yml 
- hosts: webservers
  tasks:
        # System_Status=$(netstat -lntp)
    - name: Get Network Status
      shell: netstat -lntp | grep "nginx"
      register: System_Status

        # echo "$System_Status"
    - name: Debug output Variables
      debug:
        msg: "{{ System_Status.stdout_lines }}"

5.facts變量?

#1.根據主機的cpu信息,生成不一樣的配置.
	A: 1核心    work_process 1;
	B: 2核心    work_process 2;
	
#2.根據主機名稱設定不一樣配置文件
	zabbix_agent
		Server:   ===> 指向172.16.1.61
		Hostname:      web01   web02

[root@manager project1]# cat ./file/zabbix_agent.conf.j2 
Server={{ zabbix_server_ip }}
ServerActive={{ zabbix_server_ip }}
Hostname={{ ansible_hostname }}

[root@manager project1]# cat f11.yml 
- hosts: webservers
  vars:
    - zabbix_server_ip: 172.16.1.61
  tasks:
    - name: Configure zabbix-agent.conf
      template:
        src: ./file/zabbix_agent.conf.j2
        dest: /tmp/zabbix-agent.conf
        
        
#3.根據主機的內存生成不一樣的配置文件,memcached
[root@manager project1]# cat f12.yml 
- hosts: webservers
  tasks:
    - name: Installed Memcached Server
      yum:
        name: memcached
        state: present

    - name: Configure Memcached Server
      template:
        src: ./file/memcached.j2
        dest: /etc/sysconfig/memcached
      notify: Restart Memcached Server

    - name: System Memcached Server
      systemd:
        name: memcached
        state: started
        enabled: yes

  handlers:
    - name: Restart Memcached Server
      systemd:
        name: memcached
        state: restarted

[root@manager project1]# cat file/memcached.j2 
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="{{ ansible_memtotal_mb //2 }}"
OPTIONS=""


1.根據cpu
2.根據內存
3.根據主機名
4.Redis配置文件     bind本地地址
5.操做系統不統一

		變量能夠進行運算  + - * // 
		
		
		
		
#1.定義變量
	playbook
		vars			私有
		vars_files		共享
	inventory
		host_vars	
		group_vars
			group_vars/group_name
			group_vars/all
	外置傳參
		-e
#2.測試優先級
	在不改變playbook變量的狀況下,使用新的值測試.

#3.變量註冊register
	1.將任務執行的結果存儲至特定的變量中
	2.可使用debug模塊將變量進行打印輸出
	
	python: 字典
	json 格式化數據
	{
        k1: v1
        k2: v2
	}
#4.facts

1570807064349

[root@manager project1]# cat f13.yml 
- hosts: webservers
  tasks:
    - name: RANDOM
      shell:  echo "$RANDOM"
      register: System_SJ

    - name: Debug 
      debug:
        msg: "web_{{ System_SJ.stdout }}"

#1.提取facts變量中的IP地址   mac地址  UUID 等等  只要惟一
	ansible_default_ipv4.address
[root@manager project1]# cat f14.yml 
- hosts: webservers
  tasks:

    - name: Debug 
      debug:
        msg: "web_{{ ansible_default_ipv4.address }}"

Ansible 流程控制


8.判斷語句

  • 1.centos和ubuntu系統都須要安裝httpd, 判斷系統.
  • 2.安裝軟件倉庫,只有web組的安裝webtatic其餘的主機所有跳過.
  • 3.TASK任務, TASK1任務執行成功,纔會執行TASK2

#根據不一樣的系統,安裝不一樣的服務
- hosts: webservers
  tasks:
    - name: CentOS Installed Httpd Server
      yum:
        name: httpd
        state: present
      when: ( ansible_distribution == "CentOS" )

    - name: Ubuntu Installed Httpd Server
      yum:
        name: httpd2
        state: present
      when: ( ansible_distribution == "Ubuntu" )
      
[root@manager project1]# cat f16.yml 
- hosts: all
  tasks:
  - name: Add Nginx Yum Repository
    yum_repository:
      name: nginx
      description: Nginx Repository
      baseurl: http://nginx.org/packages/centos/7/$basearch/
    when: ( ansible_hostname is match ("web*"))


[root@manager project1]# cat f17.yml 
- hosts: webservers
  tasks:

    - name: Check Httpd Server
      command: systemctl is-active httpd
      register: Check_Httpd
      ignore_errors: yes

	#判斷Check_Httpd.rc是否等於0,若是爲0則執行任務,不然不執行
    - name: Restart Httpd Server
      systemd:
        name: httpd
        state: restarted
      when: ( Check_Httpd.rc == 0 )

九、循環語句

#一次啓動多個服務
[root@manager project1]# cat f18.yml 
- hosts: webservers
  tasks:
    - name: Systemd Nginx Status
      systemd:
        name: "{{ item }}"    #調用的變量也不變,也是固定
        state: started

	#固定的語法格式
      with_items:
        - nginx
        - php-fpm


#一次拷貝多個文件
[root@manager project1]# cat f19.yml
- hosts: webservers
  tasks:
    - name: Configure nginx.conf
      copy:
        src: '{{ item.src }}'
        dest: '{{ item.dest }}'
        mode: '{{ item.mode }}'
      with_items:
        - { src: ./file/nginx.conf.j2, dest: /etc/nginx/nginx.conf, mode: '0644' }
        - { src: ./file/kold.oldxu.com.conf.j2, dest: /etc/nginx/conf.d/kold.oldxu.com.conf, mode: '0600' }



#建立多個用戶,一次建立多個? 3個用戶  TASK
[root@manager project1]# cat f20.yml 
- hosts: webservers
  tasks:
    - name: Create User
      user:
        name: "{{ item }}"

      with_items:
        - test1
        - test2
        - test3
        - test4


#1.建立tt1 --> bin  tt2 -->root tt3 --->adm   附加組
[root@manager project1]# cat  f20.yml 
- hosts: webservers
  tasks:
    - name: Create User
      user:
        name: "{{ item.name }}"
        groups: "{{ item.groups }}"

      with_items:
        - { name: tt1, groups: bin }
        - { name: tt2, groups: root }
        - { name: tt3, groups: adm }
        
        
        
1.標準循環                   --->居多
	item
	with_items:
	   - test
2.字典循環:                   --->居多
    itme.name
    with_items:
        - { name: test }


3.變量循環
- hosts: webservers
  tasks:
    - name: ensure a list of packages installed
      yum: name={{ packages }} state=present
      vars:
        packages:
          - httpd
          - httpd-tools

10.handlers

[root@manager project1]# cat f22.yml 
- hosts: webservers
  tasks:

    - name: Installed Nginx and PHP Packages
      yum:
        name: nginx
        state: present

    - name: Configure nginx.conf 
      template:
        src: ./file/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      #監控-->changed狀態-->通知-->handlers--->name-->Restart Nginx Server
      notify: Restart Nginx Server
      #notify:
      #  - Restart Nginx Server
      #  - Restart php Server

    - name: Systemd Nginx Server
      systemd:
        name: nginx
        state: started
        enabled: yes

#當nginx或php配置文件發生變動纔會觸發此操做
  handlers:
    - name: Restart Nginx Server
      systemd:
        name: nginx
        state: restarted


#3.handlers注意事項
	1.不管多少個task通知了相同的handlers,handlers僅會在全部tasks結束後運行一次。
	2.只有task發生改變了纔會通知handlers,沒有改變則不會觸發handlers.
	3.不能使用handlers替代tasks、由於handlers是一個特殊的tasks。
相關文章
相關標籤/搜索