Wie man den Standard-SSH-Benutzer für Ansible-Verbindungen einstellt

AnsibleAnsibleBeginner
Jetzt üben

💡 Dieser Artikel wurde von AI-Assistenten übersetzt. Um die englische Version anzuzeigen, können Sie hier klicken

Introduction

Ansible is a powerful automation tool that simplifies the management of remote servers. One crucial aspect of Ansible is the ability to establish secure SSH connections to these servers. In this tutorial, we will explore how to set the default SSH user for Ansible connections, ensuring a smooth and efficient workflow for your server management tasks.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL ansible(("Ansible")) -.-> ansible/InventoryManagementGroup(["Inventory Management"]) ansible(("Ansible")) -.-> ansible/PlaybookEssentialsGroup(["Playbook Essentials"]) ansible(("Ansible")) -.-> ansible/ModuleOperationsGroup(["Module Operations"]) ansible/ModuleOperationsGroup -.-> ansible/apt("Package Manager") ansible/ModuleOperationsGroup -.-> ansible/command("Execute Commands") ansible/ModuleOperationsGroup -.-> ansible/debug("Test Output") ansible/InventoryManagementGroup -.-> ansible/group_variables("Set Group Variables") ansible/InventoryManagementGroup -.-> ansible/host_variables("Set Host Variables") ansible/PlaybookEssentialsGroup -.-> ansible/playbook("Execute Playbook") subgraph Lab Skills ansible/apt -.-> lab-415242{{"Wie man den Standard-SSH-Benutzer für Ansible-Verbindungen einstellt"}} ansible/command -.-> lab-415242{{"Wie man den Standard-SSH-Benutzer für Ansible-Verbindungen einstellt"}} ansible/debug -.-> lab-415242{{"Wie man den Standard-SSH-Benutzer für Ansible-Verbindungen einstellt"}} ansible/group_variables -.-> lab-415242{{"Wie man den Standard-SSH-Benutzer für Ansible-Verbindungen einstellt"}} ansible/host_variables -.-> lab-415242{{"Wie man den Standard-SSH-Benutzer für Ansible-Verbindungen einstellt"}} ansible/playbook -.-> lab-415242{{"Wie man den Standard-SSH-Benutzer für Ansible-Verbindungen einstellt"}} end

Installing and Setting Up Ansible

Before configuring the SSH user for Ansible, we need to ensure Ansible is properly installed and set up on our system.

Installing Ansible

Let's start by installing Ansible. Open a terminal and run the following commands:

sudo apt update
sudo apt install -y ansible

Once the installation is complete, verify that Ansible is installed correctly by checking its version:

ansible --version

You should see output similar to the following:

ansible [core 2.12.x]
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/labex/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  ansible collection location = /home/labex/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.10.x (main, Ubuntu, x86_64)
  jinja version = 3.0.3
  libyaml = True

Creating an Ansible Working Directory

Next, let's create a directory structure for our Ansible project. This will help us keep our files organized:

mkdir -p ~/project/ansible/inventory
cd ~/project/ansible

Creating a Basic Inventory File

Ansible uses inventory files to define the hosts it manages. Let's create a simple inventory file:

echo "[webservers]
localhost ansible_connection=local" > ~/project/ansible/inventory/hosts

This inventory file defines a group called webservers with only one host, localhost, and tells Ansible to use a local connection rather than SSH for this host.

Now, let's verify our inventory:

ansible -i inventory/hosts --list-hosts all

You should see output like:

  hosts (1):
    localhost

This shows that Ansible recognizes our inventory and the hosts defined within it.

Understanding Ansible SSH Connections and Configuration

Ansible primarily uses SSH to connect to remote hosts and execute commands. Let's explore how Ansible establishes SSH connections and how we can configure the default SSH user.

How Ansible Uses SSH

By default, Ansible attempts to use your current system user to establish SSH connections. This means if you're logged in as the labex user and run an Ansible command, Ansible will try to connect to remote hosts as the labex user.

This default behavior might not always be what you want. For instance:

  • The remote server might require a different user for access
  • You might want to use a dedicated user for automation tasks
  • Different servers might require different users

Ansible Configuration Hierarchy

Ansible uses a hierarchy of configuration sources to determine which SSH user to use:

  1. Command line options (highest priority)
  2. Task-specific options in playbooks
  3. Host and group variables in the inventory
  4. Ansible configuration file
  5. Default values (lowest priority)

Let's create a basic Ansible configuration file to understand this better:

cat > ~/project/ansible/ansible.cfg << 'EOF'
[defaults]
inventory = ./inventory/hosts
host_key_checking = False
EOF

This configuration file tells Ansible to:

  • Use our inventory file by default
  • Disable host key checking (useful for testing in lab environments)

Let's review the file we just created:

cat ~/project/ansible/ansible.cfg

You should see the content we just added to the file.

Testing a Basic Ansible Command

Now let's run a basic Ansible command to see the current user:

cd ~/project/ansible
ansible localhost -m command -a "whoami"

The output should show:

localhost | CHANGED | rc=0 >>
labex

This confirms that Ansible is executing commands as the current user (labex).

Setting the Default SSH User for Ansible

Now that we understand how Ansible uses SSH, let's explore different ways to set the default SSH user for our connections.

Method 1: Using the Ansible Configuration File

The simplest way to set a global default SSH user is through the Ansible configuration file. Let's modify our ansible.cfg file:

cat > ~/project/ansible/ansible.cfg << 'EOF'
[defaults]
inventory = ./inventory/hosts
host_key_checking = False
remote_user = ansible_user
EOF

In this configuration, we added the remote_user parameter, which tells Ansible to use ansible_user as the default SSH user for all connections.

Method 2: Setting the User in the Inventory File

Another approach is to define the SSH user in the inventory file. This method allows you to set different users for different hosts or groups.

Let's modify our inventory file:

cat > ~/project/ansible/inventory/hosts << 'EOF'
[webservers]
localhost ansible_connection=local

[dbservers]
db.example.com ansible_user=db_admin

[all:vars]
ansible_user=default_user
EOF

In this example:

  • We've added a new group called dbservers with a host db.example.com and specified that Ansible should use the db_admin user when connecting to this host.
  • We've also added a group variable ansible_user=default_user that applies to all hosts unless overridden.

Method 3: Using Command Line Options

You can also specify the SSH user directly in the command line when running Ansible commands:

ansible localhost -m command -a "whoami" -u specific_user

The -u option tells Ansible to use specific_user for this specific command, overriding any user defined in configuration files or inventory.

Method 4: Setting the User in Playbooks

When using Ansible playbooks, you can specify the SSH user at the play level:

Let's create a simple playbook to demonstrate this:

cat > ~/project/ansible/user_demo.yml << 'EOF'
---
- name: Demonstrate user configuration
  hosts: localhost
  remote_user: playbook_user
  
  tasks:
    - name: Show current user
      command: whoami
      register: current_user
      
    - name: Display current user
      debug:
        msg: "Current user is {{ current_user.stdout }}"
EOF

In this playbook, the remote_user parameter sets the SSH user to playbook_user for all tasks in this play.

User Precedence in Ansible

Understanding the precedence of these different methods is important:

  1. Command line options (-u flag) have the highest priority
  2. Task-level settings in playbooks
  3. Play-level settings in playbooks
  4. Host variables in inventory
  5. Group variables in inventory
  6. Configuration file settings (remote_user in ansible.cfg)
  7. Default system user (lowest priority)

This means that more specific user settings override more general ones.

Testing and Verifying SSH User Configuration

Now that we have configured the default SSH user in different ways, let's test and verify our configuration.

Testing the Configuration File Setting

First, let's run a simple Ansible command to see if our configuration file settings are applied:

cd ~/project/ansible
ansible localhost -m command -a "whoami"

Since we're connecting to localhost with ansible_connection=local, Ansible will still run commands as the current user regardless of the remote_user setting. However, if this were a remote connection, Ansible would attempt to use the ansible_user user we specified in the configuration.

Using ansible-inventory to Check User Settings

Ansible provides a command called ansible-inventory that allows us to see how Ansible interprets our inventory, including the SSH user settings:

ansible-inventory --list

This command outputs a JSON representation of the inventory, showing all the variables associated with each host, including the SSH user settings.

Testing User Settings with a Playbook

Let's run the playbook we created in the previous step:

ansible-playbook user_demo.yml

The output will show something like:

PLAY [Demonstrate user configuration] ******************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [Show current user] *******************************************************
changed: [localhost]

TASK [Display current user] ****************************************************
ok: [localhost] => {
    "msg": "Current user is labex"
}

PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

The output shows that the command is still executed as the labex user, which is expected because we're connecting to localhost with ansible_connection=local.

Creating a Real SSH User Configuration Example

Let's create a more realistic example that demonstrates how to set up SSH user configuration for remote hosts. We'll create a new playbook:

cat > ~/project/ansible/remote_user_example.yml << 'EOF'
---
- name: Example of remote user configuration
  hosts: all
  remote_user: admin_user
  
  tasks:
    - name: This task uses the play-level user (admin_user)
      debug:
        msg: "This would run as admin_user"
      
    - name: This task uses a specific user
      debug:
        msg: "This would run as operator_user"
      remote_user: operator_user
      
    - name: This task uses become to elevate privileges
      debug:
        msg: "This would run as the root user"
      become: true
      become_user: root
EOF

In this playbook:

  • We set remote_user: admin_user at the play level, which applies to all tasks by default
  • The second task overrides this with remote_user: operator_user
  • The third task uses become: true to elevate privileges to the root user

This example shows the different levels at which you can configure the SSH user in Ansible.

Advanced SSH User Configuration and Troubleshooting

Now that we've covered the basics of setting the default SSH user for Ansible, let's explore some advanced techniques and troubleshooting steps.

Using SSH Keys with Ansible

When connecting to remote hosts, it's a best practice to use SSH key authentication instead of passwords. Let's see how to configure SSH key authentication in Ansible:

cat > ~/project/ansible/ssh_key_example.yml << 'EOF'
---
- name: Example using SSH key authentication
  hosts: all
  remote_user: secure_user
  vars:
    ansible_ssh_private_key_file: ~/.ssh/id_rsa
  
  tasks:
    - name: Show SSH connection details
      debug:
        msg: "Connecting as {{ ansible_user }} using key {{ ansible_ssh_private_key_file }}"
EOF

In this example:

  • We set remote_user: secure_user as the default SSH user
  • We specify the SSH private key file to use with ansible_ssh_private_key_file

Setting Different Users for Different Environments

In real-world scenarios, you might want to use different SSH users for different environments (development, staging, production). Let's see how to achieve this:

mkdir -p ~/project/ansible/group_vars

Now, let's create group variable files for different environments:

cat > ~/project/ansible/group_vars/development << 'EOF'
---
ansible_user: dev_user
EOF

cat > ~/project/ansible/group_vars/production << 'EOF'
---
ansible_user: prod_user
ansible_ssh_private_key_file: ~/.ssh/prod_key
EOF

Update the inventory file to include these environment groups:

cat > ~/project/ansible/inventory/hosts << 'EOF'
[webservers]
localhost ansible_connection=local

[development]
dev.example.com

[production]
prod1.example.com
prod2.example.com

[all:vars]
ansible_user=default_user
EOF

With this configuration:

  • Hosts in the development group will use the dev_user SSH user
  • Hosts in the production group will use the prod_user SSH user and a specific SSH key
  • All other hosts will use the default_user SSH user

Troubleshooting SSH User Configuration

If you encounter issues with SSH user configuration in Ansible, here are some troubleshooting steps:

1. Check Ansible's interpreted inventory

To see how Ansible interprets your inventory, including all variable values:

ansible-inventory --list

2. Run Ansible with verbosity

Running Ansible with increased verbosity can help identify connection issues:

ansible localhost -m ping -vvv

The -vvv flag increases the verbosity level, showing detailed information about the SSH connection process.

3. Test SSH connection manually

You can test the SSH connection manually to verify that the user and key are working:

ssh -i ~/.ssh/id_rsa username@hostname

4. Check for SSH connection errors

Common SSH connection errors include:

  • Permission denied (publickey): This indicates an issue with the SSH key authentication
  • Host key verification failed: This occurs when the host key has changed
  • Connection refused: This indicates that the SSH service is not running or is blocked by a firewall

5. Create an Ansible configuration test playbook

Let's create a simple playbook to test our SSH user configuration:

cat > ~/project/ansible/test_ssh_config.yml << 'EOF'
---
- name: Test SSH user configuration
  hosts: all
  gather_facts: no
  
  tasks:
    - name: Display connection information
      debug:
        msg: |
          Connected to: {{ inventory_hostname }}
          User: {{ ansible_user | default('not set') }}
          SSH Key: {{ ansible_ssh_private_key_file | default('not set') }}
EOF

Run this playbook to see the connection information for each host:

ansible-playbook -i inventory/hosts test_ssh_config.yml

This playbook will show you the SSH user and key that Ansible is using for each host, which can help identify configuration issues.

Summary

In this lab, you have learned how to configure the default SSH user for Ansible connections using various methods. You now understand how to:

  1. Install and set up Ansible with a basic configuration
  2. Configure the default SSH user through the Ansible configuration file
  3. Set SSH users at different levels: inventory, playbook, and command line
  4. Verify and test your SSH user configuration
  5. Troubleshoot common SSH connection issues

These skills will enable you to manage your infrastructure more effectively with Ansible, ensuring secure and reliable connections to your remote servers. By properly configuring the SSH user for your Ansible connections, you can implement consistent automation workflows across different environments while maintaining appropriate security practices.