Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The realization process of Ansible-Playbook batch initialization Server

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

Initialization step

Configure ssh key authentication remote configuration hostname control remote hosts add HOSTS resolution configure remote host yum source and some software time synchronization configuration close selinux/iptables modify sshd configuration ssh key authentication in the master node / etc/ansible/hosts configuration node $vim / etc/ansible/ hosts [new] 192.168.56.12192.168.56.13 ssh recognition configured to the controlled node in the control node Certificate mode # the master node executes $ssh-keygen-t rsa-f ~ / .ssh/id_rsa-N''$for host in 192.168.56. {11. 12} Dossh-keyscan $host > > ~ / .ssh/hnow_hosts 2 > / dev/nullsshpass-p '123456' ssh-copy-id root@$host & > / dev/nulldone

Playbookize the above scheme:

-name: config ssh connection hosts: new gather_facts: false tasks:-name: configure ssh connection shell: | ssh-keyscan {{inventory_hostname}} > > ~ / .ssh/know_hosts sshpass-p '123456' ssh-copy-id root@ {{inventory_hostname}} ansible command execution module

The following four modules do not satisfy idempotency

Command: execute simple shell commands shell: same as command, but support pipeline tycoon raw: execute underlying shell commands, usually use this module when installing python on the target host script: execute scripts on remote hosts

The following commands are idempotent:

Creates: executes when the specified file or directory does not exist. Removes is not executed when the specified file or directory does not exist. There is execution-name: modules use hosts: new gather_facts: false tasks:-name: use shell module shell: cp / tmp/my.cnf / etc/my.cnf args: creates: / etc/my.cnf-name: exec perl scripts script: / opt/script.pl args: executable: perl key connection: connection method (smart | ssh | paramiko | local | docker | winrm) Smart by default means that only ssh or paramikodelegate_to can be selected: can only be defined at the task level The effect is similar to that of connection-name: play1 hosts: zabbix gather_facts: false tasks:-name: task 1 debug: msg: "{{inventory_hostname}} is executing task" delegate_to: localhostauthorized_key module

Features:

Distribution of ssh public key is not responsible for host authentication phase

You need to configure the ansible_passwd field [new] 192.168.56.11 ansible_hostname= "centos7-node1" 192.168.56.12 ansible_hostname= "centos7-node2" [new:vars] ansible_password= "yeecallk8s" under hosts.

Distribute authentication configuration

-name: "configure ssh connection" hosts: new gather_facts: false tasks:-authorized_key: key: "{{lookup ('file','~/.ssh/id_rsa.pub')}}" state: present user: root

How external data is read:

Lookup (): support from file,redis,etcd,pipe,vars,list,dictfileglob: support configuration of file names File specifies the file, and pipe returns data from the command execution result-name: "fileglob and file task" hosts: new gather_facts: false tasks:-name: task1 debug: msg: "filenames: {{lookup ('fileglob','/etc/*.conf')}}"-name: task2 debug: msg: "filecontents: {{lookup (' file') '/ etc/hosts')}} query (): read the configuration file Return list format-name: "fileglob and files query" hosts: new gather_facts: false tasks:-name: "fileglob" debug: msg: "fileglob {{lookup ('fileglob','/etc/*.conf')}}"-name: "fileglob wantlist" debug: msg: "fileglob wantlist {{lookup (' fileglob','/etc/*.conf') Wantlist=True)} "- name:" query "debug: msg:" query {{Q ('fileglob','/etc/*.conf')}} "sets the hostname

Using the hostname module, the / etc/hostname configuration file is modified directly

-name: set hostname hosts: new gather_facts: false vars: hostnames:-host: 192.168.56.13 name: centos7-node3-host: 192.168.56.14 name: centos7-node4 tasks:-name: set hostname hostname: name: "{{item.name}}" when: item.host = = inventory_hostname loop: "{{hostnames}}"

Note for setting the vars variable:

Set at the play level, all task within the play range can access these variables, while other play cannot access the setting at the task level This variable can only be accessed within the task range-name: vars task1 hosts: new gather_facts: false vars:-var1: "value1" tasks:-name: access value1 debug: msg: "var1 in task1 {{var1}}"-name: vars task2 hosts: new gather_facts: false tasks:-name: can not access vars from task1 debug: msg: var1-name: set and access var2 in This task debug: msg: var2 vars: var2: "value2"-name: cant access var2 debug: msg: var2

When condition judgment

Execute the task when when determines that it is true Otherwise, do not execute-name: when judge hosts: new gather_facts: false vars:-myname: "alex" tasks:-name: task skip debug: msg: "myname is {{myname}}" when: myname = = "hello" # the judgment condition is false's-name: task will execute debug: msg: "myname is {{myname}}" when: myname = = "alex"

Loop loop: solving repetition problems

Examples of unused loops-name: make dirs for localhost hosts: localhost gather_facts: false tasks:-name: create test1 file: path: / tmp/test1 state: directory-name: create test2 file: path: / tmp/test2 state: directory examples of using loops-name: mkdir loop hosts: localhost gather_facts: false tasks:-name: create test1,2 directory file : path: "{{item}}" state: directory loop:-/ tmp/test01-/ tmp/test02 add hosts (DNS) hostname resolution

Hosts resolution between host of a specified hosts group added to each other

-name: add hosts DNS hosts: new gather_facts: false tasks:-name: add DNS lineinfile: path: / etc/hosts line: "{{item}} {{hostvars [item] .ansible _ hostname}}" when: item! = inventory_hostname loop: "{{play_hosts}}" lineinfile module: insert, delete, replace lines in the source file Similar to sed # create an append instance of the test file a.txt paragraph 1first linein paragraph 1second linein paragraph 1paragraph 2first linein paragraph 2second linein paragraph 2 upload # lineinfile-name: add line to a.txt hosts: localhost gather_facts: false tasks:-lineinfile: path: "a.txt" line: "append new line" state: absent # Delete the line defined by line above (append new line) # insert operation The definition is added before or after the line (insertbefore Insertafter)-name: lininfile demo for before and after insert hosts: localhost gather_facts: false tasks:-name: lineinfile lineinfile: path: "a.txt" line: "LINE1" insertbefore:'^ para.* 2' firstmatch: yes lineinfile: path: "a.txt" line: "LINE2" insertafter:'^ para.* 2' Firstmatch: yesplay_hosts and hostvars variables inventory_hostname: denote the names play_hosts and hostvars defined in the host inventory: are predefined variables You can use it directly when performing tasks. Play_hosts is equivalent to a list of all the hosts in the new host group. Hostvars: save the variable-name: add DNS lineinfile: path: / etc/hosts line: "{{item}} {{hostvars [item] .ansible _ hostname}}" when: item! = inventory_hostname loop: "{{play_hosts}}" configure the yum source and download the installation software

Replace the yum source and install the software

-name: "init yum" hosts: new gather_facts: false tasks:-name: "backup old yum_repo" shell: cmd: "mkdir bak Mv * .repo bak "chdir: / etc/yum.repos.d creates: / etc/yum.repos.d/bak-name:" add new os repo and release repo "yum_repository: name:" {{item.name}} "description:" {{item.name}} repo "baseurl:" {{item.baseurl}} "file:" {{item. Name} "enabled: 1 gpgcheck: 0 reposdir: / etc/yum.repos.d loop:-name: os baseurl:" https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/os/$basearch"-name: epel baseurl: "https://mirrors.tuna.tsinghua.edu.cn/epel/$releasever/$basearch"-name: install pkgs yum: name: vim Net-tools,git-core,lrzsz,wget,curl,sysstat,iotop,gcc,gcc-c++,cmake,pcre,pcre-devel,zlib,zlib-devel,openssl,openssl-devel,vim,wget,telnet,setuptool,lrzsz,dos2unix,net-tools,bind-utils,tree,screen,iftop,ntpdate,tree,lsof,iftop,iotop,sysstat,procps state: present time synchronization

Use ntpdate to synchronize time

-name: sync time hosts: new gather_facts: false tasks:-name: install and sync time block:-name: install ntpdate yum: name: ntpdate state: present-name: ntpupdate to sync time shell: | ntpdate ntp1.aliyun.com hwclock-wblock organizes two related tasks to turn off selinux

Two ways to close the command line and modify the configuration file

-name: disable selinux hosts: new gather_facts: false tasks:-block:-name: disable selinux by command shell: setenforce 0-name: disable selinux by config lineinfile: path: / etc/selinux/config line: "SELINUX=disabled" regexp:'^ SELINUX=' ignore_errors: true configuration firewall-name: set Firewalld hosts: new gather_facts: false tasks:-name: set iptables rule shell: | iptables-save > / tmp/iptables.bak$ (date + "% FMI% T") iptables- X iptables- F iptables- Z systemctl disable firewalld systemctl stop firewalld configuration sshd Service requirements: root users are not allowed to log in. Do not allow password login-name: "set sshd service" hosts: new gather _ facts: false tasks:-name: backup old sshd config shell: | / usr/bin/cp-f {{path}} {{path}. Bak vars:-path: / etc/ssh/sshd_config-name: disable root login lineinfile: path: "/ etc/ssh/sshd_config" line: "PermitRootLogin no" regexpr:'^ PermitRootLogin' notify: "restart sshd"-name: disable passwd auth lineinfile: path: "/ etc/ssh/sshd_config" line: "PasswordAuthentication no" regexp:'^ PasswordAuthentication yes' notify: "restart sshd" handlers:-name: "restart sshd" service: name: sshd state: restarted

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report