How to create a list of file names in a local directory?

I have a group of .keys files in the / files folder. I want to create users on remote hosts that match these key files.

Say I have alice.keys, bob.keys and john.keys in / files. I want the script to create alice, bob and john users if they do not exist, and update / add SSH keys from the corresponding .keys file for each user.

I know that I can use the module loopto scroll through files, but I don’t know how to create a list that contains only file names, so I can use it later.

My role structure is as follows:

sshrole
β”œβ”€β”€ defaults
β”‚   └── main.yml
β”œβ”€β”€ files
β”‚   β”œβ”€β”€ alice.keys
β”‚   β”œβ”€β”€ bob.keys
β”‚   └── john.keys
β”œβ”€β”€ handlers
β”‚   └── main.yml
β”œβ”€β”€ README.md
β”œβ”€β”€ tasks
β”‚   β”œβ”€β”€ main.yml
β”‚   β”œβ”€β”€ setup.yml
β”‚   β”œβ”€β”€ update.yml
β”‚   β”œβ”€β”€ useradd.yml
β”‚   └── userdel.yml
β”œβ”€β”€ templates
β”‚   └── ssh_config.j2
└── vars
    └── main.yml

In short, I want to have a variable ssh_userscontaining values {'alice', 'bob', 'john'}.

UPDATE: , ​​, :

- name: Extract user-names.
  shell: echo {{item}} | sed 's/.*\/\(.*\)\.keys/\1/'
  register: sed_commands
  with_fileglob: ../files/*.keys

{{sed_commands.results}} .

+4
1

with_fileglob, :

- hosts: target
  tasks:

    - command: cat {{item}}
      register: ssh_keys
      with_fileglob: files/*.keys
      delegate_to: localhost

, ssh_keys, results, , item - , stdout . , :

"ssh_keys": {
    "changed": true, 
    "msg": "All items completed", 
    "results": [
        {
            "item": "/home/lars/tmp/filetetst/files/john.keys", 
            "stdout": "ssh-rsa ...",
        }, 
        {
            "item": "/home/lars/tmp/filetetst/files/alice.keys", 
            "stdout": "ssh-rsa ...",
        }, 
        {
            "item": "/home/lars/tmp/filetetst/files/bob.keys", 
            "stdout": "ssh-rsa ...",
        }, 
    ]
}

with_items, .

- hosts: target
  tasks:

    - command: cat {{item}}
      register: ssh_keys
      with_fileglob: files/*
      delegate_to: localhost

- hosts: target
  tasks:

    - user:
        # username is the last path component of the
        # filename (item.item.split('/')[-1]), and then 
        # we need to remove .keys ([:-5]).
        name: "{{item.item.split('/')[-1][:-5]}}"
      with_items: "{{ssh_keys.results}}"

    - authorized_key:
        user: "{{item.item.split('/')[-1][:-5]}}"
        key: "{{item.stdout}}"
        manage_dir: yes
      with_items: "{{ssh_keys.results}}"
+7

Source: https://habr.com/ru/post/1613693/


All Articles