Terraform azurerm read current signed in user? - terraform-provider-azure

Looking at the documentation I am unable to find a data source which gives me
the current user (preferably the email) logged in to az when using the azurerm provider in terraform.
This information is available when I run az ad signed-in-user and I would like to use it to tag the resources created by terraform in azure.
Is this not possible right now?

You can use azurerm_client_config to get the AD object ID for the current user and then look up the returned object id with azuread_user to get the user principal name (UPN). Then, the UPN can be assigned to a tag. In the code below, outputs are not necessary but are helpful for validation because their values appear in the plan.
data "azurerm_client_config" "current" { }
data "azuread_user" "current_user" {
object_id = data.azurerm_client_config.current.object_id
}
resource "azurerm_resource_group" "example-rg" {
name = "example-rg"
location = "westus"
tags = {
userCreated = data.azuread_user.current_user.user_principal_name
}
}
output "object_id" {
value = data.azurerm_client_config.current.object_id
}
output "user_principal_name" {
value = data.azuread_user.current_user.user_principal_name
}

Related

how to exclude multiple zip code from adword campaign via script?

I am facing issue in google AdWords.
I want to exclude zip code from all campaign via a script, script applied on account for all campaign
function main() {
excludeLocationTarget();
}
function excludeLocationTarget() {
var campaignIterator = AdsApp.campaigns()
.withCondition('Name = "US-WooCommerce"')
.get();
if (campaignIterator.hasNext()) {
var campaign = campaignIterator.next();
// Exclude Tennessee, United States (location id = 21175) See
// https://developers.google.com/adwords/api/docs/appendix/geotargeting
// for list of all supported geo codes.
// You could pass either the location code, or a TargetedLocation or
// ExcludedLocation object from an existing campaign.
var tennessee_id =['21175','21176'];
for(val in tennessee_id){
Logger.log(tennessee_id[val]);
campaign.excludeLocation(tennessee_id[val]);
}
}
}
7/31/2019 11:45:44 PM 21175
7/31/2019 11:45:44 PM Invalid argument: id. Should be of type: number (file Code.gs, line 19)
excludeLocation method expects an integer argument and you're using string. that's why excludeLocation fails.
try
var tennessee_id =[21175,21176]; // numerical values instead of strings
for(val in tennessee_id){
Logger.log(tennessee_id[val]);
campaign.excludeLocation(tennessee_id[val]);
}
or campaign.excludeLocation(parseInt(tennessee_id[val]));

accessing Twitter API from Google Apps Script

I'm trying to read in a Google sheet my Twitter timeline.
I've copied the following code reported in the GAS documentation about twitter authentication (omitting step 2 since I'm not using the code inside a UI):
function getTwitterService() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth1.createService('twitter')
// Set the endpoint URLs.
.setAccessTokenUrl('https://api.twitter.com/oauth/access_token')
.setRequestTokenUrl('https://api.twitter.com/oauth/request_token')
.setAuthorizationUrl('https://api.twitter.com/oauth/authorize')
// Set the consumer key and secret.
.setConsumerKey('mykey')
.setConsumerSecret('mysecret')
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties());
}
function authCallback(request) {
var twitterService = getTwitterService();
var isAuthorized = twitterService.handleCallback(request);
if (isAuthorized) {
return Logger.log('Success! You can close this tab.');
} else {
return Logger.log('Denied. You can close this tab');
}
}
function makeRequest() {
var twitterService = getTwitterService();
var response = twitterService.fetch('https://api.twitter.com/1.1/statuses/user_timeline.json');
Logger.log(response);
}
but I obtain the message error: Service not authorized. (row 292, file "Service", project "OAuth1").
What's wrong?
I needed to add the following line the first time I execute makeRequest:
var authorizationUrl = twitterService.authorize();
Logger.log(authorizationUrl);
Then, open the url read from the log and authorize the app.
After that, all works fine.

How can i Pull Profile image from sharepoint

I'am new in API's & trying to pull user profile from sharepoint i use following code but don't know about servername? domainname? and username?
const string serverUrl = "http://sharepoint.com/";
const string targetUser = "ttgdev-my.sharepoint.com\\testuser1#ttgdev.guru";
// Connect to the client context.
ClientContext clientContext = new ClientContext(serverUrl);
// Get the PeopleManager object and then get the target user's properties.
PeopleManager peopleManager = new PeopleManager(clientContext);
PersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);
// Load the request and run it on the server.
// This example requests only the AccountName and UserProfileProperties
// properties of the personProperties object.
clientContext.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
clientContext.ExecuteQuery();
foreach (var property in personProperties.UserProfileProperties)
{
Console.WriteLine(string.Format("{0}: {1}",
property.Key.ToString(), property.Value.ToString()));
}
Console.ReadKey(false);
Please guide me it will give me the error in
{"The property or field 'UserProfileProperties' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."}
in the following line
clientContext.ExecuteQuery();
Most likely it is related with the format of targetUser variable. PeopleManager.GetPropertiesFor method expects accountName parameter to be specified in the proper format, in case of SharePoint Online it should be specified in claims format, for example:
i:0#.f|membership|jdow#contoso.onmicrosoft.com
For more details about Claims format follow this article.
So, in your case targetUser value should be replaced from ttgdev-my.sharepoint.com\\testuser1#ttgdev.guru to i:0#.f|membership|testuser1#ttgdev.guru
The following example demonstrates how to retrieve user profile picture via CSOM API:
using (var ctx = TokenHelper.GetClientContextWithAccessToken(webUri.ToString(), accessToken))
{
// Get the PeopleManager object and then get the target user's properties.
var peopleManager = new PeopleManager(ctx);
PersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);
//Retrieve picture property
var result = peopleManager.GetUserProfilePropertyFor(accountName, "PictureURL");
ctx.ExecuteQuery();
Console.WriteLine("Picture Url: {0}",result.Value);
}

Block IP address from Google adwords with their API

Does anyone know how to block certain IP addresses from our Google adwords account using the Google API?
In this article you can see how to do it manually, but I cannot find a way to do it programmatically.
I know it's late. But I needed it as well.
I found the IpBlock type on Google AdWords here.
Here is some sample code i found, and improved slightly
require_once this code, then make this call for each campaign u want to ban the IP for
YourNameSpace\BlockedIP::add($campaignId, $ip);
voila
<?php
/*
...
*/
namespace YourNameSpace;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\AdWords\v201802\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201802\cm\IpBlock;
use Google\AdsApi\AdWords\v201802\cm\NegativeCampaignCriterion;
use Google\AdsApi\AdWords\v201802\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201802\cm\Operator;
class BlockedIP {
public static function runExample(AdWordsServices $adWordsServices,
AdWordsSession $session,
$campaignId,
$ip) {
$campaignCriterionService =
$adWordsServices->get($session, CampaignCriterionService::class);
$campaignCriteria = [];
// Add a negative campaign criterion.
$ipBlock = new IpBlock();
$ipBlock->setIpAddress($ip);
$negativeCriterion = new NegativeCampaignCriterion();
$negativeCriterion->setCampaignId($campaignId);
$negativeCriterion->setCriterion($ipBlock);
$operation = new CampaignCriterionOperation();
$operation->setOperator(Operator::ADD);
$operation->setOperand($negativeCriterion);
$operations[] = $operation;
$result = $campaignCriterionService->mutate($operations);
// Print out some information about added campaign criteria.
foreach ($result->getValue() as $campaignCriterion) {
printf(
"Campaign targeting criterion with ID %d and type '%s' was added.\n",
$campaignCriterion->getCriterion()->getId(),
$campaignCriterion->getCriterion()->getType());
}
}
public static function add($campaignId, $ip) {
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile()
->build();
// Construct an API session configured from a properties file and the OAuth2
// credentials above.
$session = (new AdWordsSessionBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
self::runExample(new AdWordsServices(), $session, $campaignId, $ip);
}
}

google adwords api + getting all keywords

I'm using the google adwords api, I can retrieve all campaigns, group ads, ads,
but I have no idea on how to retrieve keywords related to an "group ads".
In the google adwords interface, when we select a group ads, we have two tabs, one for ads related to that group ads, and the second for keywords.
but programatily, right now I can only retrieve ads.
I'm using PHP, if some one knew how to do that in php or others programming languages or even a soap call.
To get the details of all the keywords of an adgroup you need the following to get the details of all the keywords.
require_once dirname(dirname(__FILE__)) . '/init.php';
// Enter parameters required by the code example.
$adGroupId = 'Enter your adgroup id';
/**
* Runs the example.
* #param AdWordsUser $user the user to run the example with
* #param string $adGroupId the id of the parent ad group
*/
function GetKeywordsExample(AdWordsUser $user, $adGroupId) {
// Get the service, which loads the required classes.
$adGroupCriterionService =
$user->GetService('AdGroupCriterionService', ADWORDS_VERSION);
// Create selector.
$selector = new Selector();
$selector->fields = array('KeywordText', 'KeywordMatchType', 'Id');
$selector->ordering[] = new OrderBy('KeywordText', 'ASCENDING');
// Create predicates.
$selector->predicates[] = new Predicate('AdGroupId', 'IN', array($adGroupId));
$selector->predicates[] =
new Predicate('CriteriaType', 'IN', array('KEYWORD'));
// Create paging controls.
$selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
do {
// Make the get request.
$page = $adGroupCriterionService->get($selector);
// Display results.
if (isset($page->entries)) {
foreach ($page->entries as $adGroupCriterion) {
printf("Keyword with text '%s', match type '%s', and ID '%s' was "
. "found.\n", $adGroupCriterion->criterion->text,
$adGroupCriterion->criterion->matchType,
$adGroupCriterion->criterion->id);
}
} else {
print "No keywords were found.\n";
}
// Advance the paging index.
$selector->paging->startIndex += AdWordsConstants::RECOMMENDED_PAGE_SIZE;
} while ($page->totalNumEntries > $selector->paging->startIndex);
}
// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
return;
}
try {
// Get AdWordsUser from credentials in "../auth.ini"
// relative to the AdWordsUser.php file's directory.
$user = new AdWordsUser();
// Log every SOAP XML request and response.
$user->LogAll();
// Run the example.
GetKeywordsExample($user, $adGroupId);
} catch (Exception $e) {
printf("An error has occurred: %s\n", $e->getMessage());
}
In the Adwords API Keywords are dubbed as AdGroup Criteria. You can add or retrieve the keywords for a certain AdGroup by using the AdGroupCriterionService.
If you're using the PHP client library of the Adwords API check out GetAllAdGroupCriteria.php in the example files. (don't forget to enter the AdGroupId you want to get the keywords for first)

Resources