Writing two variables in a file via chef file resource content - ruby

Is it possible to write two variables to a file generated by chef - without using a template erb file?
username = secret[:username]
password = secret[:password]
file "/home/secret_file.txt" do
content username password
owner 'user'
group 'user'
mode '0755'
end
Adding only one variable is working as expected but with two variables as shown above I get a error message "undefined method `username' for Chef::Resource::File"

Are you looking to add these variables in one line in the file? The content property takes a string type.
You could do use string interpolation to create a string and add the content to the file:
username = secret[:username]
password = secret[:password]
file "/home/secret_file.txt" do
content "#{username} #{password}"
owner 'user'
group 'user'
mode '0755'
end
or if you need to format it a certain way:
username = secret[:username]
password = secret[:password]
output = <<-CODE
The username is #{username}
The password is #{password}
CODE
file "/home/secret_file.txt" do
content output
owner 'user'
group 'user'
mode '0755'
end

Related

Puppet provider prefetch

I am writing a provider to generate self signed certificate using the certdog krestfield API.
I have implemented the create, destroy, exists? method and I can properly manage my certificate by making different call to the API.
I implemented puppet resource using the self.prefetch and self.instances methods. I can retrieve the properties of my resources to be aware of their current state.
My resource contain two sensitive types 'username' and 'password' who are required to make the API calls. I can't store those values on the filesystem and I want the 'puppet resource' command to ignore those types.
Currently when I run 'puppet apply' for the manifest:
certdog_certificate { 'tstpuppet':
ensure => present,
server => 'apiserver',
username => 'apiserver_username',
password => 'apiserver_password',
}
It returns:
Notice: /Stage[main]/Main/Certdog_certificate[tstpuppet]/username: defined 'username' as 'apiserver_username'
Notice: /Stage[main]/Main/Certdog_certificate[tstpuppet]/password: defined 'password' as 'apiserver_password'
Is there a way to hide sensitive types for puppet resources ? How should I process ?
I had to properly define my resource attributes.
The configurable data not part of the persistant state should be parameters as describe in the puppet documentation.
The attributes username and password are now define with newparam instead of newproperty as below.
module Puppet
Type.newtype(:certdog_certificate) do
#doc = 'Manage certificate using certdog REST API'
ensurable do
desc 'Create or remove a certificate'
newvalue(:present) do
provider.create
end
newvalue(:absent) do
provider.destroy
end
defaultto :present
end
newparam(:cert_name, namevar: true) do
desc 'Name of the certificate request'
end
newparam(:username) do
desc 'Username for Certdog API server'
end
newparam(:password) do
desc 'Password for Certdog API server'
end
newproperty(:server) do
desc 'Certdog API server address'
end
end
#john-bollinger Thanks for your explanation, I was missing an important concept of the custom types.

Azure Key Vault Chef Cookbook

I am a noobie with coding but am learning. I was hoping someone can help look at this ruby code that I found online that helps to get a secret from an Azure Key vault. I will paste it below. I just need help clarifying what each block of code is referring to.
Not sure what the below code is referring to. I know they are attributes but how do they work?
node.default['azurespn']['client_id'] = azurespn[node.environment]['client_id']
node.default['azurespn']['tenant_id'] = azurespn[node.environment]['tenant_id']
node.default['azurespn']['client_secret'] = azurespn[node.environment]['client_secret']
Recipe:
# retrieve the secret stored in azure key vault using this chef recipe
include_recipe 'microsoft_azure'
azurespn = data_bag_item('azurespn', 'azurespnenv')
node.default['azurespn']['client_id'] = azurespn[node.environment]['client_id']
node.default['azurespn']['tenant_id'] = azurespn[node.environment]['tenant_id']
node.default['azurespn']['client_secret'] = azurespn[node.environment]['client_secret']
spn = {
'tenant_id' => "#{node['azurespn']['tenant_id']}",
'client_id' => "#{node['azurespn']['client_id']}",
'secret' => "#{node['azurespn']['client_secret']}"
}
secret = vault_secret("#{node['windowsnode']['vault_name']}", "#{node['windowsnode']
['secret']}", spn)
file 'c:/jenkins/secret' do
action :create
content "#{secret}"
rights :full_control, 'Administrators', :one_level_deep => true
end
Chef::Log.info("secret is '#{secret}' ")
Q. Not sure what the below code is referring to. I know they are attributes but how do they work?
As you understood, this block of code is setting some node attributes. The value of these attributes is being read from a data bag (in the line above), i.e. azurespn = data_bag_item('azurespn', 'azurespnenv')
Now azurespn variable contains the contents of the data bag item azurespnenv. For better understanding, try knife data bag show azurespn azurespnenv. I created a dummy data bag structure just to illustrate.
dev:
client_id: win10
client_secret: topsecret
tenant_id: testtenant
qa:
client_id: ubuntu
client_secret: changeme
tenant_id: footenant
id: azurespnenv
In this data bag, we have two environments - dev and qa.
Let's take 1 line for example:
node.default['azurespn']['client_id'] = azurespn[node.environment]['client_id']
So the azurespn[node.environment]['client_id'] will pick up the appropriate client_id based on the Chef environment of that node. Which translates to:
node.default['azurespn']['client_id'] = azurespn['dev']['client_id']
#=> 'win10'
node.default['azurespn']['client_id'] = azurespn['qa']['client_id']
#=> 'ubuntu'

How to check whether a file contains "." (dot) operator

I have a code which asks user to upload a file. The file may be audio or image or anything. I asks user to enter file name. If he Enter file name my code adds extension to it. It is working fine. But if user enters extension say audio.mp3 then it saves as audio.mp3.mp3. So I have to check if user entered name contains dot then it should not take extension.
I used pregmatch but it is not working.
My code
$splitOptions = explode(',',$request->input('mediaName'));
$fileExtension = pathinfo($file[$i]->getClientOriginalName(),PATHINFO_EXTENSION);
$checkExtension = explode('.',$request->input('mediaName'));
if(preg_match("/[.]/", $checkExtension)){
$mediaName = $splitOptions[$i];
}
else
{
$mediaName = $splitOptions[$i]."_$fileExtension";
}
Please use laravel helper
$value = str_contains('This is my name', 'my');
// true

How to get properties of Authentification Alias on WAS 7 using wsadmin

I created a script in Jython which extracts some properties of a Data Source from WAS 7. One of theese properties is the Authentification Alias. I know that the password is crypted, but project has a semididactical purpose so the focus is on retriving the username and password, not to hack something.
How can I extract the properties of the Authentification Alias, i mean the username and the password?
Thanks in advance!
I solved the problem. :) Let's start with the beginning.
You have to find security.xml (WAS_HOME/AppServer/profiles/Profile_Name/config/cells/Cell_Name/security.xml) file and search in it the Authentication Alias.
Keep the line that contains the Auth Alias in a variable called Line and then extract the username, password and description.
After that you have to decrypt your password with a XOR algorithm, and write the variables in a file as a list. Ex: AuthDataAlias = [\ ['AuthAlias', 'username', 'password', 'description'] ]
Code:
import sys, java, java.io, java.lang, base64, binascii
resFile="resources.res"
def search ( alias, file ):
f=open(file)
lines=f.readlines()
for line in lines:
poz = line.find('/'+alias)
if poz > 0:
Line = line
break
user = Line[Line.find('userId=')+8:Line.find('\" password')]
password = Line[Line.find('password=')+15:Line.find('\" description')]
password = decrypt(password)
description = Line[Line.find('description=')+13:Line.find('\"/>')]
write ( AuthAlias, user, password, description, resFile)
def write ( alias, user, password, desc, file ):
objItemFileOutputStream = java.io.FileOutputStream(file, 1) #apend la sfirsit fisier
objItemFileOutputStream.write('\n')
AuthList = "AuthDataAlias = [\\\n[\'"+alias+"\', \'"+user+"\', \'"+password+"\', \'"+desc+"\'] ]"
objItemFileOutputStream.write(AuthList)
def decrypt ( word ):
if not len(word) > 1: exit()
word = word.replace(':', '')
value1 = binascii.a2b_base64(word)
value2 = '_' * len(value1)
out = ''
for a, b in zip(value1, value2):
out = ''.join([out, chr(ord(a) ^ ord(b))])
return out
#MAIN
search ( AuthAlias, securityFile )
If anyone gets stuck with this issue feel free to post your questions and I will try to answer ASAP.

Create windows user with chef and add user to the local Administrators group

Chef documentation for the user resource: http://docs.getchef.com/resource_user.html
Doing this works:
user "TestUser" do
password "p#ssw0rd"
end
But when I add a gid it fails:
user "TestUser" do
password "p#ssw0rd"
gid "Administrators"
end
I've also tried passing .\Administrator, but get the same result:
[2014-08-08T14:00:11-07:00] FATAL: ArgumentError: user[TestUser] (test::users line 11) had an error: ArgumentError: The user does not belong to this group.
Is the purpose of gid not to specify group membership?
Eventually figured it out. The trick is to modify the group like so:
user "TestUser" do
password "p#ssw0rd"
end
group "Administrators" do
action :modify
members "TestUser"
append true
end

Resources