pixel

ansible.posix.authorized_key – A Complete Guide

Share on Social Media

Unlock seamless SSH key management with ansible.posix.authorized_key. This complete guide covers everything you need to automate secure access like a pro. Don’t miss out—master this essential Ansible module today! #centlinux #ansible #linux



Introduction to ansible.posix.authorized_key


What is Ansible?

Ansible is an open-source automation tool used for configuration management, application deployment, and task automation. It enables you to manage infrastructure as code and simplifies the orchestration of complex IT workflows. Unlike other configuration management tools, Ansible is agentless, meaning it doesn’t require any software installation on the target machines. It uses SSH to communicate with the nodes, making it incredibly lightweight and easy to implement. Whether you’re automating server provisioning or managing cloud infrastructure, Ansible provides an intuitive, powerful way to streamline these processes.

Its YAML-based playbooks are human-readable and provide clarity, which makes it suitable for both developers and operations teams. One key area where Ansible excels is SSH key management, ensuring secure and password-less authentication to systems. And that’s where modules like authorized_key become essential.

ansible.posix.authorized_key - A Complete Guide
ansible.posix.authorized_key – A Complete Guide

The Purpose of the ansible.posix Collection

The ansible.posix collection is a curated set of Ansible modules specifically tailored for managing POSIX-compliant systems (like Linux and UNIX). These modules focus on standard system administration tasks that are common across different distributions and environments. From firewall rules to system settings, the ansible.posix collection makes it easy to manage Unix-like systems in a consistent and automated manner.

Among its many modules, authorized_key stands out as a powerful tool for managing SSH keys. This is crucial for environments that rely heavily on SSH for remote access and automation. The module allows for secure addition, modification, and removal of SSH keys from a user’s ~/.ssh/authorized_keys file. In essence, the ansible.posix collection brings control, security, and consistency to system configuration tasks.

Recommended Training: Dive Into Ansible – Beginner to Expert in Ansible – DevOps

1542886 f22c 27
show?id=oLRJ54lcVEg&bids=1597309

Role of the authorized_key Module in SSH Authentication

The authorized_key module in the ansible.posix collection is designed to manage SSH public keys for user accounts on remote systems. SSH keys are a safer and more scalable alternative to passwords for authenticating users, especially in environments with numerous servers. Instead of manually copying keys between systems, this module allows you to automate the whole process.

You can easily append or remove a key to/from a user’s authorized_keys file, define key types (like RSA or ED25519), restrict key usage with options, and even comment your key entries for better traceability. Whether you’re onboarding a new team member or rotating keys for security compliance, the authorized_key module makes the process efficient and error-free.

With increasing focus on infrastructure security, the ability to centrally manage SSH keys via Ansible is not just a luxury—it’s a necessity.


Installing and Setting Up ansible.posix.authorized_key


Prerequisites and Dependencies

Before diving into the actual installation and usage of the ansible.posix.authorized_key module, you’ll need a few things in place:

  • Ansible Installed: Make sure Ansible is already installed on your control machine. You can install it using dnf package manager:
    • dnf install -y ansible
  • Python Environment: Ansible runs on Python, so having Python 3.x installed is a must.
  • SSH Access to Target Machines: The managed nodes should be accessible over SSH and the user should have appropriate privileges (preferably with sudo access).
  • POSIX-compliant OS: This module is designed to work on Linux and UNIX-like systems.
YouTube player

Once these are set up, you’re ready to install the ansible.posix collection.


How to Install the ansible.posix Collection

Installing the ansible.posix collection is straightforward with the Ansible Galaxy command-line tool. Here’s how to do it:

ansible-galaxy collection install ansible.posix

This command downloads the collection and installs it into the default path (~/.ansible/collections/). Once installed, you can use any module from the collection by referencing it explicitly in your playbooks, like this:

- name: Add an authorized key
  ansible.posix.authorized_key:
    user: john
    key: "{{ lookup('file', '/home/john/.ssh/id_rsa.pub') }}"

You can also install specific versions of the collection if compatibility is a concern:

ansible-galaxy collection install ansible.posix:==1.5.2

Collections help ensure your playbooks use the intended version of a module and reduce surprises caused by upstream changes.


Verifying the Installation

After installation, it’s important to confirm that the ansible.posix collection was installed correctly. You can verify this in several ways:

  1. Check Installed Collections:
    • ansible-galaxy collection list
  2. Test with a Simple Playbook: Run a quick playbook using the authorized_key module and see if it executes without errors.
  3. Use ansible-doc: You can view the documentation for the module right from your terminal:
    • ansible-doc ansible.posix.authorized_key

This helps you double-check the parameters, examples, and supported functionality of the module. It’s always good practice to stay familiar with the latest documentation, especially when managing security-sensitive resources like SSH keys.


Anatomy of the authorized_key Module


Basic Syntax and Structure

The authorized_key module uses YAML syntax within an Ansible playbook. Its job is to manage a user’s authorized_keys file—either by adding, removing, or modifying SSH keys. Here’s a basic example:

- name: Ensure SSH key is present
  ansible.posix.authorized_key:
    user: deploy
    state: present
    key: "{{ lookup('file', '/home/deploy/.ssh/id_rsa.pub') }}"

This playbook task ensures that the specified SSH key is present for the deploy user. You can customize this further using additional parameters, which we’ll cover next.


Required Parameters

To make the authorized_key module work, a few parameters are essential:

  • user: Specifies the Linux user account to which the key will be added.
  • key: The actual public key string or the result of a lookup from a file.
  • state: Can be either present or absent, to manage the key’s presence.

Example:

user: devops
key: "{{ lookup('file', '/keys/devops_id_rsa.pub') }}"
state: present

These form the core of any authorized_key usage.


Optional Parameters and Their Use Cases

Here are some optional but incredibly useful parameters:

  • path: Manually specify the file path of the authorized_keys file.
  • key_options: Add options like no-agent-forwarding, from, command for restricting key usage.
  • manage_dir: Set to no to skip creating the .ssh directory.
  • exclusive: If yes, removes all other keys from the file that are not managed by the task.

Example:

key_options: 'no-port-forwarding,no-X11-forwarding'
exclusive: yes

Using these options helps fine-tune how access is managed, which is vital for high-security environments.


Supported Platforms and OS Compatibility

The ansible.posix.authorized_key module works on most POSIX-compliant systems, including:

  • Ubuntu
  • Debian
  • CentOS
  • RedHat
  • Fedora
  • FreeBSD
  • Alpine

However, it does not work on Windows or non-POSIX systems. Always test your playbook in a staging environment before rolling it out to production. OS-specific behaviors (like file permission enforcement) can lead to subtle bugs if not properly accounted for.


How authorized_key Works in Practice


Adding an SSH Key for a User

Let’s say you’ve hired a new developer and need to give them access to several Linux servers. Instead of manually logging into each machine and adding their public key, you can automate it like this:

- name: Add developer SSH key
  ansible.posix.authorized_key:
    user: devuser
    key: "{{ lookup('file', 'files/dev_id_ed25519.pub') }}"
    state: present

This playbook ensures the developer’s key is added to their ~/.ssh/authorized_keys file. Ansible even handles directory creation and permissions, saving you time and eliminating human error.

You can include this task in a broader user provisioning playbook, combining it with user creation, group assignments, and sudo configurations.


Removing SSH Keys Securely

When someone leaves the team or a key is compromised, you’ll want to revoke access immediately. Here’s how:

- name: Remove compromised key
  ansible.posix.authorized_key:
    user: devuser
    key: "{{ lookup('file', 'files/old_key.pub') }}"
    state: absent

This task deletes only the specific key, leaving other entries untouched. If you’re rotating all keys, consider using the exclusive: yes option to wipe and replace all keys at once.


Managing Multiple Keys

Sometimes users need access from multiple machines or devices. Instead of creating one massive playbook entry, you can loop through a list of keys:

- name: Add multiple keys
  ansible.posix.authorized_key:
    user: devuser
    key: "{{ item }}"
    state: present
  loop:
    - "{{ lookup('file', 'keys/laptop.pub') }}"
    - "{{ lookup('file', 'keys/workstation.pub') }}"

This method scales beautifully and keeps your playbooks clean and maintainable. It also simplifies rotating or updating individual keys as needed.


Advanced Usage Scenarios


Integrating with CI/CD Pipelines

In modern DevOps workflows, CI/CD (Continuous Integration/Continuous Deployment) pipelines are central to how code moves from development to production. Securely accessing infrastructure during these automated processes requires SSH keys—and managing them manually can quickly become a nightmare. That’s where ansible.posix.authorized_key really shines.

By integrating this module into your pipeline scripts, you can ensure that ephemeral or long-lived SSH keys are added to necessary systems only when needed. For example, your CI/CD tool like Jenkins, GitLab CI, or GitHub Actions can trigger a playbook to provision SSH access for deployment agents. Here’s a simplified playbook snippet you could run after a successful build:

- name: Grant deploy agent access to production servers
  hosts: production
  tasks:
    - name: Add CI/CD SSH key
      ansible.posix.authorized_key:
        user: deploy
        key: "{{ lookup('file', '/var/keys/ci_key.pub') }}"
        state: present

You can also configure the pipeline to remove the key afterward to reduce security exposure:

- name: Remove CI/CD SSH key
  ansible.posix.authorized_key:
    user: deploy
    key: "{{ lookup('file', '/var/keys/ci_key.pub') }}"
    state: absent

This approach ensures that deployment agents don’t have long-term access to sensitive systems and adheres to the principle of least privilege. It also creates a repeatable and auditable access control mechanism within your DevOps flow.


Dynamic User Creation with Key Authorization

When onboarding new team members, you might be tasked with not only creating their user accounts but also configuring their access keys. Combining user and authorized_key modules in one playbook makes this process seamless.

Here’s a practical example:

- name: Onboard a new developer
  hosts: all
  become: yes
  tasks:
    - name: Create user account
      user:
        name: alice
        shell: /bin/bash
        state: present
        create_home: yes

    - name: Add SSH key for alice
      ansible.posix.authorized_key:
        user: alice
        key: "{{ lookup('file', 'keys/alice_id_rsa.pub') }}"
        state: present

This method ensures that every new user gets set up with secure access, home directories, proper permissions, and all necessary configurations. It also allows you to audit and rollback access at any time through version-controlled playbooks.

Even better? You can scale this to multiple users using a loop or by importing variables from an external file like a YAML or CSV.


Using with Inventory Variables and Loops

Want to get really powerful with your Ansible automation? Combine ansible.posix.authorized_key with dynamic inventory variables and loops. This technique lets you manage SSH keys for multiple users across multiple hosts with minimal code.

Imagine you have an Ansible inventory that defines users and keys per host:

[webservers]
web1 ansible_host=192.168.1.10 users='[{"name": "john", "key": "john.pub"}, {"name": "jane", "key": "jane.pub"}]'

Then, in your playbook:

- name: Configure SSH access
  hosts: webservers
  become: yes
  tasks:
    - name: Add multiple users and keys
      authorized_key:
        user: "{{ item.name }}"
        key: "{{ lookup('file', 'keys/' + item.key) }}"
        state: present
      loop: "{{ users }}"

This makes it incredibly efficient to manage large-scale environments where different users need access to different servers. You avoid hardcoding users or keys and instead rely on structured data, making your automation both dynamic and scalable.

Moreover, by combining this with Ansible Vault, you can encrypt sensitive key data for maximum security while still maintaining automation.


Best Practices for Using ansible.posix.authorized_key


Enforce Strict Permissions

When managing SSH keys via Ansible, security should always be top of mind. One of the most common mistakes administrators make is overlooking file and directory permissions. SSH will refuse to use an authorized_keys file if it or its parent .ssh directory is too permissive. Thankfully, the authorized_key module helps maintain safe defaults, but it’s still good practice to double-check.

Here are recommended permission settings:

  • .ssh directory: 0700
  • authorized_keys file: 0600
  • User’s home directory: 0755

While the authorized_key module usually creates the .ssh directory with the right permissions if it doesn’t exist, you can explicitly enforce permissions using a task like this:

- name: Ensure correct SSH directory permissions
  file:
    path: /home/username/.ssh
    state: directory
    owner: username
    group: username
    mode: '0700'

This guarantees that your SSH configuration won’t break due to simple permission issues.


Version Control Your Keys

Tracking who has access and when keys were added or removed is essential in production environments. Storing your SSH keys and Ansible playbooks in version control (like Git) provides a full audit trail. It also ensures consistency across environments—what works in staging should work identically in production.

Here’s how you can structure your project:

ansible-ssh-keys/
├── group_vars/
│   └── all.yml
├── hosts.ini
├── keys/
│   ├── alice_id_rsa.pub
│   ├── bob_id_ed25519.pub
├── playbooks/
│   └── manage_keys.yml

By keeping everything structured and versioned, you can:

  • Roll back changes if a key breaks something
  • Track who added which key
  • Document when keys were rotated

Also, avoid hardcoding keys directly into playbooks. Use lookups or variables instead. It’s cleaner, safer, and more scalable.


Use with exclusive: yes Cautiously

The exclusive: yes parameter can be powerful—it ensures that only the keys defined in your playbook exist in the authorized_keys file. All others are removed. This is ideal for tightly controlled environments but can be dangerous if not used carefully.

Here’s a usage example:

- name: Enforce exact key set
  ansible.posix.authorized_key:
    user: john
    key: "{{ lookup('file', 'keys/john_id_rsa.pub') }}"
    state: present
    exclusive: yes

Caution: This will delete all other keys in that user’s authorized_keys file, even if they were added manually or by other tools.

Use this flag only when you are certain that Ansible is the only source of truth for that user’s keys. In shared environments, or when combining manual and automated processes, this might lead to accidental lockouts.


Common Errors and Troubleshooting


SSH Permission Denied

One of the most frustrating errors is the classic “Permission denied (publickey)” message after pushing a key with Ansible. This often comes down to permission issues or a misconfigured key.

To troubleshoot:

  1. Check that .ssh and authorized_keys have correct permissions.
  2. Verify that the key is valid and properly formatted (no line breaks or extra whitespace).
  3. Ensure the key is appended (not overwritten) unless intended.
  4. Validate the user has a login shell and home directory.

Run the following as a diagnostic:

ssh -v user@host

This gives verbose output and often points directly to the problem.


Invalid Key Format

The authorized_key module expects a valid public key in OpenSSH format. If the key is malformed, the playbook will fail silently or throw an error.

To ensure validity:

  • Use ssh-keygen -y to generate a public key from a private key
  • Avoid copying keys from PDFs, emails, or Word docs (they often break formatting)

Also, avoid using keys that are too old or deprecated (like DSA). Stick with modern types like ED25519 or RSA with adequate bit-length.


Duplicate Key Entries

Another common issue is adding the same key multiple times, especially when looping over lists or deploying across multiple servers.

Use unique=True (if you’re templating) or ensure deduplication in your source key list. This avoids redundant entries, which can bloat the authorized_keys file and cause confusion during audits.


Security Considerations


Key Rotation Policies

SSH key rotation is an essential part of security hygiene. Just like passwords, keys can be compromised. Ansible makes it easy to automate key rotation by:

  • Replacing old keys with new ones
  • Using the exclusive: yes flag to clean up obsolete keys
  • Running scheduled playbooks via cron or CI/CD

Example rotation task:

- name: Replace developer key
  ansible.posix.authorized_key:
    user: developer
    key: "{{ lookup('file', 'keys/new_dev_key.pub') }}"
    state: present
    exclusive: yes

Plan key rotation quarterly or semi-annually, and communicate with users ahead of time to avoid disruption.


Audit and Logging

SSH access should never be a black box. Use centralized logging to track SSH login attempts and Ansible runs.

You can also:

  • Keep logs of every Ansible execution with --check and --diff modes
  • Store logs in tools like ELK (Elasticsearch, Logstash, Kibana) or Splunk
  • Compare authorized_keys contents against your expected inventory

Having audit logs makes compliance with standards like HIPAA, PCI-DSS, or ISO 27001 much easier.


Conclusion


The ansible.posix.authorized_key module is an incredibly powerful and flexible way to manage SSH key-based authentication across your infrastructure. Whether you’re adding access for new users, integrating into your CI/CD pipelines, or hardening your server access controls, this module can do it all—reliably and repeatably.

It helps eliminate manual errors, scales with your infrastructure, and provides a centralized way to manage one of the most critical parts of your security strategy—SSH access. By following best practices and leveraging dynamic variables, loops, and version control, you can ensure your systems are secure, compliant, and easy to manage.

If you haven’t already adopted automated SSH key management, now is the time to do so. Ansible and the authorized_key module will make your life a lot easier—and your systems much safer.

Whether you need cloud optimization, server management, or automation, I provide comprehensive AWS and Linux services. Hire me on Fiverr to elevate your systems.


Frequently Asked Questions (FAQs)


1. Can I manage SSH keys for multiple users at once using authorized_key?
Yes! Use loops or inventory variables to iterate through a list of users and keys for efficient management.

2. What happens if I use exclusive: yes but forget to include all existing keys?
All unspecified keys will be deleted from the authorized_keys file. Use this flag with extreme caution.

3. Can I use the module with Windows targets?
No, the ansible.posix.authorized_key module is intended only for POSIX-compliant systems like Linux and UNIX.

4. How do I verify if a key was successfully added?
Check the user’s ~/.ssh/authorized_keys file on the target machine or run a test SSH login with the key.

5. Is it safe to store keys in playbooks?
It’s safer to store them in external files and use lookups, or use Ansible Vault to encrypt sensitive data.


Looking for something?

Leave a Reply