Search code examples
bashazureautomationazure-active-directory

Set up a Service principle to a AAD group by Bash Scripting


I need a Help to solve it by bash Scripting . Have a look a condition for Script :

I have a bash Script where i put the group id & list of Service Principle to that group & it works fine & ok but i want to modify that Script to like below:

  1. Script want to ask me what group you to insert here > " Put in the Group Id or Name"
  2. Script want to ask me what Service Principle you to insert to that group > "Put the Service Principle name or ID"
  3. Paste my Whole below :

groupId="ff9cf2bd-38d5-49ab-af7a-3ac4f7fba81a" sp_list=("emran-test-demo-03" "emran-test-demo-04" "TurbonomicSP")

for sp_name in "${sp_list[@]}" do spObjId=$(az ad sp list --display-name "$sp_name" --query '[0].id' --output tsv)

if [ -n "$spObjId" ]; then
    az ad group member add --group $groupId --member-id $spObjId
    if [ $? -eq 0 ]; then
        echo "Service Principal with Name: $sp_name (Object ID: $spObjId) added to AAD Group successfully."
    else
        echo "Failed to add Service Principal with Name: $sp_name (Object ID: $spObjId) to AAD Group."
    fi
else
    echo "Service Principal with Name: $sp_name not found."
fi

done

Please someone come to help me .

Emmi


Solution

  • To prompt the script for the user input, modify the script like below:

    # Prompt for the Group ID
    read -p "Enter the Group ID or Name: " groupId
    
    # Prompt for the Service Principals
    read -p "Enter the Service Principals (separated by spaces): " -a sp_list
    
    for sp_name in "${sp_list[@]}"; do
        spObjId=$(az ad sp list --display-name "$sp_name" --query '[0].id' --output tsv)
    
        if [ -n "$spObjId" ]; then
            az ad group member add --group $groupId --member-id $spObjId
            if [ $? -eq 0 ]; then
                echo "Service Principal with Name: $sp_name (Object ID: $spObjId) added to AAD Group successfully."
            else
                echo "Failed to add Service Principal with Name: $sp_name (Object ID: $spObjId) to AAD Group."
            fi
        else
            echo "Service Principal with Name: $sp_name not found."
        fi
    done
    

    enter image description here

    The Service Principals added successfully to the group like below:

    enter image description here