首页 文章

如何在第一次通过时以root身份运行Ansible?

提问于
浏览
1

这是我通过Ansible尝试完成的一步一步:

  • SSH作为root用户

  • 安装python(不存在于ubuntu中)和其他基本包 .

  • 创建新的 deploy 用户并配置 /etc/ssh/sshd_config ,使 PasswordAuhentication noPermitRootLogin no .

  • 重启ssh服务 .

后来我正在用新的任务,角色等更新我的剧本 . 所以我想重新对同一台服务器(已经阻止 root 访问)运行该剧本,这次只是作为新创建的用户访问 .

由于Ansible正试图以root用户身份访问,因此我预计会返回 Permission denied 访问权限 .

Question

  • 如何以root身份首先执行此操作,然后在下一个playbook运行时跳过根任务(本例中为 pre_tasks )?

一种选择是将它分成两个独立的剧本:一个用于配置,一个用于其余的 .

# playbook.yml
---
- name: Prepare server
  hosts: webserver
  gather_facts: False
  pre_tasks:
    - name: Install python for Ansible
      remote_user: root
      raw: type /usr/bin/python || (apt -y update && apt install -y python)
    - name: Create user
      remote_user: root
      include_role:
        name: deploy-user

  roles:
    # Future roles here
#roles/deploy-user/tasks/main.yml
---
- group:
    name: deploy
    state: present

- name: Create Deploy user
  user: 
    name={{ deploy_user }} 
    comment="Deploy User" 
    groups="sudo,deploy" 
    password="{{ deploy_password | password_hash('sha512') }}" 
    shell=/bin/bash 
    update_password=on_create


- name: Set authorized key took from files
  authorized_key:
    user: "{{ deploy_user }}"
    state: present
    key: "{{ lookup('file', item) }}"
  with_items:
    - '{{ ssh_authorized_keys }}'

- name: Disallow password authentication
  lineinfile:
    dest: /etc/ssh/sshd_config
    regexp: "^PasswordAuthentication"
    line: "PasswordAuthentication no"
    state: present

- name: Disallow root SSH access
  lineinfile:
    dest: /etc/ssh/sshd_config
    regexp: "^PermitRootLogin"
    line: "PermitRootLogin no"
    state: present

- name: restart-sshd
  remote_user: root
  service: name=ssh state=restarted

1 回答

  • 3

    创建定义同一主机组的两个清单文件:

    • 在第一个( bootstrap )中定义 ansible_user=root

    • 在第二个( inventory )中定义 ansible_user=regular_user_with_sudo_permissions .

    将第二个( inventory )定义为 ansible.cfg 中的默认库存文件 .

    每当需要引导新机器时,使用 -i bootstrap 选项运行 . 在其他情况下省略该选项 .

相关问题