ansible_ub

ansible_ub

搭建一套ansible

  1. 纳管10.80.238.31-39
  2. 批量执行命令
  3. 批量分发文件

env
ubuntu20.04
ansible [core 2.12.10]

安装验证

apt install -y software-properties-common
add-apt-repository --yes --update ppa:ansible/ansible
apt install -y ansible
ansible --version

添加主机

tee <<EOF >/etc/ansible/hosts 
[k8s_pre]
10.80.238.[31:36]
[k8s_pre:vars]
ansible_ssh_user=root
ansible_ssh_pass=Password@1
ansible_ssh_port=22

[k8s_pre_nfs]
10.80.238.39
[k8s_pre_nfs:vars]
ansible_ssh_user=root
ansible_ssh_pass=Password@1
ansible_ssh_port=22

EOF

ansible-inventory --list -y
ansible k8s_pre --list-hosts

建议不设置明文密码,而是ssh免密通信
ssh-keygen -t rsa -b 2048 -N "" -f ~/.ssh/id_rsa
for i in {31..36}; do ssh-copy-id root@10.80.238.$i; done
for i in {31..36}; do sshpass -p 'Password@1' ssh-copy-id -o StrictHostKeyChecking=no -p 5008 root@10.80.238.$i; done

命令使用

ansible k8s_pre -m shell -a "uptime"
1. apt安装
ansible k8s_pre_nfs -m apt -a "name=nginx state=present update_cache=yes" --become
2. 服务重启
ansible k8s_pre_nfs -m service -a "name=nginx state=restarted" --become
3. 拷贝文件
ansible k8s_pre_nfs -m copy -a "src=igo.txt dest=/tmp/ mode=0644"
4. 追加文件内容
ansible k8s_pre_nfs -m blockinfile -a "path=/etc/hosts block='10.80.238.31  k8s-pre-31\n10.80.238.32  k8s-pre-32' marker='# ANSIBLE MANAGED BLOCK'" --become
5. 批量修改127主机名,避免普通用户的sudo报错
ansible all -b -m shell -a "sed -i 's/^127.0.1.1.*/127.0.1.1 '\$(hostname)'/' /etc/hosts"
ansible k8s_pre:k8s_pre_nfs -b -m shell -a "sed -i 's/^127.0.1.1.*/127.0.1.1 '\$(hostname)'/' /etc/hosts"

playbook样例

sys_init.yaml

---
- name: 初始化 31-39 服务器
  hosts: my_servers
  become: yes
  gather_facts: no

  tasks:
    - name: 更新 apt 缓存
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: 安装基础工具
      apt:
        name:
          - vim
          - curl
          - wget
          - htop
        state: present

    - name: 关闭防火墙 (ufw)
      service:
        name: ufw
        state: stopped
        enabled: no

igozhang 2021