Created
April 13, 2026 21:25
-
-
Save StyXman/0003d9f903edb0dc12a3ac561a37c8df to your computer and use it in GitHub Desktop.
Boostrapping Ansible with a sudoer user
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| - 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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