Array attribute in chef creating Database Mysql

#1

Hi Experts,

Create DB define attribute.

default['cms_mysql']['db'] = 'testy7'
After that iam calling in the recipe and creating the database
mysql -uroot -p'#{pw}' -Be\ "CREATE DATABASE #{node['cms_mysql']['db']}"
Which is working fine, Now i would like to have multiple attributes so that my recipe can loop over an array/hash of database attributes.
Can you pls give a direction on this how to go about it.Thanks

0 Likes

#2

Hey @sandeepiii!

Take a look at this comment regarding doing a similar thing with user creation using a data bag: Using databag in recipe

In short, you'll want to use each_pair against a hash of databases + passwords.

0 Likes

#3

I have found the solution of the above might be helpful for others.
Below code needs to be written in your recipe

Create DB

node['c_mysql']['db_name'].each do |db|
execute "create-db_#{db}" do
command "mysql -uroot -p'#{pw}' -e 'CREATE DATABASE #{db}';"
not_if "mysql -u root -p'#{pw}' -Be\ 'SHOW DATABASES' | grep #{db};"
end
end

the attribute must be declared in your \attribute\default.rb file
['c_mysql']['db_name'] = ['test1','test2','test3']

0 Likes

#4

Hey @sandeepiii!

Great work! One other suggestion I might make here is instead of running the create database via an execute block, look at performing the same operation with the mysql cookbook. You can still pass an array of databases and users to be created, but it's done in a much more manageable manner that will be able to be debugged in the future should an issue arise.

0 Likes