Chef delay attribute assignment via data bag The Next CEO of Stack OverflowChef attributes versus data bagsChef - Data Bag QueryWhere is my Chef data bag item?Chef library helper method is undefinedCombining attribute with literal in Chef data bag referencemanaging chef data bag easier and faster using knife commandStoring master token in Chef data bagAccess a Chef data bag from an attributes fileHow to read an encrypted data bag in a chef recipe?Create ipsets for iptables using Chef and data bags

Different harmonic changes implied by a simple descending scale

How did people program for Consoles with multiple CPUs?

How do we know the LHC results are robust?

Why has the US not been more assertive in confronting Russia in recent years?

Complex fractions

Do I need to enable Dev Hub in my PROD Org?

How fast would a person need to move to trick the eye?

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?

Rotate a column

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Giving the same color to different shapefiles in QGIS

Received an invoice from my ex-employer billing me for training; how to handle?

Sending manuscript to multiple publishers

What does "Its cash flow is deeply negative" mean?

How does the mv command work with external drives?

Unreliable Magic - Is it worth it?

Indicator light circuit

"and that skill is always a class skill for you" - does "always" have any meaning in Pathfinder?

Is it possible to search for a directory/file combination?

What's the best way to handle refactoring a big file?

Workaholic Formal/Informal

Won the lottery - how do I keep the money?

What connection does MS Office have to Netscape Navigator?

What happens if you roll doubles 3 times then land on "Go to jail?"



Chef delay attribute assignment via data bag



The Next CEO of Stack OverflowChef attributes versus data bagsChef - Data Bag QueryWhere is my Chef data bag item?Chef library helper method is undefinedCombining attribute with literal in Chef data bag referencemanaging chef data bag easier and faster using knife commandStoring master token in Chef data bagAccess a Chef data bag from an attributes fileHow to read an encrypted data bag in a chef recipe?Create ipsets for iptables using Chef and data bags










0















So i have a bit of a pickle.
I have an encrypted data bag to store LDAP passwords. In my node run list, one of my recipes installs the secret key onto my client machine.
In my problematic cookbook, i have a helper (in /libraries) that pulls data from AD (using LDAP). Problem is, i can't find a way to delay the assignment of my node attribute after initial compile phase.



Take this line of code as example :



node.override['yp_chefserver']['osAdminUser'] = node['yp_chefserver']['osAdminUser'] + get_sam("#data_bag_item('yp_chefserver', 'ldap', IO.read('/etc/chef/secret/yp_chefserver'))['ldap_password']")


Im trying to override an attribute by adding an array returned by my helper function "get_sam" which returns an array, but it needs to run AFTER the compile phase since the file "/etc/chef/secret/yp_chefserver" doesnt exist before the convergence of my runlist.



So my question : Is there a way to assign node attributes via data_bag_items during the execution phase?



Some things i've tried :



ruby_block 'attribution' do
only_if File.exist?('/etc/chef/secret/yp_chefserver')
block do
node.override['yp_chefserver']['osAdminUser'] = node['yp_chefserver']['osAdminUser'] + get_sam("#data_bag_item('yp_chefserver', 'ldap', IO.read('/etc/chef/secret/yp_chefserver'))['ldap_password']")
Chef::Log.warn("content of osAdminUser : #node['yp_chefserver']['osAdminUser']")
end
end


This doesn't work because the custom resource ruby_block doesn't have the method "data_bag_item". I've tried using lazy attributes in my "chef_server" custom resource, but same problem.



I also tried having the attribution done directly in my helper module, but since the helper module compiles before the exec phase, the file doesn't exist when it assigns the variable.



Here is the helper function in question should anyone wonder, it pulls the SamAccountName from LDAP to assign admin users to my chef server. :



module YpChefserver
module LDAP

require 'net-ldap'
@ldap

def get_ldap(ldap_password)
if @ldap.nil?
@ldap = Net::LDAP.new :host => "ADSERVER",
:port => 389,
:auth =>
:method => :simple,
:username => "CN=USERNAME,OU=East Service Accounts,OU=System Accounts,DC=ad,DC=ypg,DC=com",
:password => "#ldap_password"

end
@ldap
end

def get_ldap_users(ldap_password)
filter = Net::LDAP::Filter.eq("cn", "DevOps")
treebase = "dc=ad, dc=ypg, dc=com"
get_ldap(ldap_password).search(:base => treebase, :filter => filter) do |entry|
#puts "DN: #entry.dn"
entry.each do |attribute, values|
return values if attribute == :member
end
end
end

def get_sam(ldap_password)
samacc = Array.new
get_ldap_users(ldap_password).entries.eachelem
return samacc
end

end
end









share|improve this question


























    0















    So i have a bit of a pickle.
    I have an encrypted data bag to store LDAP passwords. In my node run list, one of my recipes installs the secret key onto my client machine.
    In my problematic cookbook, i have a helper (in /libraries) that pulls data from AD (using LDAP). Problem is, i can't find a way to delay the assignment of my node attribute after initial compile phase.



    Take this line of code as example :



    node.override['yp_chefserver']['osAdminUser'] = node['yp_chefserver']['osAdminUser'] + get_sam("#data_bag_item('yp_chefserver', 'ldap', IO.read('/etc/chef/secret/yp_chefserver'))['ldap_password']")


    Im trying to override an attribute by adding an array returned by my helper function "get_sam" which returns an array, but it needs to run AFTER the compile phase since the file "/etc/chef/secret/yp_chefserver" doesnt exist before the convergence of my runlist.



    So my question : Is there a way to assign node attributes via data_bag_items during the execution phase?



    Some things i've tried :



    ruby_block 'attribution' do
    only_if File.exist?('/etc/chef/secret/yp_chefserver')
    block do
    node.override['yp_chefserver']['osAdminUser'] = node['yp_chefserver']['osAdminUser'] + get_sam("#data_bag_item('yp_chefserver', 'ldap', IO.read('/etc/chef/secret/yp_chefserver'))['ldap_password']")
    Chef::Log.warn("content of osAdminUser : #node['yp_chefserver']['osAdminUser']")
    end
    end


    This doesn't work because the custom resource ruby_block doesn't have the method "data_bag_item". I've tried using lazy attributes in my "chef_server" custom resource, but same problem.



    I also tried having the attribution done directly in my helper module, but since the helper module compiles before the exec phase, the file doesn't exist when it assigns the variable.



    Here is the helper function in question should anyone wonder, it pulls the SamAccountName from LDAP to assign admin users to my chef server. :



    module YpChefserver
    module LDAP

    require 'net-ldap'
    @ldap

    def get_ldap(ldap_password)
    if @ldap.nil?
    @ldap = Net::LDAP.new :host => "ADSERVER",
    :port => 389,
    :auth =>
    :method => :simple,
    :username => "CN=USERNAME,OU=East Service Accounts,OU=System Accounts,DC=ad,DC=ypg,DC=com",
    :password => "#ldap_password"

    end
    @ldap
    end

    def get_ldap_users(ldap_password)
    filter = Net::LDAP::Filter.eq("cn", "DevOps")
    treebase = "dc=ad, dc=ypg, dc=com"
    get_ldap(ldap_password).search(:base => treebase, :filter => filter) do |entry|
    #puts "DN: #entry.dn"
    entry.each do |attribute, values|
    return values if attribute == :member
    end
    end
    end

    def get_sam(ldap_password)
    samacc = Array.new
    get_ldap_users(ldap_password).entries.eachelem
    return samacc
    end

    end
    end









    share|improve this question
























      0












      0








      0








      So i have a bit of a pickle.
      I have an encrypted data bag to store LDAP passwords. In my node run list, one of my recipes installs the secret key onto my client machine.
      In my problematic cookbook, i have a helper (in /libraries) that pulls data from AD (using LDAP). Problem is, i can't find a way to delay the assignment of my node attribute after initial compile phase.



      Take this line of code as example :



      node.override['yp_chefserver']['osAdminUser'] = node['yp_chefserver']['osAdminUser'] + get_sam("#data_bag_item('yp_chefserver', 'ldap', IO.read('/etc/chef/secret/yp_chefserver'))['ldap_password']")


      Im trying to override an attribute by adding an array returned by my helper function "get_sam" which returns an array, but it needs to run AFTER the compile phase since the file "/etc/chef/secret/yp_chefserver" doesnt exist before the convergence of my runlist.



      So my question : Is there a way to assign node attributes via data_bag_items during the execution phase?



      Some things i've tried :



      ruby_block 'attribution' do
      only_if File.exist?('/etc/chef/secret/yp_chefserver')
      block do
      node.override['yp_chefserver']['osAdminUser'] = node['yp_chefserver']['osAdminUser'] + get_sam("#data_bag_item('yp_chefserver', 'ldap', IO.read('/etc/chef/secret/yp_chefserver'))['ldap_password']")
      Chef::Log.warn("content of osAdminUser : #node['yp_chefserver']['osAdminUser']")
      end
      end


      This doesn't work because the custom resource ruby_block doesn't have the method "data_bag_item". I've tried using lazy attributes in my "chef_server" custom resource, but same problem.



      I also tried having the attribution done directly in my helper module, but since the helper module compiles before the exec phase, the file doesn't exist when it assigns the variable.



      Here is the helper function in question should anyone wonder, it pulls the SamAccountName from LDAP to assign admin users to my chef server. :



      module YpChefserver
      module LDAP

      require 'net-ldap'
      @ldap

      def get_ldap(ldap_password)
      if @ldap.nil?
      @ldap = Net::LDAP.new :host => "ADSERVER",
      :port => 389,
      :auth =>
      :method => :simple,
      :username => "CN=USERNAME,OU=East Service Accounts,OU=System Accounts,DC=ad,DC=ypg,DC=com",
      :password => "#ldap_password"

      end
      @ldap
      end

      def get_ldap_users(ldap_password)
      filter = Net::LDAP::Filter.eq("cn", "DevOps")
      treebase = "dc=ad, dc=ypg, dc=com"
      get_ldap(ldap_password).search(:base => treebase, :filter => filter) do |entry|
      #puts "DN: #entry.dn"
      entry.each do |attribute, values|
      return values if attribute == :member
      end
      end
      end

      def get_sam(ldap_password)
      samacc = Array.new
      get_ldap_users(ldap_password).entries.eachelem
      return samacc
      end

      end
      end









      share|improve this question














      So i have a bit of a pickle.
      I have an encrypted data bag to store LDAP passwords. In my node run list, one of my recipes installs the secret key onto my client machine.
      In my problematic cookbook, i have a helper (in /libraries) that pulls data from AD (using LDAP). Problem is, i can't find a way to delay the assignment of my node attribute after initial compile phase.



      Take this line of code as example :



      node.override['yp_chefserver']['osAdminUser'] = node['yp_chefserver']['osAdminUser'] + get_sam("#data_bag_item('yp_chefserver', 'ldap', IO.read('/etc/chef/secret/yp_chefserver'))['ldap_password']")


      Im trying to override an attribute by adding an array returned by my helper function "get_sam" which returns an array, but it needs to run AFTER the compile phase since the file "/etc/chef/secret/yp_chefserver" doesnt exist before the convergence of my runlist.



      So my question : Is there a way to assign node attributes via data_bag_items during the execution phase?



      Some things i've tried :



      ruby_block 'attribution' do
      only_if File.exist?('/etc/chef/secret/yp_chefserver')
      block do
      node.override['yp_chefserver']['osAdminUser'] = node['yp_chefserver']['osAdminUser'] + get_sam("#data_bag_item('yp_chefserver', 'ldap', IO.read('/etc/chef/secret/yp_chefserver'))['ldap_password']")
      Chef::Log.warn("content of osAdminUser : #node['yp_chefserver']['osAdminUser']")
      end
      end


      This doesn't work because the custom resource ruby_block doesn't have the method "data_bag_item". I've tried using lazy attributes in my "chef_server" custom resource, but same problem.



      I also tried having the attribution done directly in my helper module, but since the helper module compiles before the exec phase, the file doesn't exist when it assigns the variable.



      Here is the helper function in question should anyone wonder, it pulls the SamAccountName from LDAP to assign admin users to my chef server. :



      module YpChefserver
      module LDAP

      require 'net-ldap'
      @ldap

      def get_ldap(ldap_password)
      if @ldap.nil?
      @ldap = Net::LDAP.new :host => "ADSERVER",
      :port => 389,
      :auth =>
      :method => :simple,
      :username => "CN=USERNAME,OU=East Service Accounts,OU=System Accounts,DC=ad,DC=ypg,DC=com",
      :password => "#ldap_password"

      end
      @ldap
      end

      def get_ldap_users(ldap_password)
      filter = Net::LDAP::Filter.eq("cn", "DevOps")
      treebase = "dc=ad, dc=ypg, dc=com"
      get_ldap(ldap_password).search(:base => treebase, :filter => filter) do |entry|
      #puts "DN: #entry.dn"
      entry.each do |attribute, values|
      return values if attribute == :member
      end
      end
      end

      def get_sam(ldap_password)
      samacc = Array.new
      get_ldap_users(ldap_password).entries.eachelem
      return samacc
      end

      end
      end






      ruby chef databags






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 21 at 16:47









      DexirianDexirian

      1717




      1717






















          1 Answer
          1






          active

          oldest

          votes


















          0














          Turns out you can actually call it inside a ruby block, just by using the actual Chef call instead of the resource name, as follow :



          ruby_block 'attributes' do
          only_if File.exist?('/etc/chef/secret/yp_chefserver')
          block do
          dtbg = Chef::EncryptedDataBagItem.load('yp_chefserver','ldap',"IO.read('/etc/chef/secret/yp_chefserver')")
          end
          end


          Leaving this here for those who might need it



          EDIT :
          Here is final function using the code mentionned above to pull accounts from AD, using encrypted data bags to provide the password and to then pass those results to my node attributes, all during the execution phase :



          ruby_block 'attributes' do
          extend YpChefserver::LDAP
          only_if File.exist?('/etc/chef/secret/yp_chefserver')
          block do
          # Chef::Config[:encrypted_data_bag_secret] = '/etc/chef/secret/yp_chefserver'
          dtbg = Chef::EncryptedDataBagItem.load('yp_chefserver','ldap')
          node.override['yp_chefserver']['ldap_pw'] = dtbg['ldap_password']
          userarray = Array.new
          userarray.push("#node['yp_chefserver']['osAdminUser']")
          get_sam("#node['yp_chefserver']['ldap_pw']").each userarray.push(i[0])
          node.override['yp_chefserver']['authorized_users'] = userarray
          node.override['yp_chefserver']['local_admin_pw'] = dtbg['local_admin_pw']
          end
          end





          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285409%2fchef-delay-attribute-assignment-via-data-bag%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Turns out you can actually call it inside a ruby block, just by using the actual Chef call instead of the resource name, as follow :



            ruby_block 'attributes' do
            only_if File.exist?('/etc/chef/secret/yp_chefserver')
            block do
            dtbg = Chef::EncryptedDataBagItem.load('yp_chefserver','ldap',"IO.read('/etc/chef/secret/yp_chefserver')")
            end
            end


            Leaving this here for those who might need it



            EDIT :
            Here is final function using the code mentionned above to pull accounts from AD, using encrypted data bags to provide the password and to then pass those results to my node attributes, all during the execution phase :



            ruby_block 'attributes' do
            extend YpChefserver::LDAP
            only_if File.exist?('/etc/chef/secret/yp_chefserver')
            block do
            # Chef::Config[:encrypted_data_bag_secret] = '/etc/chef/secret/yp_chefserver'
            dtbg = Chef::EncryptedDataBagItem.load('yp_chefserver','ldap')
            node.override['yp_chefserver']['ldap_pw'] = dtbg['ldap_password']
            userarray = Array.new
            userarray.push("#node['yp_chefserver']['osAdminUser']")
            get_sam("#node['yp_chefserver']['ldap_pw']").each userarray.push(i[0])
            node.override['yp_chefserver']['authorized_users'] = userarray
            node.override['yp_chefserver']['local_admin_pw'] = dtbg['local_admin_pw']
            end
            end





            share|improve this answer





























              0














              Turns out you can actually call it inside a ruby block, just by using the actual Chef call instead of the resource name, as follow :



              ruby_block 'attributes' do
              only_if File.exist?('/etc/chef/secret/yp_chefserver')
              block do
              dtbg = Chef::EncryptedDataBagItem.load('yp_chefserver','ldap',"IO.read('/etc/chef/secret/yp_chefserver')")
              end
              end


              Leaving this here for those who might need it



              EDIT :
              Here is final function using the code mentionned above to pull accounts from AD, using encrypted data bags to provide the password and to then pass those results to my node attributes, all during the execution phase :



              ruby_block 'attributes' do
              extend YpChefserver::LDAP
              only_if File.exist?('/etc/chef/secret/yp_chefserver')
              block do
              # Chef::Config[:encrypted_data_bag_secret] = '/etc/chef/secret/yp_chefserver'
              dtbg = Chef::EncryptedDataBagItem.load('yp_chefserver','ldap')
              node.override['yp_chefserver']['ldap_pw'] = dtbg['ldap_password']
              userarray = Array.new
              userarray.push("#node['yp_chefserver']['osAdminUser']")
              get_sam("#node['yp_chefserver']['ldap_pw']").each userarray.push(i[0])
              node.override['yp_chefserver']['authorized_users'] = userarray
              node.override['yp_chefserver']['local_admin_pw'] = dtbg['local_admin_pw']
              end
              end





              share|improve this answer



























                0












                0








                0







                Turns out you can actually call it inside a ruby block, just by using the actual Chef call instead of the resource name, as follow :



                ruby_block 'attributes' do
                only_if File.exist?('/etc/chef/secret/yp_chefserver')
                block do
                dtbg = Chef::EncryptedDataBagItem.load('yp_chefserver','ldap',"IO.read('/etc/chef/secret/yp_chefserver')")
                end
                end


                Leaving this here for those who might need it



                EDIT :
                Here is final function using the code mentionned above to pull accounts from AD, using encrypted data bags to provide the password and to then pass those results to my node attributes, all during the execution phase :



                ruby_block 'attributes' do
                extend YpChefserver::LDAP
                only_if File.exist?('/etc/chef/secret/yp_chefserver')
                block do
                # Chef::Config[:encrypted_data_bag_secret] = '/etc/chef/secret/yp_chefserver'
                dtbg = Chef::EncryptedDataBagItem.load('yp_chefserver','ldap')
                node.override['yp_chefserver']['ldap_pw'] = dtbg['ldap_password']
                userarray = Array.new
                userarray.push("#node['yp_chefserver']['osAdminUser']")
                get_sam("#node['yp_chefserver']['ldap_pw']").each userarray.push(i[0])
                node.override['yp_chefserver']['authorized_users'] = userarray
                node.override['yp_chefserver']['local_admin_pw'] = dtbg['local_admin_pw']
                end
                end





                share|improve this answer















                Turns out you can actually call it inside a ruby block, just by using the actual Chef call instead of the resource name, as follow :



                ruby_block 'attributes' do
                only_if File.exist?('/etc/chef/secret/yp_chefserver')
                block do
                dtbg = Chef::EncryptedDataBagItem.load('yp_chefserver','ldap',"IO.read('/etc/chef/secret/yp_chefserver')")
                end
                end


                Leaving this here for those who might need it



                EDIT :
                Here is final function using the code mentionned above to pull accounts from AD, using encrypted data bags to provide the password and to then pass those results to my node attributes, all during the execution phase :



                ruby_block 'attributes' do
                extend YpChefserver::LDAP
                only_if File.exist?('/etc/chef/secret/yp_chefserver')
                block do
                # Chef::Config[:encrypted_data_bag_secret] = '/etc/chef/secret/yp_chefserver'
                dtbg = Chef::EncryptedDataBagItem.load('yp_chefserver','ldap')
                node.override['yp_chefserver']['ldap_pw'] = dtbg['ldap_password']
                userarray = Array.new
                userarray.push("#node['yp_chefserver']['osAdminUser']")
                get_sam("#node['yp_chefserver']['ldap_pw']").each userarray.push(i[0])
                node.override['yp_chefserver']['authorized_users'] = userarray
                node.override['yp_chefserver']['local_admin_pw'] = dtbg['local_admin_pw']
                end
                end






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 22 at 16:51

























                answered Mar 21 at 19:46









                DexirianDexirian

                1717




                1717





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285409%2fchef-delay-attribute-assignment-via-data-bag%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해