2015-05-04 02:47:26 +00:00
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
2014-02-11 17:03:11 +00:00
#
# 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/>.
2015-05-04 02:47:26 +00:00
# Make coding more python3-ish
from __future__ import ( absolute_import , division , print_function )
__metaclass__ = type
2014-11-18 00:36:49 +00:00
2015-05-04 02:47:26 +00:00
import os
import subprocess
2014-11-18 00:36:49 +00:00
2014-02-11 17:03:11 +00:00
from ansible import constants as C
2015-05-04 02:47:26 +00:00
from ansible . errors import AnsibleError
from ansible . utils . path import is_executable
2014-02-11 17:03:11 +00:00
2015-05-04 02:47:26 +00:00
def read_vault_file ( vault_password_file ) :
2014-03-10 21:15:44 +00:00
"""
2015-05-04 02:47:26 +00:00
Read a vault password from a file or if executable , execute the script and
retrieve password from STDOUT
2014-03-10 21:15:44 +00:00
"""
2015-05-04 02:47:26 +00:00
this_path = os . path . realpath ( os . path . expanduser ( vault_password_file ) )
if not os . path . exists ( this_path ) :
raise AnsibleError ( " The vault password file %s was not found " % this_path )
2014-03-10 21:15:44 +00:00
2015-05-04 02:47:26 +00:00
if is_executable ( this_path ) :
try :
# STDERR not captured to make it easier for users to prompt for input in their scripts
p = subprocess . Popen ( this_path , stdout = subprocess . PIPE )
except OSError as e :
raise AnsibleError ( " Problem running vault password script %s ( %s ). If this is not a script, remove the executable bit from the file. " % ( ' ' . join ( this_path ) , e ) )
stdout , stderr = p . communicate ( )
vault_pass = stdout . strip ( ' \r \n ' )
else :
try :
f = open ( this_path , " rb " )
vault_pass = f . read ( ) . strip ( )
f . close ( )
except ( OSError , IOError ) as e :
raise AnsibleError ( " Could not read vault password file %s : %s " % ( this_path , e ) )
2014-03-10 21:15:44 +00:00
2015-05-04 02:47:26 +00:00
return vault_pass
2014-02-24 18:09:36 +00:00