mirror of https://github.com/ansible/ansible.git
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
225 lines
6.9 KiB
Plaintext
225 lines
6.9 KiB
Plaintext
12 years ago
|
#!/usr/bin/python
|
||
12 years ago
|
# -*- coding: utf-8 -*-
|
||
|
|
||
13 years ago
|
"""
|
||
|
Ansible module to add authorized_keys for ssh logins.
|
||
13 years ago
|
(c) 2012, Brad Olson <brado@movedbylight.com>
|
||
|
|
||
|
This file is part of Ansible
|
||
|
|
||
|
Ansible is free software: you can redistribute it and/or modify
|
||
|
it under the terms of the GNU General Public License as published by
|
||
|
the Free Software Foundation, either version 3 of the License, or
|
||
|
(at your option) any later version.
|
||
|
|
||
|
Ansible is distributed in the hope that it will be useful,
|
||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
|
GNU General Public License for more details.
|
||
|
|
||
|
You should have received a copy of the GNU General Public License
|
||
|
along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||
|
"""
|
||
|
|
||
12 years ago
|
DOCUMENTATION = '''
|
||
|
---
|
||
|
module: authorized_key
|
||
12 years ago
|
short_description: Adds or removes an SSH authorized key
|
||
12 years ago
|
description:
|
||
12 years ago
|
- Adds or removes an SSH authorized key for a user from a remote host.
|
||
12 years ago
|
version_added: "0.5"
|
||
|
options:
|
||
|
user:
|
||
|
description:
|
||
|
- Name of the user who should have access to the remote host
|
||
|
required: true
|
||
|
default: null
|
||
|
aliases: []
|
||
|
key:
|
||
|
description:
|
||
|
- the SSH public key, as a string
|
||
|
required: true
|
||
|
default: null
|
||
12 years ago
|
path:
|
||
|
description:
|
||
|
- Alternate path to the authorized_keys file
|
||
|
required: false
|
||
12 years ago
|
default: "(homedir)+/.ssh/authorized_keys"
|
||
12 years ago
|
version_added: "1.2"
|
||
12 years ago
|
manage_dir:
|
||
|
description:
|
||
12 years ago
|
- Whether this module should manage the directory of the authorized_keys file
|
||
12 years ago
|
required: false
|
||
|
choices: [ "yes", "no" ]
|
||
|
default: "yes"
|
||
12 years ago
|
version_added: "1.2"
|
||
12 years ago
|
state:
|
||
|
description:
|
||
|
- whether the given key should or should not be in the file
|
||
|
required: false
|
||
|
choices: [ "present", "absent" ]
|
||
|
default: "present"
|
||
12 years ago
|
description:
|
||
|
- "adds or removes authorized keys for particular user accounts"
|
||
12 years ago
|
author: Brad Olson
|
||
|
'''
|
||
|
|
||
12 years ago
|
EXAMPLES = '''
|
||
|
# Example using key data from a local file on the management machine
|
||
12 years ago
|
authorized_key: user=charlie key="{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"
|
||
12 years ago
|
|
||
|
# Using alternate directory locations:
|
||
12 years ago
|
authorized_key: user=charlie key="{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}" sshdir='/etc/ssh/authorized_keys/charlie' manage_dir=no
|
||
12 years ago
|
'''
|
||
|
|
||
13 years ago
|
# Makes sure the public key line is present or absent in the user's .ssh/authorized_keys.
|
||
|
#
|
||
|
# Arguments
|
||
|
# =========
|
||
|
# user = username
|
||
|
# key = line to add to authorized_keys for user
|
||
12 years ago
|
# path = path to the user's authorized_keys file (default: ~/.ssh/authorized_keys)
|
||
|
# manage_dir = whether to create, and control ownership of the directory (default: true)
|
||
13 years ago
|
# state = absent|present (default: present)
|
||
|
#
|
||
|
# see example in examples/playbooks
|
||
|
|
||
|
import sys
|
||
|
import os
|
||
|
import pwd
|
||
|
import os.path
|
||
12 years ago
|
import tempfile
|
||
|
import shutil
|
||
13 years ago
|
|
||
12 years ago
|
def keyfile(module, user, write=False, path=None, manage_dir=True):
|
||
13 years ago
|
"""
|
||
12 years ago
|
Calculate name of authorized keys file, optionally creating the
|
||
13 years ago
|
directories and file, properly setting permissions.
|
||
|
|
||
|
:param str user: name of user in passwd file
|
||
13 years ago
|
:param bool write: if True, write changes to authorized_keys file (creating directories if needed)
|
||
12 years ago
|
:param str path: if not None, use provided path rather than default of '~user/.ssh/authorized_keys'
|
||
|
:param bool manage_dir: if True, create and set ownership of the parent dir of the authorized_keys file
|
||
13 years ago
|
:return: full path string to authorized_keys for user
|
||
|
"""
|
||
|
|
||
12 years ago
|
try:
|
||
|
user_entry = pwd.getpwnam(user)
|
||
|
except KeyError, e:
|
||
|
module.fail_json(msg="Failed to lookup user %s: %s" % (user, str(e)))
|
||
12 years ago
|
if path is None:
|
||
|
homedir = user_entry.pw_dir
|
||
|
sshdir = os.path.join(homedir, ".ssh")
|
||
|
keysfile = os.path.join(sshdir, "authorized_keys")
|
||
|
else:
|
||
|
sshdir = os.path.dirname(path)
|
||
|
keysfile = path
|
||
13 years ago
|
|
||
12 years ago
|
if not write:
|
||
13 years ago
|
return keysfile
|
||
|
|
||
13 years ago
|
uid = user_entry.pw_uid
|
||
|
gid = user_entry.pw_gid
|
||
13 years ago
|
|
||
12 years ago
|
if manage_dir in BOOLEANS_TRUE:
|
||
|
if not os.path.exists(sshdir):
|
||
|
os.mkdir(sshdir, 0700)
|
||
|
if module.selinux_enabled():
|
||
|
module.set_default_selinux_context(sshdir, False)
|
||
|
os.chown(sshdir, uid, gid)
|
||
|
os.chmod(sshdir, 0700)
|
||
13 years ago
|
|
||
12 years ago
|
if not os.path.exists(keysfile):
|
||
|
basedir = os.path.dirname(keysfile)
|
||
|
if not os.path.exists(basedir):
|
||
|
os.makedirs(basedir)
|
||
13 years ago
|
try:
|
||
13 years ago
|
f = open(keysfile, "w") #touches file so we can set ownership and perms
|
||
13 years ago
|
finally:
|
||
|
f.close()
|
||
12 years ago
|
if module.selinux_enabled():
|
||
|
module.set_default_selinux_context(keysfile, False)
|
||
13 years ago
|
|
||
13 years ago
|
os.chown(keysfile, uid, gid)
|
||
|
os.chmod(keysfile, 0600)
|
||
|
return keysfile
|
||
|
|
||
13 years ago
|
def readkeys(filename):
|
||
|
|
||
12 years ago
|
if not os.path.isfile(filename):
|
||
13 years ago
|
return []
|
||
|
f = open(filename)
|
||
|
keys = [line.rstrip() for line in f.readlines()]
|
||
|
f.close()
|
||
13 years ago
|
return keys
|
||
|
|
||
12 years ago
|
def writekeys(module, filename, keys):
|
||
13 years ago
|
|
||
12 years ago
|
fd, tmp_path = tempfile.mkstemp('', 'tmp', os.path.dirname(filename))
|
||
12 years ago
|
f = open(tmp_path,"w")
|
||
|
try:
|
||
|
f.writelines( (key + "\n" for key in keys) )
|
||
|
except IOError, e:
|
||
|
module.fail_json(msg="Failed to write to file %s: %s" % (tmp_path, str(e)))
|
||
13 years ago
|
f.close()
|
||
12 years ago
|
module.atomic_move(tmp_path, filename)
|
||
13 years ago
|
|
||
|
def enforce_state(module, params):
|
||
|
"""
|
||
|
Add or remove key.
|
||
13 years ago
|
"""
|
||
|
|
||
12 years ago
|
user = params["user"]
|
||
|
key = params["key"]
|
||
|
path = params.get("path", None)
|
||
|
manage_dir = params.get("manage_dir", True)
|
||
|
state = params.get("state", "present")
|
||
13 years ago
|
|
||
12 years ago
|
key = key.split('\n')
|
||
12 years ago
|
|
||
13 years ago
|
# check current state -- just get the filename, don't create file
|
||
12 years ago
|
write = False
|
||
|
params["keyfile"] = keyfile(module, user, write, path, manage_dir)
|
||
13 years ago
|
keys = readkeys(params["keyfile"])
|
||
12 years ago
|
|
||
|
# Check our new keys, if any of them exist we'll continue.
|
||
12 years ago
|
for new_key in key:
|
||
12 years ago
|
present = new_key in keys
|
||
|
# handle idempotent state=present
|
||
|
if state=="present":
|
||
|
if present:
|
||
|
continue
|
||
|
keys.append(new_key)
|
||
12 years ago
|
write = True
|
||
|
writekeys(module, keyfile(module, user, write, path, manage_dir), keys)
|
||
12 years ago
|
params['changed'] = True
|
||
|
|
||
|
elif state=="absent":
|
||
|
if not present:
|
||
|
continue
|
||
|
keys.remove(new_key)
|
||
12 years ago
|
write = True
|
||
|
writekeys(module, keyfile(module, user, write, path, manage_dir), keys)
|
||
12 years ago
|
params['changed'] = True
|
||
|
|
||
13 years ago
|
return params
|
||
|
|
||
|
def main():
|
||
|
|
||
|
module = AnsibleModule(
|
||
|
argument_spec = dict(
|
||
12 years ago
|
user = dict(required=True, type='str'),
|
||
|
key = dict(required=True, type='str'),
|
||
|
path = dict(required=False, type='str'),
|
||
12 years ago
|
manage_dir = dict(required=False, type='bool'),
|
||
12 years ago
|
state = dict(default='present', choices=['absent','present'])
|
||
13 years ago
|
)
|
||
|
)
|
||
|
|
||
|
results = enforce_state(module, module.params)
|
||
|
module.exit_json(**results)
|
||
|
|
||
|
# this is magic, see lib/ansible/module_common.py
|
||
|
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
|
||
12 years ago
|
main()
|