Skip to content

Instantly share code, notes, and snippets.

@StyXman
Created April 13, 2026 21:25
Show Gist options
  • Select an option

  • Save StyXman/0003d9f903edb0dc12a3ac561a37c8df to your computer and use it in GitHub Desktop.

Select an option

Save StyXman/0003d9f903edb0dc12a3ac561a37c8df to your computer and use it in GitHub Desktop.
Boostrapping Ansible with a sudoer user
#! /bin/bash
set -euo pipefail
if [ $# -lt 2 ]; then
echo "Usage: $0 USER HOST"
exit 1
fi
user=$1
host=$2
shift 2
cat << EOF > b-inv.yaml
all:
hosts:
${host}:
EOF
# TODO: properly handle the password
if ansible-playbook bootstrap.yaml --inventory inventory-common.yaml --user $user --ask-pass --ask-become-pass -vvv "$@"; then
rm b-inv.yaml
fi
- name: Boostrap a node for running ansible remotely
hosts: all
become: yes
become_method: sudo
vars:
user_name: ansible
tasks:
- name: Create ansible user
user:
name: "{{ user_name }}"
shell: /bin/bash
groups:
- sudo
state: present
- name: Add public key
authorized_key:
user: "{{ user_name }}"
key: "{{ lookup('file', 'ansible-key.pub') }}"
state: present
- name: Create sudoers.d directory
file:
path: /etc/sudoers.d
owner: root
group: root
mode: 0770
state: directory
- name: Enable sudoers.d
lineinfile:
path: /etc/sudoers
line: "#includedir /etc/sudoers.d"
owner: root
group: root
mode: 0440
state: present
create: yes
- name: sudo for ansible
template:
# TODO: better layout
src: sudoer.j2
dest: /etc/sudoers.d/ansible
owner: root
group: root
mode: 0440
validate: /usr/sbin/visudo --check --strict --file %s
# keep this file empty, as ansible is in the sudoers group and that should be enough
{{ user_name }} ALL=(ALL) NOPASSWD:ALL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment