使用ansible的剧本制作salt-master与salt-minion的安装与启动服务过程

虚拟机版本:Rocky Linux release 8.6 (Green Obsidian)

准备几台虚拟机

ipv4地址主机名
192.168.137.13center
192.168.137.14sp-1
192.168.137.15sp-2
192.168.137.16sp-3

一、center主机的配置

1.vim /etc/hosts


127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.137.13 center
192.168.137.14 sp-1
192.168.137.15 sp-2
192.168.137.16 sp-3

2.下载ansible-core

yum -y install ansible-core

3.配置ansible,执行剧本

3-1. 新建ansible目录,进入该目录,整个剧本操作都在ansible目录中完成

mkdir ansible
cd ansible

3-2. vim ansible.cfg

[defaults]
inventory=inventory
host_key_checking=False

注意事项,如果不是root用户,是sudo免密提权的普通用户alice可以这么写:

[defaults]
inventory=/home/alice/ansible/inventory #清单文件
roles_path=/home/alice/ansible/roles #角色目录
collections_paths=/home/alice/ansible/collections 
#collection 目录,多个目录冒号:分隔(仅适用于 RHEL9)
remote_user=alice #远程用户
[privilege_escalation] #sudo 提权
become=True #是否提权
become_method=sudo #提权方式
become_user=root #提权用户
become_ask_pass=False #是否需要密码

3-3.vim inventory

[master]
center
[minions]
center
sp-[1:3]
[master:vars]
ansible_connection=local
[minions:vars]
ansible_ssh_pass=a

检查ansible是否配置成功:

[root@localhost ansible]# ansible all -m ping
[WARNING]: Platform linux on host center is using the discovered Python interpreter at /usr/bin/python3.8,
but future installation of another Python interpreter could change the meaning of that path. See
https://docs.ansible.com/ansible-core/2.12/reference_appendices/interpreter_discovery.html for more
information.
center | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3.8"
    },
    "changed": false,
    "ping": "pong"
}
sp-2 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
sp-3 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
sp-1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

注意:这步失败的话,如果检查前面的代码也没问题,可以把第二步免密ssh登录做了再试试

3-4. vim install.yml

---
- hosts: all
  gather_facts: false
  tasks:
    - name: get salt.repo
      shell: |
        sudo rpm --import https://repo.saltproject.io/py3/redhat/8/x86_64/latest/SALTSTACK-GPG-KEY.pub
        sudo curl -fsSL https://repo.saltproject.io/py3/redhat/8/x86_64/latest.repo | tee /etc/yum.repos.d/salt.repo
        sudo yum clean all
      become: true

    - name: get master name
      set_fact:
        master_name: "{{ groups['master'][0] }}"

    - name: get master ip
      shell:  "cat /etc/hosts | grep {{ master_name }} | awk '{print $1}'"
      register: shell_out

    - name: set master_ip
      set_fact:
        master_ip: "{{ shell_out.stdout }}"

    - name: debug master_name and master_ip
      debug:
        msg: "master_name = {{ master_name }}, master_ip = {{ master_ip }}"

- hosts: master
  gather_facts: false
  tasks:
    - name: install salt-master
      yum:
        name: salt-master
        state: present
      become: true

    - name: change master configuration
      shell: "sed -i 's/^#interface.*/interface: {{ master_ip }}/' /etc/salt/master"
      become: true

    - name: start salt-master
      service:
        name: salt-master
        enabled: yes
        state: started
      become: true

- hosts: minions
  gather_facts: false
  tasks:
    - name: copy hosts to minions(为了获取salt-key)
      copy:
        src: /etc/hosts
        dest: /etc/hosts

    - name: install salt-minion
      yum:
        name: salt-minion
        state: present
      become: true
    
    - name: change minion configuration
      shell: "sed -i 's/^#master:.*/master: {{ master_name }}/' /etc/salt/minion"
      become: true
    
    - name: start salt-minion
      service:
        name: salt-minion
        enabled: yes
        state: started
      become: true

3-5.执行剧本

ansible-playbook install.yml

4.center主机获取salt-key

4-1.批量接受所有未接受的 minion

[root@localhost ansible]# salt-key -A
The following keys are going to be accepted:
Unaccepted Keys:
sp-1
sp-2
sp-3
Proceed? [n/Y] y
Key for minion sp-1 accepted.
Key for minion sp-2 accepted.
Key for minion sp-3 accepted.

4-2.检查是否获取成功:

[root@localhost ansible]# salt-key -L
Accepted Keys:
center
sp-1
sp-2
sp-3
Denied Keys:
Unaccepted Keys:
Rejected Keys:

4-3.也可以一次性接收多个salt-key:

salt-key -a sp-1,sp-2,sp-3

4-4.测试是否成功连接:

test.ping
[root@localhost ansible]# salt '*' test.ping
sp-3:
    True
sp-1:
    True
sp-2:
    True
center:
    True

#使用正则表达式,加-E参数
[root@localhost ansible]# salt 'sp-.*' -E test.ping
sp-1:
    True
sp-3:
    True
sp-2:
    True

#-L参数,将字符串以空格或者,号分隔开,再每个匹配展示

[root@localhost ansible]# salt 'sp-1,sp-2,sp-3' -L test.ping
sp-1:
    True
sp-3:
    True
sp-2:
    True
#或
[root@localhost ansible]# salt 'sp-1 sp-2 sp-3' -L test.ping
sp-1:
    True
sp-3:
    True
sp-2:
    True

#-G 选项用于基于 minion 的 grains 数据来进行目标定位(targeting)。Grains 是 SaltStack 中的一种数据结构,它允许 minion 收集有关自身的信息,并将这些信息报告给 master。Grains 可以包括操作系统类型、内核版本、硬件信息等各种系统元数据。使用 -G 选项,您可以根据这些 grains 数据来选择特定的 minion 执行命令
[root@localhost ansible]# salt 'fqdn:sp-1' -G test.ping
sp-1:
    True


#-C(大写)选项,混合方式
[root@localhost ansible]#  salt 'G@host:center or E@sp-[1-2]' -C test.ping
sp-2:
    True
center:
    True
sp-1:
    True
查看test.version
[root@localhost ansible]# salt '*' test.version
sp-2:
    3005.5
sp-1:
    3005.5
center:
    3005.5
sp-3:
    3005.5
 查看grains(采集硬件信息)
#grains,采集硬件信息
[root@localhost ansible]# salt 'sp-1' grains.ls
[root@localhost ansible]# salt 'sp-1' grains.items
#只要具体的几项:
[root@localhost ansible]# salt 'sp-1' grains.item host fqdn selinux master
sp-1:
    ----------
    fqdn:
        sp-1
    host:
        sp-1
    master:
        center
    selinux:
        ----------
        enabled:
            False
        enforced:
            Disabled
4-5.拒绝未接受的minion

拒绝所有:

[root@localhost ansible]# salt-key -R

拒绝指定的一个或多个minion:

salt-key -r sp-1,sp-2,sp-3

4-6.删除已接受的minion

拒绝所有:

[root@localhost ansible]# salt-key -D

批量删除已接受的具体某些minion:

[root@localhost ansible]# salt-key -d center,sp-1,sp-2,sp-3

5.配置/etc/salt/master

5-1.配置nodegroups

​
使用/etc/salt/master配置nodegroups

[root@localhost ansible]# vim  /etc/salt/master
加上
nodegroups:
  sp_group: L@sp-1,sp-2,sp-3

[root@localhost ansible]# systemctl restart salt-master
[root@localhost ansible]# salt -N sp_group cmd.run "ls"
sp-3:
    anaconda-ks.cfg
sp-2:
    anaconda-ks.cfg
sp-1:
    anaconda-ks.cfg


​

cmd.exec_code,cmd.exec_code_all 可以指定解释器执行命令:

[root@localhost ansible]# salt sp-1 cmd.exec_code_all sh "echo hello"
sp-1:
    ----------
    pid:
        14927
    retcode:
        0
    stderr:
    stdout:
        hello
[root@localhost ansible]# salt sp-1 cmd.exec_code sh "echo hello"
sp-1:
    hello

二、免密ssh登录sp-1,sp-2,sp-3

在center主机执行:

ssh-keygen一路回车
ssh-copy-id sp-1
有yes/no选项的=》yes
输入密码,回车

ssh-copy-id sp-2
同上

ssh-copy-id sp-3
同上

然后依然在center主机使用
ssh sp-1
到该主机后命令行输入exit返回center主机
ssh sp-2
同上
ssh sp-3
同上

 三、salt模块

列出所有的模块


[root@localhost ansible]# salt sp-1 sys.list_modules
sp-1:
    - acl
    - aliases
    - alternatives
    - archive
    - artifactory
    - at
    - baredoc
    - beacons
    - bigip
    - btrfs
    - buildout
    - chroot
    - cloud
    - cmd
    - composer
    - config
    - consul
    - container_resource
    - cp
    - cron
    - cryptdev
    - data
    - defaults
    - devinfo
    - devmap
    - dig
    - disk
    - django
    - dnsmasq
    - dnsutil
    - drbd
    - environ
    - ethtool
    - event
    - extfs
    - file
    - freezer
    - gem
    - genesis
    - glassfish
    - glusterfs
    - gnome
    - google_chat
    - grafana4
    - grains
    - group
    - hashutil
    - helm
    - highstate_doc
    - hosts
    - http
    - hue
    - incron
    - ini
    - inspector
    - introspect
    - iosconfig
    - ip
    - iptables
    - jboss7
    - jboss7_cli
    - jinja
    - k8s
    - kernelpkg
    - key
    - keyboard
    - kmod
    - kubeadm
    - locale
    - locate
    - log
    - logrotate
    - lowpkg
    - lvm
    - mandrill
    - match
    - mattermost
    - mine
    - minion
    - modjk
    - mount
    - msteams
    - nagios_rpc
    - namecheap_domains
    - namecheap_domains_dns
    - namecheap_domains_ns
    - namecheap_ssl
    - namecheap_users
    - network
    - nexus
    - nfs3
    - nova
    - nspawn
    - nxos
    - nxos_api
    - nxos_upgrade
    - openscap
    - openstack_config
    - opsgenie
    - out
    - pagerduty
    - pagerduty_util
    - pam
    - parallels
    - partition
    - peeringdb
    - pillar
    - pip
    - pkg
    - pkg_resource
    - ps
    - publish
    - pushover
    - pyenv
    - qemu_img
    - qemu_nbd
    - quota
    - raid
    - random
    - random_org
    - rbenv
    - rest_sample_utils
    - restartcheck
    - ret
    - rsync
    - rvm
    - s3
    - s6
    - salt_proxy
    - salt_version
    - saltcheck
    - saltutil
    - schedule
    - scsi
    - sdb
    - seed
    - selinux
    - serverdensity_device
    - service
    - shadow
    - slack
    - slsutil
    - smbios
    - smtp
    - solrcloud
    - sqlite3
    - ssh
    - state
    - status
    - statuspage
    - supervisord
    - sys
    - sysctl
    - sysfs
    - syslog_ng
    - system
    - telegram
    - telemetry
    - temp
    - test
    - timezone
    - tuned
    - udev
    - uptime
    - user
    - vault
    - vbox_guest
    - virtualenv
    - vsphere
    - x509
    - xfs
    - xml
    - zabbix
    - zenoss

 1.cmd模块

查看cmd的方法有哪些?

[root@localhost ansible]# salt 'sp-1' sys.list_functions cmd
sp-1:
    - cmd.exec_code
    - cmd.exec_code_all
    - cmd.has_exec
    - cmd.powershell
    - cmd.powershell_all
    - cmd.retcode
    - cmd.run
    - cmd.run_all
    - cmd.run_bg
    - cmd.run_chroot
    - cmd.run_stderr
    - cmd.run_stdout
    - cmd.script
    - cmd.script_retcode
    - cmd.shell
    - cmd.shell_info
    - cmd.shells
    - cmd.tty
    - cmd.which
    - cmd.which_bin

 查看cmd.run的帮助文档

[root@localhost ansible]# salt sp-1 sys.doc cmd.run

cmd.run使用示例:

[root@localhost ansible]# salt 'sp-1' cmd.run "ls -l;hostname"
sp-1:
    total 4
    -rw-------. 1 root root 1039 May 16 16:06 anaconda-ks.cfg
    sp-1

#批量执行
[root@localhost ansible]#  salt '*' cmd.run "hostname"
sp-3:
    sp-3
sp-2:
    sp-2
sp-1:
    sp-1
center:
    center

2.cp模块(复制)

查看帮助文档:

[root@localhost ansible]# salt sp-1 sys.doc cp

修改/etc/salt/master配置:

file_roots:
  base:
    - /srv/salt

重启salt-master

systemctl restart salt-master 

cp.get_file(获取文件)

[root@localhost ansible]# mkdir -p /srv/salt/files/
[root@localhost ansible]# vim /srv/salt/files/test_get.txt
这是master文件

#使用示例:
[root@localhost ansible]# salt sp-2 cp.get_file salt://files/test_get.txt /root/test.txt
sp-2:
    /root/test.txt
[root@localhost ansible]# salt sp-2 cmd.run "ls /root"
sp-2:
    anaconda-ks.cfg
    test.txt
[root@localhost ansible]# salt sp-2 cmd.run 'cat /root/test.txt'
sp-2:
    这个是master节点的文件!!!

cp.get_dir

#注意:不能是空目录,至少要有一个文件的目录才能使用这个方法

[root@localhost ansible]# mkdir -p /srv/salt/test_dirs
[root@localhost ansible]# salt sp-2 cp.get_dir salt://test_dirs/ /root/                                    sp-2:
#没有复制过去,因为是空目录
#给该目录加一个文件就可以了
[root@localhost ansible]# echo hello > /srv/salt/test_dirs/1.txt
[root@localhost ansible]# salt sp-2 cp.get_dir salt://test_dirs/ /root/
sp-2:
    - /root//test_dirs/1.txt
[root@localhost ansible]# salt sp-2 cmd.run 'ls /root/'
sp-2:
    anaconda-ks.cfg
    test.txt
    test_dirs
[root@localhost ansible]# salt sp-2 cmd.run 'ls /root/test_dirs'
sp-2:
    1.txt

cp.push


[root@localhost ansible]# vim /etc/salt/master
file_recv: True

[root@localhost ansible]# systemctl restart salt-master

[root@localhost ansible]# salt sp-2 cp.push /root/test.txt
sp-2:
    True
[root@localhost ansible]# ls /var/cache/salt/master/minions/sp-2/files/root/
test.txt


[root@localhost ansible]# salt sp-2 cp.push /root/test.txt upload_path=/test/file/file.txt
sp-2:
    True
[root@localhost ansible]# find / -name 'file.txt'
...
/var/cache/salt/master/minions/sp-2/files/test/file/file.txt
[root@localhost ansible]# ls /var/cache/salt/master/minions/sp-2/files/test/file/
file.txt


state.sls => 类似ansible的剧本

查看某个模块的剧本示例帮助

#查看帮助文档
salt sp-1 sys.list_state_functions pkg
salt sp-1 sys.state_doc pkg.installed

salt sp-1 sys.list_state_functions service
salt sp-1 sys.state_doc service.dead

编辑nginx下载启动服务剧本

mkdir /srv/salt/state/
cd  /srv/salt/state/
mkdir nginx
cd nginx
vim nginx_install.sls
#剧本内容
nginx-install:
  pkg.installed:
    - name: nginx

nginx-service:
  service.running:
    - name: nginx
    - enable: True
    - require:
      - pkg: nginx-install

#执行nginx_install.sls剧本
salt sp-1 state.sls state.nginx.nginx_install
#检测是否成功
salt sp-1 cmd.run 'ps -ef | grep nginx'
salt sp-1 cmd.run 'service nginx status'

关闭nginx服务

vim nginx_stop.sls
#关闭nginx
stop_nginx_service:
  service.dead:
    - name: nginx

[root@localhost nginx]# salt sp-1 state.sls state.nginx.nginx_stop
sp-1:
----------
          ID: stop_nginx_service
    Function: service.dead
        Name: nginx
      Result: True
     Comment: Service nginx was killed
     Started: 08:20:02.938253
    Duration: 358.058 ms
     Changes:
              ----------
              nginx:
                  False

Summary for sp-1
------------
Succeeded: 1 (changed=1)
Failed:    0
------------
Total states run:     1
Total run time: 358.058 ms
[root@localhost nginx]# salt sp-1 cmd.run 'service nginx status'
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值