Ansible创建用户添加sudoers

  • A+
所属分类:Linux技术

强制分发公钥

ssh-copy-id -f -i /etc/ansible/roles/id_rsa.pub root@127.0.0.1

安装ansible

yum install epel-release -y
yum install ansible

生成用户密文密码

生成密文密码
a=$(python -c 'import crypt,getpass;pw="Dh1Tsdf==";print(crypt.crypt(pw))')
echo $a
$6$GBkZEivSgIjtsDoN$sdsH8nT/Gd80Wss1kMgq9/Mh4YPgWsszLoQQ10lQqiyKBeAB.ZIWLMB4LXuupfm2rbVoTrKny8EvBx9ikB2KCHC/X84C/

关闭ansible主机key检测

vim /etc/ansible/ansible.cfg
host_key_checking = False

配置主机组

提前创建好ssh公钥和私钥

[root@yunwei-192 ansible]# cat hosts
[INT]
10.0.128.18:22 ansible_ssh_user=root ansible_ssh_key=/root/.ssh/id_rsa

配置要分发的公钥

[root@yunwei-192 ansible]# cat /etc/ansible/roles/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDB6GpMOrM0V7VMuMuOF/Qobn/vtIhK9RuX2ev0sYvpOwviftFjtrGCJcdwP1966QqrktgNHE9mTGT7v4CSZcf0JLD7zDL8OB1W81AoJzsrhWhIR51x4fEJtAOCBDA6x0JagtqqFaZvQWpJzuuAxUcaTJnca3ZA81n3pfJwZ6aO50KAPIwofjS2OCUxsPTuHJACPcVKXGrOfeasIB5942de5vD5+RVVFbj+LHMVHyruFQuUygOed7tMhOGEZIORalF0hLuH2qMsIlecVE5gqC6Gh1r+hVHDSRBqG1lNXjhjMyfugXa+Uh7FxbPnZ2GM6WvbaxL0hofRAMftyX9/Y0Md alauda@jumpserver

编写playbook

[root@yunwei-192 ansible]# cat /etc/ansible/add-user-key.yml
- hosts: INT
  vars:
    user: liuyalei
    password: "$6$GBkZEivSgIjt222sDoN$H8nT/Gd80W1kMgq9/Mh4YPgWzLoQQ10lQqiyKBeAB.ZIWLMB4LXuupfm2rbVoTrKny8EvBx9ikB2KCHC/X84C/"
  remote_user: root
  gather_facts: false
  tasks:
  - name: Add user {{ user }}
    user: name={{user}} password={{ password }}
  - name: Config /etc/sudoers
    lineinfile:
      dest: /etc/sudoers
      state: present
      regexp: '^{{ user }}'
      line: '{{ user }} ALL=(ALL) NOPASSWD: ALL'
  - name: Add authorized_keys
    authorized_key:
        user: '{{ user }}'
        key: "{{ lookup('file', '/etc/ansible/roles/authorized_keys') }}"  # 从本地authorized_keys文件读取公钥内容
        state: present
        exclusive: yes

检查playbook

ansible-playbook -C add-user-key.yml

最后检查远端服务器用户、sudoers,本地尝试免密登录、密码登录

YaLei

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: