未分类
批量插入/替换整段代码到指定位置
需求是用ansible来修改nginx配置文件,添加代理gotty打开终端的逻辑,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
--- - name: modify nginx configure gather_facts: F hosts: nginx pre_tasks: - name: define variables set_fact: nginx_conf: /data/middleware/nginx/conf.d/upstream-tomcat.conf tasks: - name: "modify nginx configure - part 1" shell: cmd: | time=$(date +%F) sed -i "1i\# modified at $time" upstream-tomcat.conf Bstr='\# modified at' Estr='upstream dashboard' sed -n " /$Bstr/ { n :start /$Estr/! { N b start } p } " map.txt | sed " /$Bstr/ { n :start /$Estr/! { N b start } r /dev/stdin d } " {{ nginx_conf }} > {{ nginx_conf }}.new mv -f {{ nginx_conf }}.new {{ nginx_conf }} - name: "modify nginx configure - part 2" shell: cmd: | Bstr='# --- END FOR KUBOARD ---' Estr='location.*.\/redis\/' sed -n " /$Bstr/ { n :start /$Estr/! { N b start } p } " location.txt | sed " /$Bstr/ { n :start /$Estr/! { N b start } r /dev/stdin d } " {{ nginx_conf }} > {{ nginx_conf }}.new mv -f {{ nginx_conf }}.new {{ nginx_conf }} |
map.txt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
map $http_upgrade $connection_upgrade { default upgrade; '' close; } map $http_cookie $c_cookie { default ""; ~*host=([^\;]*) $1; } map $args $r_host { default $c_cookie; ~*host=(.*) $1; } upstream dashboard { |
location.txt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# --- END FOR KUBOARD --- # --- START FOR gotty --- location ~ /webterminal/ { if ($uri = /webterminal/ ){ set $hostip "$r_host"; set_decode_base64 $hostip; proxy_pass http://$hostip:50000; rewrite /webterminal/(.*)$ /$1 break; add_header Set-Cookie "host=$hostip"; } if ($uri ~ .js){ proxy_pass http://$c_cookie:50000; rewrite /webterminal/(.*)$ /$1 break; } if ($uri ~ webterminal/ws){ rewrite /(.*)$ /webterminalws last; } } location ~ /webterminalws { proxy_pass http://$c_cookie:50000/ws; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; } # --- END FOR gotty --- location ^~ /redis/ { |
注意: 需要插入/替换的新内容:map.txt和location.txt 开始和结束的匹配字段也要写上去(Bstr和Estr)